$(window).on("scroll", function() {
    if($(window).scrollTop() > 100) {
        $(".header-bottom").addClass("animate__animated animate__fadeInDown fixed-top");
    } else {
        //remove the background property so it comes transparent again (defined in your css)
       $(".header-bottom").removeClass("animate__animated animate__fadeInDown fixed-top");
    }
});


function showHidePassword(){
    const togglePassword = document.querySelector('#togglePassword');
    const togglePassword2 = document.querySelector('#togglePassword2');
    const password = document.querySelector('#password');
    const password_verif = document.querySelector('#password_verif');

    togglePassword.addEventListener('click', function (e) {
        // toggle the type attribute
        const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
        
        password.setAttribute('type', type);
        password_verif.setAttribute('type',type2);
        // toggle the eye slash icon
        this.classList.toggle('fa-eye-slash');
    });

    togglePassword2.addEventListener('click', function (e) {
        // toggle the type attribute
        const type2 = password_verif.getAttribute('type') === 'password' ? 'text' : 'password';
        
        password_verif.setAttribute('type',type2);
        // toggle the eye slash icon
        this.classList.toggle('fa-eye-slash');
    });
}

function showHidePassword2(){
    const togglePassword = document.querySelector('#showHide');
    const password = document.querySelector('#passworduser');
    

    togglePassword.addEventListener('click', function (e) {
        // toggle the type attribute
        const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
        
        password.setAttribute('type', type);
        // toggle the eye slash icon
        this.classList.toggle('fa-eye-slash');
    });

}

function changePrice(){

    $('select#change_size').change(function(){

        var price = $('option:selected', this).attr('data-price')
        var size = $(this).val()
        $('#price_bottom').html(new Intl.NumberFormat().format(price)+' fcfa')
        $('#price_top').html(new Intl.NumberFormat().format(price)+' fcfa')
        $('#size').val(size)
        $('#price').val(price)

        //alert(price)

    })

}

function AddToFavoris(){
    $('#addtofavoris').click(function(e){
        e.preventDefault()
        var id = $(this).attr('data-id')
        AjaxLoading("fonctions/ajax_navigation.php","op=favoris&id="+id+"","#favadd"); 

    })
}

function changeAlbumBySize(){

    //console.log('ok')

    var url = "fonctions/ajax_navigation.php?op=size"
    var remise = $("#remiseProd").val()

    if($('select#change_size option:selected')){

        var id = $('select#change_size').find(':selected').attr('data-id')

        var code_prod = $('select#change_size').find(':selected').attr('data-code')
        $('#size').val($('select#change_size').find(':selected').val())


        //console.log(id)
        

        if(id != '' && id != undefined){

            data = {"id":id}

            AjaxLoading("fonctions/ajax_navigation.php","op=album&id="+id+"&code_prod="+code_prod+"","#changeAlbum"); 

            $.ajax({
            type : "POST",
            url  : url,
            data : data,

            beforeSend : function(){
                //$(container).append('<div class="loader_c"></div>');
                //$('<div id="loader"><div class="lds-ring"><div></div><div></div></div></div>').appendTo('.message-ctn');
                //alert('chargement en cours...');
            },
            success : function(response){
                //console.log(response)
                response = JSON.parse(response)
                
                var html = ''
                html += '<h4 class="lib_ep">Epaisseurs en cm</h4>'
                html += '<ul class="epaisseur">'
                for(let i in response){
                    html += '<li><a href="#" id="epaisseur'+i+'" class="'+(i==0?"selected":"")+'" data-price="'+response[i]['price']+'" id="epaisseur_'+response[i]['epaisseur']+'" data-size="'+response[i]['epaisseur']+'">'+response[i]['epaisseur']+'</a></li>'

                }
                html += '</ul>'
                $('#epaisseur').html(html)
                
                $('ul.epaisseur > li > a').click(function(e){
                    e.preventDefault()

                    var epaisseur = $(this).attr('data-size')
                    var price = $(this).attr('data-price')
                    var remisePrice = parseInt(price-((price*remise)/100))
                    $('ul.epaisseur > li > a').removeClass('selected')
                    $(this).addClass('selected')

                    $('#price_bottom').html(new Intl.NumberFormat().format(price)+' FCFA')
                    $('#price_top').html(new Intl.NumberFormat().format(price)+' FCFA')
                    var priceProd = remise ? remisePrice : price
                      $('#price').val(priceProd)
                    $('#epaisseur_value').val(epaisseur)
                })
                $('ul.epaisseur > li > a.selected').trigger('click')
                        
            },
            complete : function(){
                $('.loader_c').remove();
            }
        });

        }

    }

    $('select#change_size').change(function(){

        var id = $('option:selected', this).attr('data-id')

        console.log(id)
        

        if(id != '' && id != undefined){

            data = {"id":id}

            AjaxLoading("fonctions/ajax_navigation.php","op=album&id="+id+"","#changeAlbum"); 

            $.ajax({
            type : "POST",
            url  : url,
            data : data,

            beforeSend : function(){
                //$(container).append('<div class="loader_c"></div>');
                //$('<div id="loader"><div class="lds-ring"><div></div><div></div></div></div>').appendTo('.message-ctn');
                //alert('chargement en cours...');
            },
            success : function(response){
                //console.log(response)
                response = JSON.parse(response)
                
                var html = ''
                html += '<ul class="epaisseur">'
                for(let i in response){
                    html += '<li><a href="#"  id="epaisseur'+i+'" class="'+(i==0?"selected":"")+'" data-price="'+response[i]['price']+'" id="epaisseur_'+response[i]['epaisseur']+'" data-size="'+response[i]['epaisseur']+'">'+response[i]['epaisseur']+'</a></li>'
                }
                html += '</ul>'
                $('#epaisseur').html(html)
                $('ul.epaisseur > li > a').click(function(e){
                    e.preventDefault()

                    var epaisseur = $(this).attr('data-size')
                    var price = $(this).attr('data-price')
                    $('ul.epaisseur > li > a').removeClass('selected')
                    $(this).addClass('selected')

                    $('#price_bottom').html(new Intl.NumberFormat().format(price)+' fcfa')
                    $('#price_top').html(new Intl.NumberFormat().format(price)+' fcfa')
                    $('#epaisseur_value').val(epaisseur)
                })
                $('ul.epaisseur > li > a.selected').trigger('click')
                        
            },
            complete : function(){
                $('.loader_c').remove();
            }
        });

        }

    })   
}

function changeColor(){

    $('select#change_color').change(function(){

        var size = $(this).val()
        $('#color').val(size)

    })

}

function choiceColor(){

    $('ul.couleur > li > a').click(function(e){
        e.preventDefault()

        var id = $(this).attr('data-id')
        var color = $(this).attr('data-color')
        $('ul.couleur > li > a').removeClass('selected')
        $(this).addClass('selected')
        $('#color').val(color)
    })
}

function changeCurtain(){

    $('select#change_material').change(function(){

        var size = $(this).val()
        $('#curtain').val(size)

    })

}

function change_panier_qty(){

    $('input[type=number]').change(function(){
        var id = $(this).attr('id');
        var quantite = $(this).val();
        var prix = $(this).attr('data-p');
        var droits = $(this).attr('data-droits');
        var code_cmde = $(this).attr('data-cmde');
        AjaxLoading("fonctions/ajax_navigation.php","op=chge_qty&produit="+id+"&quantite="+quantite+"&prix="+prix+"&droits="+droits+"&code_cmde="+code_cmde+"","#panier_c");  

    })
   
}

function confirmAchat(){

    var montant = $('#montant').val()

    var url = "fonctions/ajax_navigation.php?op=transport"

    $('#change_paiement').on('change', function(e){
        var lieu = $(this).val()
        var transport = $(this).find(':selected').data('transport')
        var prix_transport = 1000

        if(lieu == 1){
            $('#commune_input').removeClass('hidden')
            $('#adresse').attr('placeholder', 'Sasir votre adresse')
        }else{
            $('#commune_input').addClass('hidden')
            $('#adresse').attr('placeholder', 'Sasir votre ville')
        }

        if(lieu == 2){

            $.ajax({
                type : "GET",
                url  : url,

                beforeSend : function(){
                    //$(container).append('<div class="loader_c"></div>');
                    //$('<div id="loader"><div class="lds-ring"><div></div><div></div></div></div>').appendTo('.message-ctn');
                    //alert('chargement en cours...');
                },
                success : function(response){
                    console.log(response)
                    response = JSON.parse(response)
                   // console.log(response['other'])
                    if(response['other'] != null){
                        let k=0
                        for(let i in response['other']){
                            
                            if(response['other'][i] != null && response['count'] != null){
                                //console.log(response['other'][i])
                                //console.log(k)
                                //if(k==0){
                                    //var total_transport = ((parseInt(transport)*parseInt(response['count']))+(parseInt(response['other'][i])*1000))
                                    var total_transport = ((parseInt(transport)*parseInt(response['count'])))
                                /*}else{
                                    var total_transport = ((parseInt(transport)*parseInt(response['count']))+(1000*parseInt(k)))
                                }*/
    
                                
                                console.log(total_transport)
                                $('#mode_paiement').val(total_transport)
                                $('#transport').html(total_transport.toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
                                $('#ttc').html((parseInt(total_transport)+parseInt(montant)).toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))

                            }else if(response['other'][i] != null && response['count'] == null){

                                //console.log(k)
                                if(k==0){
                                    var total_transport = transport
                                }else{
                                    var total_transport = transport
                                }

                                
                               // console.log(total_transport)
                                $('#mode_paiement').val(total_transport)
                                $('#transport').html(total_transport.toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
                                $('#ttc').html((parseInt(total_transport)+parseInt(montant)).toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))

                            }else if(response['count'] != null && response['other']['oreillers'] != null){

                                response['other'].splice("oreillers")

                                //console.log(response['other'])

                                var total_transport = ((parseInt(transport)*parseInt(response['count'])))

                                //console.log(total_transport)
                                
                                
                               // console.log(total_transport)
                                $('#mode_paiement').val(total_transport)
                                $('#transport').html(total_transport.toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
                                $('#ttc').html((parseInt(total_transport)+parseInt(montant)).toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))

                            }
                            k++
                        }
                        
                    }else{
                        var total_transport = (parseInt(transport)*parseInt(response['count']))
                        //console.log(total_transport)
                        $('#mode_paiement').val(total_transport)
                        $('#transport').html(total_transport.toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
                        $('#ttc').html((parseInt(total_transport)+parseInt(montant)).toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
                    }
                    
                    //console.log(response)
                            
                },
                complete : function(){
                    $('.loader_c').remove();
                }
            })

        }
        else{
            $('#mode_paiement').val(transport)
            $('#transport').html(transport.toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
            $('#ttc').html((parseInt(transport)+parseInt(montant)).toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
        }

        

        /*$('#mode_paiement').val(transport)
        $('#transport').html(transport.toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))
        $('#ttc').html((parseInt(transport)+parseInt(montant)).toLocaleString("fr-FR",{style:'currency', currency:"XOF"}))*/
        //$('#montant').val()


    })

    $('#confirm').on('click', function(e){
        e.preventDefault()

        var form = document.querySelector('#formAchat')

        

        if(form.checkValidity()){
            //e.stopPropagation()
            
            var montant = $('#montant').val()
            var currency = $('#currency').val()
            var adresse = $('#adresse').val()
            var contact_livraison = $('#contact_liv').val()
            var contact_livraison_2 = $('#contact_liv_2').val()
            var mode_paiement = $('#mode_paiement').val()
            var transport = $('#mode_paiement').val()
            var commune = $('#commune').val()
            //console.log(montant+'_'+currency)
            
            AjaxLoading("fonctions/ajax_navigation.php","op=paiement&montant="+montant+"&currency="+currency+"&adresse="+adresse+"&__mode_paiement__="+mode_paiement+"&transport="+mode_paiement+"&contact_liv="+contact_livraison+"&contact_liv_2="+contact_livraison_2+"&commune="+commune+"","#panier_c");
        }
        form.classList.add('was-validated')

        
    })
}

function paiement(){

    if($('#validAchat').length){
        $('#validAchat').on('click', function(e){
            //alert('ok')
            e.preventDefault()
            var montant = $('#montant').val()
            var adresse = $('#adresse').val()
            var transport = $('#transport').val()
            var contact_liv = $('#contact_liv').val()
            var contact_liv_2 = $('#contact_liv_2').val()
            var commune = $('#commune').val()
            AjaxLoading("fonctions/ajax_navigation.php","op=achat&montant="+montant+"&adresse="+adresse+"&transport="+transport+"&contact_liv="+contact_liv+"&contact_liv_2="+contact_liv_2+"&commune="+commune+"","#panier_c");

        })
    }

}


function submitSearch(){

    if($('#btn_search').length){


        $('#btn_search').on('click', function(e){
            e.preventDefault()

            var item = $('#search').val()

            console.log(item)

            AjaxLoading("fonctions/ajax_navigation.php","op=search&item="+item+"","#search-container");
        })
    }
}

function submitComment(container, nom_form){

    if($('#submitComment').length){
        $('#submitComment').on('click', function(e){
            e.preventDefault()

            return formSubmit2(container+ ' form#'+nom_form, "op=comment", container);


        })
    }

}



function addToBasket(){

    $('a#addToBasket').on('click', function(e){
        e.preventDefault()
        var qte = $('#qte').val()
        var price = $('#price').val()
        var product = $('#product').val()
        var size = $('#size').val()
        var color = $('#color').val()
        var curtain = $('#curtain').val()
        var epaisseur = $('#epaisseur_value').val()
        var code_cat = $('#code_cat').val()
        var url = 'fonctions/ajax_navigation.php?op=ajout'
        var data = {
            "code":product,
            "quantite":qte,
            "prix":price,
            "size":size,
            "color":color,
            "matiere":curtain,
            "epaisseur":epaisseur,
            "code_cat":code_cat,
        }
        var html = ''
        $('#overlayer-container').addClass('show-ctn')
       $.ajax({
            type : "POST",
            url  : url,
            data : data,

            beforeSend : function(){
                //$(container).append('<div class="loader_c"></div>');
                $('<div id="loader"><div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div></div>').appendTo('.message-ctn');
                //alert('chargement en cours...');
            },
            success : function(response){
                response = JSON.parse(response)

                    
                    //console.log(response['code'])
                    
                        
                    if(response['code'] == 1){

                        html += '<div class="success">'
                            html += '<span>Ce produit a été ajouté à votre panier avec succès.</span>'
                        html += '</div>'
                        $(".nav-icon  .nbre").html(response['nbre'])
                        $('.message-ctn').html(html)

                    }else{

                    }
                    
                    
                
                
                
            },
            complete : function(){
                $('.loader_c').remove();
            }
        });

       setTimeout(function(){
            $('#overlayer-container').removeClass('show-ctn')
        },1500);

        //AjaxLoading2("fonctions/ajax_navigation.php","op=ajout&code="+product+"&quantite="+qte+"&prix="+price+"&size="+size+"&color="+color+"&matiere="+curtain+"&__type__=2","#list_produit");  

    })
   
}

function slideAlbum(){

    $('.slider-for').slick({
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: false,
      fade: true,
      asNavFor: '.slider-nav'
    });
    $('.slider-nav').slick({
      slidesToShow: 3,
      slidesToScroll: 1,
      asNavFor: '.slider-for',
      dots: false,
      centerMode: true,
      focusOnSelect: true,
      prevArrow:'<span class="slick-prev"><i class="fa-solid fa-chevron-left"></i></span>',
      nextArrow:'<span class="slick-next"><i class="fa-solid fa-chevron-right"></i></span>',
    });

}

$(document).ready(function(){

    //show map modal

    if($('#boutique').length){
        $('.collapse').each(function(){
            var id = $(this).data('id')
            $('#shopMap'+id).on('click', function(){
                var libelle = $(this).data('libelle')
                var lat = $(this).data('lat')
                var long = $(this).data('long')
                var map = $(this).data('map')
                 $('#mapModal .modal-title').html('CIL '+libelle)
                 $('#mapModal .modal-body').html(map)
            })
        })
    }

   /* $('#shopMap').off().on('click',function(){
        var libelle = $(this).data('libelle')
        $('#mapModal .modal-title').html(libelle)
    })*/

    $('#longueur').on('change mousemove', function(){
        
        var long = $(this).val()
        $('#lg_val').html(long)
        $('#longueur_value').val(long)
    })

    $('#largeur').on('change mousemove', function(){
        
        var long = $(this).val()
        $('#larg_val').html(long)
        $('#largeur_value').val(long)
    })

    /*$('#epaisseur').on('change mousemove', function(){
        
        var long = $(this).val()
        $('#ep_val').html(long)
        $('#epaisseur_value').val(long)
    })*/

    $('#couleur').spectrum({
        type: "component"
    });

    $('ul.epaisseur > li > a').click(function(e){
        e.preventDefault()

        var epaisseur = $(this).attr('data-size')
        var price = $(this).attr('data-price')
        $('ul.epaisseur > li > a i').removeClass('selected')
        $(this).addClass('selected')

        $('#price_bottom').html(new Intl.NumberFormat().format(price)+' fcfa')
        $('#price_top').html(new Intl.NumberFormat().format(price)+' fcfa')
        $('#epaisseur_value').val(epaisseur)
    })

    /*$('.rating ul > li > a').click(function(e){
        e.preventDefault()
        //alert('ok')
        var i = 0
        var note = $(this).attr('data-value')
        $('.rating ul > li > a i', this).removeClass('fa-solid')
        $('i',this).addClass('fa-solid')

       
        $('#note').val(note)
    })*/

    $('[type*="radio"]').change(function () {
        var me = $(this);
        $('#note').val(me.attr('value'))
        //log.html(me.attr('value'));
    });

    $('.slider .owl-carousel').owlCarousel({
        loop:true,
        dots:true,
        nav:true,
        video:true,
        autoplay:true,
        lazyLoad:true,
        mouseDrag:false,
        autoplay:true,
        autoplayTimeout:15000,
        animateOut: 'animate__slideOutLeft',
        animateIn: 'animate__slideInLeft',
        navText:['<i class="fa-solid fa-chevron-left"></i>','<i class="fa-solid fa-chevron-right"></i>'],
        responsive:{
            0:{
                items:1
            },
            600:{
                items:1
            },
            1000:{
                items:1
            }
        }
    });

    $('#product .owl-carousel').owlCarousel({
        loop:true,
        margin:20,
        dots:false,
        nav:true,
        mouseDrag:false,
        autoplay:false,
        animateOut: 'animate__slideOutLeft',
        animateIn: 'animate__slideInLeft',
        smartSpeed: 2000,
        navText:['<i class="fa-solid fa-chevron-left"></i>','<i class="fa-solid fa-chevron-right"></i>'],
        responsive:{
            0:{
                items:1
            },
            600:{
                items:1
            },
            1000:{
                items:4
            }
        }
    });

    $('#bonplan .owl-carousel').owlCarousel({
        loop:true,
        margin:20,
        dots:false,
        nav:true,
        mouseDrag:false,
        autoplay:true,
        animateOut: 'animate__slideOutLeft',
        animateIn: 'animate__slideInLeft',
        smartSpeed: 2000,
        navText:['<i class="fa-solid fa-chevron-left"></i>','<i class="fa-solid fa-chevron-right"></i>'],
        responsive:{
            0:{
                items:1
            },
            600:{
                items:1
            },
            1000:{
                items:4
            }
        }
    });

    $('#slide-video .owl-carousel').owlCarousel({
        loop:true,
        margin:20,
        dots:false,
        nav:true,
        mouseDrag:false,
        autoplay:true,
        animateOut: 'animate__slideOutLeft',
        animateIn: 'animate__slideInLeft',
        smartSpeed: 3500,
        navText:['<i class="fa-solid fa-chevron-left"></i>','<i class="fa-solid fa-chevron-right"></i>'],
        responsive:{
            0:{
                items:1
            },
            600:{
                items:1
            },
            1000:{
                items:4
            }
        }
    });

    if($('.responsive-menu-show').length){
        $('.responsive-menu-show').on('click', function(e){
            e.preventDefault()
           
            $('.responsive-menu').addClass('left')

            //$('.responsive-menu').css('left', '0')

        })

        $('.close').on('click', function(e){
            e.preventDefault()
             $('.responsive-menu').removeClass('left')
        })
    }

})