var loader_is_showed = false
var g_rc = false
function recaptchaOK() {
    g_rc=true
    $(".invalid-grc-feedback").hide()
};
function recaptchaKO() {
    g_rc=false
};
function showLoader(text=null){
    if(!loader_is_showed){
        loader_is_showed=true
        if(text!==null){
         $(".loader-text").html(text)
        }else{
            $(".loader-text").html("")
        }
        $(".loader-wrapper").fadeIn("slow", function () {
            
        });
    }
}
function hideLoader(){
    if(loader_is_showed){
        loader_is_showed=false
        $(".loader-wrapper").fadeOut("slow", function () {
            $(".loader-text").html("")
        });
    }
    
}
function checkForm(form, type){
    //dichiaro i campi del form dal controllare. 
    // type 1 verifico che i campi siano stati compilati correttamente
    // type 2 rimuovo i messaggi di errore

    //variabile per il check delle email
    const inputs = form.querySelectorAll('.form-register:required')
    inputToCheck = inputs, label_recaptcha = form.querySelector('.error-label.for-g-recaptcha');
    const validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
    const regNumber = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;    
    let validation = false, error = 0, field_error = [];
    
    inputToCheck.forEach((item) => {
        if(type == '1'){
            if (item.type == 'email') {
                if (item.value.match(validRegex))
                    validation = true;
                else
                    validation = false;        
            } else if (item.type == 'tel') {
                if (item.value.match(regNumber)) 
                    validation = true;
                else
                    validation = false;
            } else if (item.type == 'checkbox') {
                if (item.checked) 
                    validation = true;
                else
                    validation = false;
            } else {
                if (item.value == '')
                    validation = false;
                else
                    validation = true;
            }            
            
            if(validation === false){
                item.parentNode.querySelector('.error-label').classList.remove('d-none');
                error ++;
                field_error.push(item.name);
            }else
                item.parentNode.querySelector('.error-label').classList.add('d-none');            
        }else if(type == '2'){
            let event_input;
            if(item.type == 'checkbox' || item.tagName.toLowerCase() == 'select')
                event_input = 'change';
            else
                event_input = 'keydown';
            
            item.addEventListener(event_input, (e) => {
                item.parentNode.querySelector('.error-label').classList.add('d-none');
            });
        }
    });     
//    if(type == '1'){
//       console.log('--->', grecaptcha.getResponse());
//        if(grecaptcha.getResponse().length == 0){
//            label_recaptcha.classList.remove('d-none');
//            error ++;
//            field_error.push('recaptcha');
//        }
//        console.log(field_error);
//        return error;
//    }
}
function validationForm(form,google_rc=false){
    form.addEventListener('submit', function (event) {
        if(google_rc){
            if (!form.checkValidity() || !g_rc) {
                event.preventDefault()
                event.stopPropagation()
              }
        }else{
            if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
              }
        }
        if(google_rc){
            if(!g_rc){
               $(".invalid-grc-feedback").show()
            }else{
                $(".invalid-grc-feedback").hide()
            }
        }
        form.classList.add('was-validated')
      }, false)
}
function openDrop(dd,arrow){
    
  document.querySelector('.'+dd).classList.toggle('d-none');    
  document.querySelector('.'+arrow).classList.toggle('rotate');
}

function rotateArrow(el){
    el.childNodes[1].classList.toggle('rotate')

}

//START ACCORDION FOOTER 
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");

    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
} 
//END ACCORDION FOOTER
custom_js = {
    cookie_settings:function(){
        $(document).on('click','.popup-cookie .content .list-cookies>li>.status-cookie-item .switch-option',function(){
           var item = $(this),
           text_inactive = item.data('text-inactive'),
           text_active = item.data('text-active');

           if(item.children('input').is(':checked')){
              item.children('input').prop('checked',false).parent('div').removeClass('on'); 
              item.siblings('p').text(text_inactive);
           }else{
              item.children('input').prop('checked',true).parent('div').addClass('on');        
              item.siblings('p').text(text_active);
           }
        });
        $(document).on('click','.popup-cookie .content .list-cookies>li>a',function(e){
            e.preventDefault()
            var item = $(this);
            if(item.siblings('ul').hasClass('visible')){
               item.siblings('ul').removeClass('visible');
               item.children('i').attr('class','fa fa-angle-right');
            }else{
               item.siblings('ul').addClass('visible');
               item.children('i').attr('class','fa fa-angle-down');
            }
        });

        $(document).on('click','.popup-cookie .inner-popup>a',function(e){
            e.preventDefault();
            $(this).parent('div').parent('div').removeClass('active');
        });

        $(document).on('click','.settings-cookie-opener, footer .open-settings-cookie, .footer-privacy-menu li:last-of-type>a',function(e){
            e.preventDefault();
            $('.popup-cookie').addClass('active');
        });

        $(document).on('click','.cookie-bar .buttons-container>a.accept-all',function(e){
            e.preventDefault();
            $.ajax({
                url: "ajxrq/query.php",
                type: "post",
                data: {
                    task: 'accetta_tutti_cookie',
                },
                dataType : 'json',
                success: function(result){
                    $('.cookie-bar').removeClass('active');
                    //setTimeout(function (){ window.location.reload(); },500);
                },
                error:function(result){
                    console.log('There is error while adding');
                }                           
            });                  
        });

        $(document).on('click','.popup-cookie .inner-popup .buttons-container > a.save-settings-cookie',function(e){
            e.preventDefault();
            var popup = $('.popup-cookie'),i,array_fields, array_results = [],
            input = popup.find('input.checkbox-cookie');
            if(input.length>0){
                for(i=0;i<input.length;i++){
                    array_fields = input.eq(i).attr('name').split('_');            
                    array_results[i] = ((input.eq(i).is(':checked')))?array_fields[1]+'_1':array_fields[1]+'_0';
                }
            }
            var obj = JSON.stringify(array_results);
            $.ajax({
                url: "ajxrq/query.php",
                type: "post",
                data: {
                    task: 'salva_preferenze_cookie',
                    results: obj,
                },
                dataType : 'json',
                success: function(result){
                    $('.cookie-bar').removeClass('active');
                    popup.removeClass('active');
                    //setTimeout(function (){ window.location.reload(); },500);
                },
                error:function(result){
                    console.log('There is error while adding');
                }
            });    
        });

        $(document).on('click','.cookie-bar .buttons-container>a.reject-all',function(e){
            e.preventDefault();
            $.ajax({
                url: "ajxrq/query.php",
                type: "post",
                data: {
                    //task: 'rifiuta_tutti_cookie',
                    task: 'accetta_tutti_cookie',
                },
                dataType : 'json',
                success: function(result){
                    $('.cookie-bar').removeClass('active');
                },
                error:function(result){
                    console.log('There is error while adding');
                }
            });       
        });
    },

   
    init:function(){
        if($('.popup-newsletter').length > 0){
            $('.popup-newsletter .close').on('click', function(e){
                e.preventDefault();
                $('.popup-newsletter').removeClass('open');
            });
            setTimeout(function(){
                $('.popup-newsletter').addClass('open');
            },5000);
        }
        /*CONST - START*/
        const listCountries = document.querySelector('.countries-list'), /*da utilizzare per il cambio nazione spedizione*/
        body = document.querySelector('body'),
        offcanvasBtn = document.getElementById('offcanvas-hamburger'),
        offcanvasCloseBtn = document.querySelector('.close-btn-offcanvas'),
        asideMenu = document.getElementById('menu'),
        input_search_country = document.querySelector('input[name=search_country]');        
        /*CONST - END*/
        
        listCountries.addEventListener( "click", (e)=>{
            let element = e.target;            
            if(element.parentNode.getAttribute("class").includes("country-item")){
                window.location.replace(element.parentNode.getAttribute('data-href'));                
            }
            
        });
        
        input_search_country.addEventListener("keyup", (e)=>{
            let word = e.target.value.toLowerCase();            
            listCountries.querySelectorAll('li').forEach(function(item){
                let countryName = item.children[0].textContent.trim().toLowerCase();
                console.log(word.length);
                if(word.length >= 3){
                    //console.log('==>', countryName+' '+word);
                    if(countryName.includes(word)){
                        item.classList.remove('d-none');
                        item.classList.add('d-flex');
                    }else{
                        item.classList.remove('d-flex');
                        item.classList.add('d-none');
                    }
                }else{
                    item.classList.remove('d-none');
                    item.classList.add('d-flex');
                }
            });
        });
        
        $(document).on('click', '.carrello-prodotti .elimina-prodotto', function (e) {
            showLoader()
            e.preventDefault();
            var item = $(this),
            lang = $('html').attr('lang'),
            id = item.attr("href").replace('#',''),
            datapost = "task=cart_del&prodottoID=" + id;
            //alert("pippo");  
            $.ajax({
                url: "/ajxrq/cart_2023.php",
                type: "post",
                data: datapost,
                dataType: 'json',
                success: function (result) {
                    $('.carrello-prodotti').html(result.cart);
                    $("#cart_header_number").html(result.qta);
                    $(".cart_header_number_gen, .cart_header_number_gen_mob").html(result.qta_header);
                    $("#cart_header_euro").html(result.totale);
                    hideLoader()
                },
                error: function () {
                    console.log('There is error while deleting');
                    hideLoader()
                }
            });

        });
        $(document).on('click', '.open-cart', function (e) {
            e.preventDefault();
            $('.container-laterale.container-carrello').addClass('active');
            $('body').addClass('overflow-hidden');
        });
        $(document).on('click', '.close-cart-header', function (e) {
            e.preventDefault();
            $('.container-laterale.container-carrello').removeClass('active');
            $('body').removeClass('overflow-hidden');
        });

        // offcanvas logo toggle        
        document.addEventListener('click', event => {
            if (asideMenu.classList.contains('show')) {
                const isInside = asideMenu.contains(event.target);

                if (!isInside) {
                    logo.classList.remove('hidden');
                }
            }
        });



// offcanvas logo toggle
        $(document).on('click', '.popup-language > .content button', function (e) {
            e.preventDefault();
            closePopup();
        });
        $(document).on('click', '.backdrop', function (e) {
            e.preventDefault();
            closePopup();
        });
        $(document).on('click', '.toogle-languages', function (e) {
            e.preventDefault();
            $('.popup-language').addClass('visible');
            $('.backdrop').addClass('d-block');
        });
        /*
        $(document).on('keyup', 'input[name=search_country]', function () {
            var item = $(this), word = item.val(), page_it = item.data('page-it'), page_en = item.data('page-en');
            
            $.ajax({
                url: "/ajxrq/query.php",
                type: "post",
                data: {
                    task: 'search_country',
                    word: word,
                    length: word.length,
                    page_it: page_it,
                    page_en: page_en,
                },
                dataType: 'json',
                success: function (result) {
                    $('ul.countries-list').html(result);
                },
                error: function () {
                    console.log('There is error while deleting');
                }
            });
        });
*/
        $('.accedi, .footer-login, .btn-reg').click(function (e) {
            e.preventDefault();
            $('.popup-login .overlay').css("display", "block");
            $('.box-login').css("display", "flex");
            if ($(this).hasClass('btn-reg')) {
                $('.popup-login #registrati-tab').click();
            }
        });
        $('.toogle-local').click(function (e) {
            e.preventDefault();
            $('.popup-local .overlay-local').css("display", "block");
            $('.box-local').css("display", "flex");
            
        });

        $('#close-login-box').click(function (event) {
            event.preventDefault();
            $('.popup-login .overlay').css("display", "none");
            $('.box-login').css("display", "none");
        });
        $('#close-local-box').click(function (event) {
            event.preventDefault();
            $('.popup-local .overlay-local').css("display", "none");
            $('.box-local').css("display", "none");
        });

        $('.overlay').click(function () {
            $(this).css("display", "none");
            $('.box-login').css("display", "none");
        });
        $('.overlay-local').click(function () {
            $(this).css("display", "none");
            $('.box-local').css("display", "none");
        });
        $('.psw-recovery').click(function (e) {
            e.preventDefault();
            $loginBoxPassword = $('.box-login #accedi input[type="password"]'),
            $loginForm = $('.login-form');
                $loginForm.attr("action", "recupera.html");
                $("#login-btn").hide();
                $("#recupera-btn").show();
                $loginBoxPassword.slideUp();
                $loginBoxPassword.removeAttr("required");
                $(this).hide();
                $(".back-to-login").show()

            
        });

        $('.back-to-login').click(function (e) {
            e.preventDefault();
            var $loginBoxButton = $('.box-login #accedi input[type="submit"]'),
            $loginForm = $('.login-form');
                $loginForm.attr("action", "login.html");
                $("#login-btn").show();
                $("#recupera-btn").hide();
                $loginBoxPassword.prop("required", true);
                $loginBoxPassword.slideDown();
                $(this).hide();
                $(".psw-recovery").show()
            
        });




        $('.navbar-list > li:not(.free-li)').click(function (e) {
            e.preventDefault();
            if ($(this).next().is(":visible")) {
                $(this).next().removeClass("active");
            } else {
                $('.navbar-list li').next().removeClass("active");
                $(this).next().addClass("active");
                $('.close-menu').show();
            }
        })


        $('.close-menu').on("click", function () {
            $('.navbar-list li').next().removeClass("active");
            $('.close-menu').hide();
        })
        $('#basic-addon2').on("click", function (e) {
            e.preventDefault();
            $(this).parent('form').submit();
        });
        
        let form_rg = document.getElementById('registerForm');
        validationForm(form_rg,true)

        

//        form.addEventListener('click', (e)=>{
//            if(grecaptcha.getResponse().length > 0)          
//                document.querySelector('.error-label.for-g-recaptcha').classList.add('d-none');            
//        });
                      

    },
    home:function(){
        $('.newsletter-language').select2({
            autocomplete: true,
        });
        $(document).on('select2:open', () => {
            document.querySelector('.select2-search__field').focus();
        });
    },
    form_user:function(){
        $('input[name="tipo_clienteID"]').click(function () {
            $tipologiaCliente = ($(this).attr("id"));
            const $fieldAzienda = $('.field-azienda');
            const $fieldPrivato = $('.field-privato');
            switch ($tipologiaCliente){
                case 'azienda':
                        $fieldAzienda.css("display", "block");
                        $fieldAzienda.prop("required", "true")
                        $fieldPrivato.removeAttr("required");
                        $fieldPrivato.css("display", "none");
                        break;
                        case 'privato':
                        $fieldAzienda.removeAttr("required");
                        $fieldAzienda.css("display", "none");
                        $fieldPrivato.css("display", "block");
                        $fieldPrivato.prop("required", "true");
                        break;
            }
        });

        var $oneRequiredInput = $('input[name="pec"],input[name="codice_sdi"]');
        $oneRequiredInput.on('input', function () {
            $oneRequiredInput.not(this).prop('required', !$(this).val().length);
        });

        $('.one-required').on("change", function () {
            if ($('input[name=pec]').val() != "") {
                $('input[name=codice_sdi]').removeClass("required").prev().children();
            } else if ($('input[name=codice_sdi]').val() != "") {
                $('input[name=pec]').removeClass("required");
            }
        });

        $(document).on('keyup', 'input[name=piva]', function () {
            var item = $(this);
            var form = item.parents('form');
            if ($(this).val().length == 11) {
                var piva = $(this).val();
                var datapost = "task=cerca_ragionesociale&piva=" + piva;
                $.ajax({
                    url: "ajxrq/query.php",
                    type: "post",
                    data: datapost,
                    dataType: 'json',
                    success: function (result) {
                        form.find('input[name=ragionesociale]').val(result.nome);
                        form.find('input[name=indirizzo]').val(result.indirizzo);
                        form.find('input[name=civico]').val(result.civico);
                        form.find('input[name=cap]').val(result.cap);
                        form.find('input[name=citta]').val(result.citta);
                        form.find('select[name=provincia]').val(result.provinciaID);
                    },
                    error: function () {
                        $("#result").html('There is error while submit');
                    }
                });
            } else {
                form.find('input[name=ragionesociale]').val('');
            }
        });
        // $(document).on('blur', 'input[name=cf]', function(e){
        //     var item = $(this);
        //     var nome = $('input[name="nome"]').val();
        //     var cognome = $('input[name="cognome"]').val();
        //     if (nome != "" && cognome != "") {
        //         item.siblings('.cf-check-error').addClass("d-none");
        //         var check = CheckCFNomeCognome(item.val(), nome, cognome);
        //         if (!check) {
        //             item.val('');
        //             if (!item.siblings('.cf-generated-error').is(":visible")) {
        //                 item.siblings('.cf-generated-error').removeClass("d-none");
        //                 setTimeout(function () {
        //                     item.siblings('.cf-generated-error').addClass("d-none");
        //                 }, 6000);
        //             }
        //             return;
        //         } else {
        //             item.siblings('.cf-generated-error').addClass("d-none");
        //         }
        //     } else {
        //         item.val('');
        //         if (!item.siblings('.cf-check-error').is(":visible")) {
        //             item.siblings('.cf-check-error').removeClass("d-none");
        //             setTimeout(function () {
        //                 item.siblings('.cf-check-error').addClass("d-none");
        //             }, 6000);
        //         }
        //         return;
        //     }

        //     var verifica = VerificaCF(item.val());
        //     if (!verifica) {
        //         item.val('');
        //         if (!item.siblings('.cf-ctrl-error').is(":visible")) {
        //             item.siblings('.cf-ctrl-error').removeClass("d-none");
        //             setTimeout(function () {
        //                 item.siblings('.cf-ctrl-error').addClass("d-none");
        //             }, 6000);
        //         }
        //     }
        // });
        function CheckCFNomeCognome(cf, nome, cognome) {
            let checkCognome = getPatternCF(cognome);
            let checkNome = getPatternCF(nome, 1);
            let cfCognomeNome = checkCognome.concat(checkNome);
            cfCognomeNome = cfCognomeNome.join('');
            let generatedCfCognomeNome = cfCognomeNome.toUpperCase();
            let insertCfCognomeNome = cf.substring(0, 6).toUpperCase();
            return insertCfCognomeNome === generatedCfCognomeNome;
        }

        function getPatternCF(parola, nome) {
            parola = parola.toLowerCase();
            parola = parola.replace(/\s/g, '');
            let allVocali = ['a', 'e', 'i', 'o', 'u'];
            let vocali = [];
            let consonanti = [];
            let result = [];
            let limit = (nome === 1) ? 4 : 3;
            for (let i = 0; i < parola.length; i++) {
                if (allVocali.includes(parola.charAt(i))) {
                    vocali.push(parola.charAt(i))
                } else {
                    consonanti.push(parola.charAt(i))
                    if (consonanti.length === limit) {
                        if (nome) {
                            consonanti.splice(1, 1);
                        }
                        return consonanti;
                    }
                }
            }

            // Aggiungi vocali o x al cognome
            switch (consonanti.length) {
                case 3:
                    return consonanti;
                case 2:
                    if (vocali.length > 0) {
                        consonanti.push(vocali[0]);
                    }
                    return consonanti;
                case 1:
                    if (vocali.length > 1) {
                        consonanti.push(vocali[0], vocali[1])
                    } else {
                        consonanti.push(vocali[0], "x")
                    }
                    return consonanti;
                case 0:
                    if (vocali.length > 1) {
                        result.push(vocali[0], vocali[1], "x");
                    }
                    return result;
                default:
                    return false;
            }

        }



        function VerificaCF(cf) {
            var validi, i, s, set1, set2, setpari, setdisp;
            if (cf == '')
                return '';
            cf = cf.toUpperCase();
            if (cf.length != 16)
                return false;
            validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            for (i = 0; i < 16; i++) {
                if (validi.indexOf(cf.charAt(i)) == -1)
                    return false;
            }

            set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
            setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
            s = 0;
            for (i = 1; i <= 13; i += 2)
                s += setpari.indexOf(set2.charAt(set1.indexOf(cf.charAt(i))));
            for (i = 0; i <= 14; i += 2)
                s += setdisp.indexOf(set2.charAt(set1.indexOf(cf.charAt(i))));
            if (s % 26 != cf.charCodeAt(15) - 'A'.charCodeAt(0))
                return false;
            return true;
        }
    },
    products:function(){
        for(i=0; i<document.querySelectorAll('.line-color > a').length;i++){
            document.querySelectorAll('.line-color > a')[i].addEventListener("click", function (e) {
                e.preventDefault();
                let url = '/'+this.getAttribute('data-href');
                window.location.href = url;
            });
            document.querySelectorAll('.line-color > a')[i].addEventListener("mouseover", function () {
                let urlImage = this.getAttribute('data-image');
                this.parentNode.parentNode.parentNode.style.backgroundImage = "url("+urlImage+")";
            });
        }
        for(i=0; i<document.querySelectorAll('.prodotto > .prodotto-img').length;i++){
            document.querySelectorAll('.prodotto > .prodotto-img')[i].addEventListener("mouseleave", function () {
                let urlImage = this.getAttribute('data-image');
                this.style.backgroundImage = "url("+urlImage+")";
            });
        }
        
        $(document).on('click','.toggle-filters',function(e){
            let item = $(this);
            item.parent('div').siblings('.box-filters').toggleClass('d-none');
        });
        $(document).on('click','.add-favourite',function(e){
            e.preventDefault();
            var item = $(this),
            itemID = item.attr('href').replace('#','');
            var datapost = "task=aggiungi_preferiti&itemID="+itemID+"+&product_list=1";    
            $.ajax({
                url: "/ajxrq/cart_2023.php",
                type: "post",
                data: datapost,
                dataType : 'json',
                success: function(result){
                    item.removeClass('add-favourite').addClass('remove-favourite');
                    item.children("i").attr("class", "fi fi-ss-heart red-col");
                },
                error:function(){
                    console.log('There is error while adding');
                }
            });  
        });
        $(document).on('click','.remove-favourite',function(e){
            e.preventDefault();
            var item = $(this),
            itemID = item.attr('href').replace('#','');
            var datapost = "task=rimuovi_preferiti&product_list=1&itemID="+itemID;    
            $.ajax({
                url: "/ajxrq/cart_2023.php",
                type: "post",
                data: datapost,
                dataType : 'json',
                success: function(result){
                    item.removeClass('remove-favourite').addClass('add-favourite');
                    item.children("i").attr("class", "fi fi-rs-heart");
                },
                error:function(){
                    console.log('There is error while adding');
                }
            });  
        });
        $(document).on('click','.order_inc_price',function(e){
            var lng = $('html').attr('lang');
            url = window.location.toString().split('?')[0];
            queryString = window.location.search;
            querySearch='';
            urlParams = new URLSearchParams(queryString);
            querySearch += '?order=inc_price';
            if (urlParams.has('price_start'))   
            querySearch += '&price_start=' + urlParams.get('price_start');
            if (urlParams.has('price_end'))   
            querySearch += '&price_end=' + urlParams.get('price_end');
            if (urlParams.has('size'))
            querySearch += '&size=' + urlParams.get('size');
            if (urlParams.has('color'))
            querySearch += '&color=' + urlParams.get('color');
            if (urlParams.has('promo'))
            querySearch += '&promo=' + urlParams.get('promo');
        document.location.replace(url + querySearch);
        })
        $(document).on('click','.order_dec_price',function(e){
            var lng = $('html').attr('lang');
            url = window.location.toString().split('?')[0];
            queryString = window.location.search;
            querySearch='';
            urlParams = new URLSearchParams(queryString);
            querySearch += '?order=dec_price';
            if (urlParams.has('price_start'))   
            querySearch += '&price_start=' + urlParams.get('price_start');
            if (urlParams.has('price_end'))   
            querySearch += '&price_end=' + urlParams.get('price_end');
            if (urlParams.has('size'))
            querySearch += '&size=' + urlParams.get('size');
            if (urlParams.has('color'))
            querySearch += '&color=' + urlParams.get('color');
            if (urlParams.has('promo'))
            querySearch += '&promo=' + urlParams.get('promo');
            
        document.location.replace(url + querySearch);
        })
        $(document).on('click','.order_rel',function(e){
            var lng = $('html').attr('lang');
            var url = window.location.toString().split('?')[0];
            var queryString = window.location.search;
            var querySearch='';
            var urlParams = new URLSearchParams(queryString);
            var count_params=0;
            if (urlParams.has('price_start'))   
            {querySearch += (count_params==0?'?':'&')+'price_start=' + urlParams.get('price_start')
             count_params++;
            }
            if (urlParams.has('price_end'))   
            {querySearch += (count_params==0?'?':'&')+'price_end=' + urlParams.get('price_end')
            count_params++;
            }
            if (urlParams.has('size'))
            {querySearch += (count_params==0?'?':'&')+'size=' + urlParams.get('size')
            count_params++;
            }
            if (urlParams.has('color'))
            {querySearch += (count_params==0?'?':'&')+'color=' + urlParams.get('color')
            count_params++;
            }
            if (urlParams.has('promo'))
            {querySearch += (count_params==0?'?':'&')+'promo=' + urlParams.get('promo')
            count_params++;
            }
            
        document.location.replace(url + querySearch);
        })
        $(document).on('change', '.collapse input[type=checkbox]', function(){
            window.location.replace($(this).val());
        });

        
    },
    product_item:function(){
        $(window).on('load', function(){
            if($('.product-item-detail .line-color > a').length == 1 ){
                $('.product-item-detail .line-color > a').click();
            }
        });
        $(document).on('click','.product-item-detail .line-color > a',function(e){
            e.preventDefault();
            var item = $(this);
            console.log(item)
            item.siblings('a').removeClass('selected'), value = item.attr('title');
            item.addClass('selected'), immagine_url = item.data('image');
            var item = item.attr('href').replace('#','');
            $.ajax({
                url: "/ajxrq/query.php",
                type: "post",
                data: {
                    task: 'search_taglie_da_colore',
                    item: item,
                },
                dataType : 'json',
                success: function(result){  
                    console.log(result) 
                    $('.dropdown-taglia ul').html(result.list);
                    $('.dropdown-taglia-all ul').html(result.list_all);
                    $('.prd-image').css({backgroundImage: 'url('+immagine_url+')'});
                    $(".prd-image").attr('href',immagine_url)
                    $('input[name=color_value]').val(value);
                    $('.adviser-size form input[name=colore]').val(value);
                },
                error:function(){
                    console.log('There is error while deleting');
                }
            });
        });
        $(document).on('click','.dropdown-taglia ul li a.dropdown-item',function(e){
            e.preventDefault();
            var item = $(this), value = item.attr('title'), size_price = item.children('span').find('.price_taglia').text();
            item.parent('li').parent('ul').siblings('button').html($(this).html());
            $('input[name=costoID]').val(item.attr('href').replace('#',''));
            $('input[name=barcode]').val(item.data('barcode'));
            $('input[name=limit]').val(item.data('limit'));
            $('input[name=size_value]').val(value);
            $('.product-detail-price').html('<p class="fw-semibold mt-2 fs-5">'+size_price+'</p>');
            //set scalapay widget
            $("scalapay-widget").attr("amount",size_price);
            //
        });     
        $(document).on('click','.dropdown-taglia ul li a.no-size-alert',function(e){
            e.preventDefault();
            var popup = $('.adviser-size');
            popup.addClass('visible');
        });
        $(document).on('click','.dropdown-taglia-all ul li a.dropdown-item',function(e){
            e.preventDefault();
            var item = $(this), form = item.parent('li').parent('ul').parent('div').siblings('form'), varianteID = item.attr('href').replace('#',''),
            title = item.attr('title');
            form.find('input[name=varianteID]').val(varianteID);
            item.parent('li').parent('ul').siblings('button').html($(this).html());
            form.find('input[name=taglia]').val(title);
            
        });
        $(document).on('click','.adviser-size > .content > button',function(e){
            $(this).parent('div').parent('div').removeClass('visible');
        });
        
        /*GESTIONE DEL CARRELO NEL SINGOLO PRODOTTO - START*/
        $(document).on('click','.add-cart',function(e){
            
            
            e.preventDefault();
            var item = $(this), 
            costoID = item.siblings('input[name=costoID]').val(),
            codice = item.siblings('input[name=itemID]').val(),
            barcode = item.siblings('input[name=barcode]').val(),
            lang = $('html').attr('lang'),
            limit = item.siblings('input[name=limit]').val(), quantita = item.siblings('input[name=quantita]').val(),
            size = item.siblings('input[name=size_value]').val(),
            color = item.siblings('input[name=color_value]').val();
            if(costoID!=''){                
                var barcode
                //attributi_value = taglia_sel.siblings('input[name=attributi_value]').val(),
                //attributi_label = taglia_sel.siblings('input[name=attributi_label]').val(),               
                if(quantita<=limit){
                    showLoader()
                    $.ajax({
                        url: "/ajxrq/cart_2023.php",
                        type: "post",
                        data: {
                            task: 'cart_add',
                            prodottoID: codice+'|'+costoID,
                            barcode: barcode,
                            qta: quantita,
                            size: size,
                            color: color,
                        },
                        dataType : 'json',
                        success: function(result){
                            hideLoader()
                            $(".container-laterale .carrello-prodotti").html(result.cart);
                            $("#cart_total").html(result.totale);
                            $("#cart_header_number").html(result.qta);
                            $("#cart_header_euro").html(result.totale);
                            
                            $('.n-products').text(result.qta_header);
                            $("#success").fadeIn('fast').delay(5500).fadeOut('fast');
                        },
                        error:function(){
                            hideLoader()
                            console.log('There is error while adding');
                        }
                    });
                }else{
                    
                    if(lang=='it')
                       var testo_errore = 'Attenzione! Ci sono solo '+limit+' pezzi disponibili.';
                    else
                       var testo_errore = 'Attention! There are only '+limit+' pieces available.';

                    var text = '<p>'+testo_errore+'</p>';
                    $('.popup-notify').html(text).fadeIn('fast').delay(2000).fadeOut('fast');
                }            
            }else{
                
                if(lang=='it')
                    $('.popup-notify').html('<p>Attenzione! Non hai selezionato la taglia</p>').fadeIn('fast').delay(2000).fadeOut('fast');
                else
                    $('.popup-notify').html('<p>Attention! You have not selected the size</p>').fadeIn('fast').delay(2000).fadeOut('fast');
            }
            
        });
        $('.btn-up').on('click',function(){
            var lang = $('html').attr('lang');
            if($('.square-taglia.sel').length>0){
                var item = $(this), taglia_sel = $('.square-taglia.sel'),
                qta = parseInt(item.siblings('input[name=quantita]').val()), limit = parseInt(taglia_sel.siblings('input[name=limit]').val()), 
                multiplo = parseInt(taglia_sel.siblings('input[name=multiplo]').val()),
                new_qta = qta + multiplo;
                if(new_qta <= limit){
                    item.siblings('input[name=quantita]').val(new_qta);
                }
            }else{
                if(lang=='it')
                    $('.popup-notify').html('<p>Attenzione! Non hai selezionato la taglia</p>').fadeIn('fast').delay(2000).fadeOut('fast');
                else
                    $('.popup-notify').html('<p>Attention! You have not selected the size</p>').fadeIn('fast').delay(2000).fadeOut('fast');
            }
        })
        $('.btn-down').on('click',function(){
            var lang = $('html').attr('lang');
            if($('.square-taglia.sel').length>0){
                var item = $(this), taglia_sel = $('.square-taglia.sel'),
                qta = parseInt(item.siblings('input[name=quantita]').val()), limit = 0, 
                multiplo = parseInt(taglia_sel.siblings('input[name=multiplo]').val()),
                new_qta = qta - multiplo;
                if(new_qta > limit){
                    item.siblings('input[name=quantita]').val(new_qta);
                }
            }else{
                if(lang=='it')
                    $('.popup-notify').html('<p>Attenzione! Non hai selezionato la taglia</p>').fadeIn('fast').delay(2000).fadeOut('fast');
                else
                    $('.popup-notify').html('<p>Attention! You have not selected the size</p>').fadeIn('fast').delay(2000).fadeOut('fast');
            }
        })
        /*GESTIONE DEL CARRELO NEL SINGOLO PRODOTTO - END*/
        
        $(document).on('click','.add-favourite',function(e){
            e.preventDefault();
            var item = $(this),
            itemID = item.attr('href').replace('#','');
            var datapost = "task=aggiungi_preferiti&itemID="+itemID;    
            $.ajax({
                url: "/ajxrq/cart_2023.php",
                type: "post",
                data: datapost,
                dataType : 'json',
                success: function(result){
                    item.removeClass('add-favourite').addClass('remove-favourite');
                    item.children("i").attr("class", "fi fi-ss-heart red-col");
                },
                error:function(){
                    console.log('There is error while adding');
                }
            });  
        });
        $(document).on('click','.remove-favourite',function(e){
            e.preventDefault();
            var item = $(this),
            itemID = item.attr('href').replace('#','');
            var datapost = "task=rimuovi_preferiti&itemID="+itemID;    
            $.ajax({
                url: "/ajxrq/cart_2023.php",
                type: "post",
                data: datapost,
                dataType : 'json',
                success: function(result){
                    item.removeClass('remove-favourite').addClass('add-favourite');
                    item.children("i").attr("class", "fi fi-rs-heart");
                },
                error:function(){
                    console.log('There is error while adding');
                }
            });  
        });

    },
    close_success:function(){
        //const succ = document.getElementById('success');
    },
    
    contacts: function(){
        var form = document.getElementById('contactsForm');
        form.querySelector('input[name=pulsante]').addEventListener('click', (e) =>{            
            let check = checkForm(form, 1);
            if(check > 0)
                e.preventDefault();
        });
        checkForm(form, 2);
//        form.addEventListener('click', (e)=>{
//            console.log('recaptcha', grecaptcha.getResponse().length);
//            if(grecaptcha.getResponse().length > 0)          
//                document.querySelector('.error-label.for-g-recaptcha').classList.add('d-none');            
//        });
    },
    cart: function(){
        if($('input[name=pagamento]:checked').val() == undefined){
            $('input[name=pagamento]:first').attr('checked', true); 
            setCart(); 
        }else{
            setCart();
        }
        
        $(document).on('change', 'input[name=trasporto]', function (e) {
            setCart();            
        });
        $(document).on('click', '.btn-down-cart', function (e) {
            
            e.preventDefault();
            var item = $(this), 
            id = item.siblings('input[name=item]').val(),
            row = item.parents('.tbody'),
            multiplo = parseInt(item.siblings('input[name=multiplo]').val()),
            unit_price = parseFloat(item.siblings('input[name=unit]').val()), total_price,
            qta_min = parseInt(item.siblings('input[name=qta_min]').val()),
            qta_input = item.siblings('input[name=quantita]'),
            qta = parseInt(item.siblings('input[name=quantita]').val()), less;
            
            if((qta - multiplo) >= qta_min){
                
                $(this).parent('div').parent('div').remove();
                total_price = unit_price * (qta - multiplo);
                less = multiplo - (multiplo * 2);
                //alert("pippo");  
                $.ajax({
                    
                    url: "/ajxrq/cart_2023.php",
                    type: "post",
                    data: {
                        task: 'cart_add',
                        prodottoID: id,
                        qta: less,
                    },
                    dataType: 'json',
                    success: function (result) {
                        row.children('.column-total').children('p').html('&euro; '+total_price.toFixed(2).toString().replace('.',','));
                        qta_input.val(qta - multiplo),
                        setCart();
                    },
                    error: function () {
                        console.log('There is error while deleting');
                    }
                });                
            }
            
        }); 
        
        $(document).on('click', '.btn-up-cart', function (e) {
            
            e.preventDefault();
            var item = $(this), 
            id = item.siblings('input[name=item]').val(),
            row = item.parents('.tbody'),
            unit_price = parseFloat(item.siblings('input[name=unit]').val()), total_price,
            limit = parseInt(item.siblings('input[name=limit]').val()),
            multiplo = parseInt(item.siblings('input[name=multiplo]').val()),
            qta_input = item.siblings('input[name=quantita]'),
            qta = parseInt(item.siblings('input[name=quantita]').val()), less;
            if((qta + multiplo) <= limit){
                total_price = unit_price * (qta + multiplo);
                $(this).parent('div').parent('div').remove();
                //alert("pippo");  
                $.ajax({
                    async: false,
                    url: "/ajxrq/cart_2023.php",
                    type: "post",
                    data: {
                        task: 'cart_add',
                        prodottoID: id,
                        qta: multiplo,
                    },
                    dataType: 'json',
                    success: function (result) {
                        row.children('.column-total').children('p').html('&euro; '+total_price.toFixed(2).toString().replace('.',','));
                        qta_input.val(qta + multiplo),
                        setCart();
                    },
                    error: function () {
                        console.log('There is error while deleting');
                    }
                });                
            }else{
                var text = '<p>Quantità prodotti non disponibile!</p>';
                $('.popup-notify').html(text).fadeIn('fast').delay(1000).fadeOut('fast');
            }
            
        }); 
        
        $(document).on('click', '.btn-remove-cart', function (e) {
            
            e.preventDefault();
            var item = $(this), 
            id = item.siblings('input[name=item]').val(),
            limit = parseInt(item.siblings('input[name=limit]').val()),
            multiplo = parseInt(item.siblings('input[name=multiplo]').val()),
            qta_min = parseInt(item.siblings('input[name=qta_min]').val()),
            qta = parseInt(item.siblings('input[name=quantita]').val()), less;
            if((qta - multiplo) >= qta_min){
                $(this).parent('div').parent('div').remove();
                less = multiplo - (multiplo * 2);
                //alert("pippo");  
                $.ajax({
                    url: "/ajxrq/cart_2023.php",
                    type: "post",
                    data: {
                        task: 'cart_del',
                        prodottoID: id,
                        qta: less,
                    },
                    dataType: 'json',
                    success: function (result) {
                        setCart();
                        $('.n-products').text(result.qta_header);
                        
                        
                    },
                    error: function () {
                        console.log('There is error while deleting');
                    }
                });                
            }
            
        }); 
        $(document).on('click','.add-coupon',function(){
                showLoader()
                var coupon = $('input[name="coupon"]').val();
                var userID = parseInt($(this).data('user'));
                if(coupon!=''){
                    var datapost = "task=coupon_add&codice="+coupon+"&userID="+userID;
                    $.ajax({
                        url: "/ajxrq/cart_2023.php",
                        type: "post",
                        data: datapost,
                        dataType : 'json',
                        success: function(result){
                            if(result.operation==true){
                                location.reload();
                            }
                            if(result.operation==false){
                                $('input[name="coupon"]').val('');
                                //$('input[name="coupon"]').attr('placeholder',result.errore);
                                $('.coupon-message p').html(result.errore);
                                $('.coupon').html('0,00');
                            }
                        },
                        error:function(){
                            //alert("failure");
                            $("#result").html('There is error while submit');
                        }
                    });// funzione ajxa per validare il coupon, segue esempio
                }else{
                        $('input[name="coupon"]').attr('placeholder','  Nessun codice promozionale inserito!');
                }
                checkcoupon = 1;
                setCart();
                hideLoader()
                return false;
                
        });
        
        $('.remove-coupon').click(function(){
            showLoader()
            var datapost = "task=coupon_remove";
            $.ajax({
                    url: "/ajxrq/cart.php",
                    type: "post",
                    data: datapost,
                    dataType : 'json',
                    success: function(result){
                        if(result.operation==true){
                            location.reload();
                        }else{
                            alert("Error");
                        }
                    },
                    error:function(){
                        //alert("failure");
                        $("#result").html('There is error while submit');
                    }
                });// funzione ajxa per validare il coupon, segue esempio

            checkcoupon = 0;
            setCart();
            hideLoader()
            return false;
        });
        
        $(document).on('change','select[name=indirizzoID]',function(){
            
            var item = $(this);
            if(item.val()=='aggiungi'){
                $('.address-form').removeClass('d-none');
                $('.address-form input[type=text]').val('').removeAttr('disabled').attr('required','required');
                $('.address-form input[name=indirizzo_google]').removeAttr('required');
                $('.address-form select').val('').removeAttr('disabled').attr('required','required');
                $('.address-form select[name=provinciaID]').val('');
            }else{
                if(!$('.address-form').hasClass('d-none'))
                    $('.address-form').addClass('d-none')
                $('.address-form input[type=text]').attr('disabled','disabled').removeAttr('required');
                $('.address-form select').attr('disabled','disabled').removeAttr('required');
                var nazioneID = item.children('option:selected').data('nazione');
                var nazione_sigla = item.children('option:selected').data('nazione-sigla'); 
                $('input[name=nazione]').val(nazioneID);
                if(nazioneID == 106 && !$('.banner-pudo').hasClass('active')){
                    $('.banner-pudo').addClass('active');
                }else if(nazioneID != 106){
                    $('.banner-pudo').removeClass('active');                    
                }
                setCart();
                //reset general locale reloading page
                document.body.innerHTML += '<form id="changeLocaleAndAddress" action="'+window.location.href.split('?')[0]+'" method="post"><input type="hidden" name="change_locale" value="'+nazione_sigla+'"><input type="hidden" name="address" value="'+item.val()+'"></form>';
                document.getElementById("changeLocaleAndAddress").submit();
                
                

            }
            
        });
        
        /*
        $(document).on('change','input[name=pagamento]',function(){
            console.log('test')
            setCart();
        });
        */
        $(document).on('change','input[name=pagamento], .opional-options',function(){
           
            setCart();
        });
        $(document).on('click','.address-form .btn-send',function(e){
            
            e.preventDefault();            
            var item = $(this), form = item.parents('.address-form'), errori = new Array();
            form.find('input:required').each(function(){
                if($(this).val()==''){
                    errori.push($(this).attr('field'));
                }
            });
            form.find('select:required').each(function(){
                if($(this).val()==''){
                    errori.push($(this).attr('field'));
                }
            });
            if(form.find('input[name=cap]').val().length >= 8){
                errori.push($(this).attr('field'));
            }
            /*controllo della città per evitare che venga inserito il cap - start*/
            var citta_value = form.find('input[name=citta]').val(),
            citta_n = citta_value.length, cont_check = 0;
            var citta_type = checkTypeString(citta_value,citta_n);
            if(citta_type=='numeric')
                errori.push(form.find('input[name=citta]').attr('field'));
            /*controllo della città per evitare che venga inserito il cap - end*/
            
            if(errori.length==0){
                var referente = form.find('input[name=referente]').val(),
                indirizzo = form.find('input[name=indirizzo]').val(), civico = form.find('input[name=civico]').val(),
                indirizzo_google = form.find('input[name=indirizzo_google]').val(),
                citta = form.find('input[name=citta]').val(),cap = form.find('input[name=cap]').val(),
                cf = form.find('input[name=cf]').val(),
                cellulare = form.find('input[name=cellulare]').val(),
                nazioneID = parseInt(form.find('select[name=stato]').val()),provinciaID = form.find('select[name=provincia]').val(),
                note = form.find('textarea[name=note]').val();

                var data = {
                    task: "action_address",
                    referente: referente,
                    indirizzo_google: indirizzo_google,
                    indirizzo: indirizzo,
                    civico: civico,
                    citta: citta,
                    cap: cap,
                    cellulare: cellulare,
                    cf: cf,
                    nazioneID: nazioneID,
                    provinciaID: provinciaID,
                    note: note,
                };    
                if(parseInt(item.siblings('input[name=id]').val())>0){
                    var id = parseInt(item.siblings('input[name=id]').val());
                    data.id = id;
                }
                
                $.ajax({
                    url: "ajxrq/cart_2023.php",
                    type: "post",
                    data: data,
                    dataType : 'json',
                    success: function(result){
                        $('select[name=indirizzoID]').html(result.option).removeClass('d-none').siblings('i').removeClass('d-none');                        
                        $('input[name=nazione]').val(result.nazione);                        
                        form.addClass('d-none');
                        setCart();
                        //reset general locale reloading page
                        
                        document.body.innerHTML += '<form id="changeLocaleAndAddress" action="'+window.location.href.split('?')[0]+'" method="post"><input type="hidden" name="change_locale" value="'+result.nazione_sigla+'"><input type="hidden" name="address" value="'+result.address_id+'"></form>';
                        document.getElementById("changeLocaleAndAddress").submit();
                        
                        /*
                        $('.options-container.transport').removeClass('hidden').find('.left').html(result.transport);
                        $.ajax({
                            url: "ajxrq/query.php",
                            type: "post",
                            data:  {
                                    task: "get_info_transport",
                                    nazioneID: nazioneID,
                                    },
                            dataType : 'json',
                            success: function(result){
                                item.parents('.forms-user-container').siblings('.transport').removeClass('hidden').find('.left').html(result.transport);
                                $('input[name=nazione]').val(nazioneID);
                                if(!$('.banner-pudo').hasClass('visible'))
                                    $('.banner-pudo').addClass('visible');
                                setCart();
                            },
                            error:function(){
                                //alert("failure");
                                $("#result").html('There is error while submit');
                            }
                        });
                         * 
                         */

                    },
                    error:function(){
                        //alert("failure");
                        $("#result").html('There is error while submit');
                    }
                });
            }else{
                var uniqueNames = [];
                $.each(errori, function(i, el){
                    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
                });
                var testo_errore = '<b>'+$("#address-error-mex").val()+'</b><br/> '+uniqueNames.join(', ');
                var text = '<p>'+testo_errore+'</p>';
                $('.popup-notify').html(text).fadeIn('fast').delay(2500).fadeOut('fast');
            }
            
        });
        $(document).on('click','.elimina-prodotto-carrello',function(e){
            
            e.preventDefault();
            var item = $(this), n_prodotti = parseInt($('.elimina-prodotto-carrello').length),
            cart_container = item.parents('.carrello-prodotti-page'),
            lang = $('html').attr('lang'),
            prodottoID = item.attr('href').replace('#','');
            $.ajax({
                url: "/ajxrq/cart_2023.php",
                type: "post",
                data: {
                    task: 'cart_del_by_cart',
                    prodotto: prodottoID,
                },
                dataType: 'json',
                success: function (result) {
                    if(parseInt(result) > 0)
                        item.parent('div').parent('div').remove();
                    else{
                        var message = (lang=='it')?'Nessun prodotto nel carrello':'No products in the cart';
                        cart_container.html('<div class="row product-cart-item"><div class="col-12"><p class="barlow">'+message+'</p></div></div>');
                    }
                    
                    $('.n-products').text(result);
                    setCart();
                },
                error: function () {
                    console.log('There is error while adding');
                }
            });
            
        });
        $(document).on('change', '#utente-nazione', function(){
            var item = $(this);
            if(item.val()!='106'){
                $('#administrative_area_level_2').val('ES')
                $("#prov_box").hide()
                $('input[name=cf]').val('').removeAttr('required')
                $("#cf_box").hide()
            }else{
                $('#administrative_area_level_2').val('')
                $("#prov_box").show()
                $('input[name=cf]').val('').attr('required', 'required')
                $("#cf_box").show()
            }
        });
        
        function setCart(shipval) {
            showLoader()
            var nazione = parseInt($('input[name=nazione]').val()),
            pagamento = $('input[name=pagamento]:checked').val(),
            is_msp=0,
            msp_type=null,
            msp_description=null,
            is_pp=0,
            pp_type=null,
            pp_description=null,
            opzioni_aggiuntive = $('input[name="opzioni[]"]:checked').length > 0 ? $('input[name="opzioni[]"]:checked').map(function() {return this.value;}).get() : '',
            trasporto = $('input[name="trasporto"]:checked').val(),
            lng = $('html').attr('lang');
            if(pagamento=='multisp'){
                is_msp = 1
                msp_type = $('input[name=pagamento]:checked').data('msp-type')
                msp_description = $('input[name=pagamento]:checked').data('msp-description')
                
            }
            if(pagamento=='payplug'){
                is_pp = 1
                pp_type = $('input[name=pagamento]:checked').data('pp-type')
                pp_description = $('input[name=pagamento]:checked').data('pp-description')
                
            }
            $.ajax({
                url: "/ajxrq/cart_2023.php",
                type: "post",
                data: {
                    task: 'set_cart',
                    pagamento: pagamento,
                    is_msp: is_msp,
                    msp_type: msp_type,
                    msp_description: msp_description,
                    is_pp: is_pp,
                    pp_type: pp_type,
                    pp_description: pp_description,
                    nazione: nazione,
                    trasporto: trasporto,
                    opzioni_aggiuntive: btoa(opzioni_aggiuntive),
                    lng: lng,
                },
                dataType: 'json',
                success: function (result) {
                    console.log(result)
                    if(is_msp==1){
                        $('input[name=msp_type]').val(msp_type)
                    }
                    if(is_pp==1){
                        $('input[name=pp_type]').val(pp_type)
                        $('input[name=pp_type_desc]').val(pp_description)
                    }
                    $('.totale-prodotti').text(result.totale_prodotti);
                    $('#cart_header_euro').html(result.totale_prodotti);
                    $('.totale-imponibile').text(result.totale_imponibile_prodotti);
                    if(result.totale_coupon && !result.totale_coupon.includes("0,00")){
                        $('.coupon-value').html('<span class="coupon fs-5">- '+result.totale_coupon+'</span>');
                        $('.coupon-value-container .coupon').text('- '+result.totale_coupon);
                    }else{
                        $('.coupon-value-container .coupon').text('');
                        $('.coupon-value').text('');
                    }
                    $('.totale-prodotti.final').text(result.totale_prodotti);
                    $('.totale-iva').text(result.totale_iva);
                    $('.totale-spedizione').text(result.totale_trasporto);
                    $('.totale-pagamento').text(result.totale_pagamento);
                    $('.totale-ordine').text(result.totale);
                    $('.totale-opzioni').text(result.totale_opzioni_aggiuntive);
                    if(!result.opzioni_aggiuntive_show){
                        if(!$('.totale-opzioni-box').hasClass('d-none'))
                           $('.totale-opzioni-box').addClass('d-none');
                    }else{
                        if($('.totale-opzioni-box').hasClass('d-none'))
                           $('.totale-opzioni-box').removeClass('d-none');
                    }
                    $('.pagamento-label').html(result.label_pagamento);
                    $('.spedizione-label').html(result.label_spedizione);
                    $('.number-products').html(result.numero_prodotti);
                    $('.shipping-standard').siblings('span.float-end').html(result.consegna_standard_label);
                    if(result.nazione == 106)
                        $('.label-radio-custom.contrassegno').removeClass('d-none');
                    else
                        $('.label-radio-custom.contrassegno').addClass('d-none');
                    
                    if(result.nazione == 106 && !$('.banner-pudo').hasClass('active')){
                        $('.banner-pudo').addClass('active');
                    }else if(result.nazione != 106){
                        $('.banner-pudo').removeClass('active');                    
                    }
                    //set scalapay widget
                    $("scalapay-widget").attr("amount",result.totale_without_symbol);
                    $("scalapay-widget").attr("currency-display",result.totale_symbol);
                    //
                    if(parseInt(result.esito)==1){
                        if(!$('.contaner-cart-alert').hasClass('d-none'))
                            $('.contaner-cart-alert').addClass('d-none');
                        if($('.container-buttons-cart').hasClass('d-none'))
                            $('.container-buttons-cart').removeClass('d-none')
                        //if($('.cart-summary').hasClass('d-none'))
                          //  $('.cart-summary').removeClass('d-none')
                    }else{
                        if($('.contaner-cart-alert').hasClass('d-none'))
                            $('.contaner-cart-alert').removeClass('d-none');
                        else
                            $('.contaner-cart-alert').addClass('d-none');
                        if(!$('.container-buttons-cart').hasClass('d-none'))
                            $('.container-buttons-cart').addClass('d-none')
                        //if(!$('.cart-summary').hasClass('d-none'))
                          //  $('.cart-summary').addClass('d-none')
                         if($('.contaner-cart-alert').hasClass('d-none'))
                            $('.contaner-cart-alert').removeClass('d-none');
                        
                        $('.contaner-cart-alert .alert p').text(result.messaggio_errore);
                    }
                    /*
                    if(lang=='it')
                        window.location.replace('https://shop.the-complainers.com/carrello.html');
                    if(lang=='en')
                        window.location.replace('https://shop.the-complainers.com/cart.html');
                     * 
                     */
                },
                error: function () {
                    console.log('There is error while adding');
                }
            }); 
            hideLoader()
        }
        
        /*PUDO START*/
        $(document).on('click','.remove-pudo-popup',function(e){
            e.preventDefault();
            $(this).parent('div').parent('div').removeClass('open');
            $('input[name=pudoID].pudo-selected').val('');
            $('input[name=pudo_nome].pudo-selected').val('');
            $('input[name=pudo_check]').prop('checked',false);
        });
        $(document).on('change','input[name=pudo_check]',function(){
            if($(this).prop('checked')==true){
                var indirizzoID = $('select[name=indirizzoID]').val();
                var datapost = "task=get_pudo&indirizzo="+indirizzoID;
                $.ajax({
                    url: "/ajxrq/query.php",
                    type: "post",
                    data: datapost,
                    dataType : 'json',
                    success: function(result){
                        $('.container-popup-pudo .box .entry .container-results ul').html(result.pudo_list);
                        $('.container-popup-pudo .box .entry .row-input .input-col input[name=indirizzo]').val(result.dati.address)
                        $('.container-popup-pudo .box .entry .row-input .input-col input[name=citta]').val(result.dati.city)
                        $('.container-popup-pudo .box .entry .row-input .input-col select[name=provincia]').val(result.dati.provincia)
                        $('.container-popup-pudo .box .entry .row-input .input-col input[name=cap]').val(result.dati.zipCode)
                    },
                    error:function(){
                        //alert("failure");
                        $("#result").html('There is error while submit');
                    }
                });
                $('.container-popup-pudo').addClass('open');
            }else{
                $('.go-on input[name=pudoID].pudo-selected').val('');
                $('.go-on input[name=pudo_nome].pudo-selected').val('');
                $('.address-box').removeClass('d-none');
            }
        });
        $(document).on('change','.container-popup-pudo .box .entry .container-results ul input[name=pudoID]',function(){
           $('input[name=pudo_nome].pudo-selected').val($(this).parent('li').text()); 
        });
        $(document).on('click','.container-popup-pudo .box .entry .row-input .input-col button',function(e){
            e.preventDefault();
            var item = $(this), form = item.parent('div').parent('div'),
            indirizzo = form.find('input[name=indirizzo]').val(),
            cap = form.find('input[name=cap]').val(),
            citta = form.find('input[name=citta]').val(),
            provincia = form.find('select[name=provincia]').val();
            $.ajax({
                    url: "/ajxrq/query.php",
                    type: "post",
                    data: {
                        task: 'search_pudo',
                        indirizzo: indirizzo,
                        cap: cap,
                        citta: citta,
                    },
                    dataType : 'json',
                    success: function(result){
                        $('.container-popup-pudo .box .entry .container-results ul').html(result.pudo_list);
                    },
                    error:function(){
                        //alert("failure");
                        $("#result").html('There is error while submit');
                    }
                });
        });
        $(document).on('click','.container-popup-pudo .box .entry .container-results button',function(e){
            if($(this).siblings('ul').find('input[name=pudoID]:checked').length==1){
                var pudoID = $(this).siblings('ul').find('input[name=pudoID]:checked').val();
                $('input[name=pudoID].pudo-selected').val(pudoID);
                $(this).siblings('ul').html('');
                $('.container-popup-pudo').removeClass('open');
                $('.address-box').addClass('d-none');
            }else{
                alert('Attenzione! Non hai selezionato un punto di ritiro.');
                $('.address-box').removelass('d-none');
            }

        });
        /*PUDO END*/
    },
    
    cart_sp: function(){
        $(document).on('change', 'select[name=nazioneID]', function(){
            var item = $(this);
            
            if(item.val()!='106'){
                $('#administrative_area_level_2').val('123').parent('div').addClass('opacity-0').addClass('h-0').addClass('overflow-hidden');
                $('input[name=cf]').val('').removeAttr('required').parent('div').addClass('opacity-0').addClass('h-0').addClass('overflow-hidden');
            }else{
                $('#administrative_area_level_2').val('').parent('div').removeClass('opacity-0').removeClass('h-0').removeClass('overflow-hidden');
                $('input[name=cf]').val('').attr('required', 'required').parent('div').removeClass('opacity-0').removeClass('h-0').removeClass('overflow-hidden');
            }
        });
        let form_r = document.getElementById('registrationForm');
        validationForm(form_r,true)
        $("select[name=nazioneID]").trigger("change")
        
    },
    edit_address: function(){
        $(document).on('change', 'select[name=nazioneID]', function(){
            var item = $(this);
            if(item.val()!='106'){
                $('#administrative_area_level_2').val('ES');
                $('.provincia-box').addClass('opacity-0');
                $('.cf-box').addClass('opacity-0').find('input').removeAttr('required');
            }else{
                $('.provincia-box').removeClass('opacity-0');
                $('.cf-box').removeClass('opacity-0').find('input').attr('required', 'required');
            }
        });
    },
    resi: function(){
        $(document).on('click','.add-photos', function(e){
            e.preventDefault();
            $(this).siblings('div').removeClass('d-none');
        });
        $(document).on('change','.checkbox-product-return', function(){
            var item = $(this);
            if(item.is(':checked'))
                item.parent('div').parent('div').find('.box-reso').removeClass('d-none');
            else
                item.parent('div').parent('div').find('.box-reso').addClass('d-none');

        });
        
        /*GESTIONE CARICAMENTO IMMAGINI MULTIPLE - START*/
        const inputDiv = document.querySelector(".input-div");
        const input = document.querySelectorAll(".input_gallery");
        const output = document.querySelectorAll("output");
        const errorLimit = document.querySelector('error-msg .limit');
        const errorName = document.querySelector('error-msg .name');
        //const submit = document.querySelector('#submit-proponi');
        for(let y=0; y < input.length; y++){
            let imagesArray = [];
            input[y].addEventListener("change", () => {
                const files = input[y].files;

                for (let i = 0; i < files.length; i++) {
                    imagesArray.push(files[i]);
                }

                displayImages(imagesArray, output[y]);
    //            if (imagesArray.length > 10) {
    //                errorLimit.classList.remove('d-none');
    //                submit.disabled = 'true';
    //                submit.classList.add('disable');
    //            } else {
    //                submit.disabled = '';
    //                submit.classList.remove('disable');
    //            }
            });
            
        }

        inputDiv.addEventListener("drop", (e) => {
            e.preventDefault();
            const files = e.dataTransfer.files;
            for (let i = 0; i < files.length; i++) {
                if (!files[i].type.match("image"))
                    continue;

                if (imagesArray.every(image => image.name !== files[i].name)) {
                    errorName.classList.add('d-none');
                    imagesArray.push(files[i]);
                } else {
                    errorName.classList.remove('d-none');
                }
            }
            if (imagesArray.length > 30) {
                errorLimit.classList.remove('d-none');
                //submit.disabled = 'true';
                //submit.classList.add('disable');
            }
            displayImages(imagesArray, output);
        });
        /*GESTIONE CARICAMENTO IMMAGINI MULTIPLE - END*/
        
    },
    share_social: function () {
        // Social share Start
        $('.share-social a').click(function () {
            var url = $('meta[property="og:url"]').attr('content')
            var title = $('meta[property="og:title"]').attr('content');
            console.log(url)
            var shareOn = $(this);
            console.log(shareOn);
            if (shareOn.hasClass('facebook')) {
                var pu_height = 310, pu_width = 550;
                var pu_url = "http://www.facebook.com/share.php?u=" + url;
            } else if (shareOn.hasClass('instagram')) {
                var pu_height = 461, pu_width = 550;
                var pu_url = "https://www.instagram.com/?url=" + url + "&text=" + title + "";
            } else if (shareOn.hasClass('linkedin')) {
                var pu_height = 468, pu_width = 512;
                var pu_url = "http://www.linkedin.com/shareArticle?mini=true&url=" + url;
            }
            var pu_top = (screen.height / 2) - (pu_height / 2)
            var pu_left = (screen.width / 2) - (pu_width / 2);
            window.open(pu_url, null, "height=" + pu_height + ",width=" + pu_width + ",top=" + pu_top + ",left=" + pu_left + ",status=0");
            return false;
        });
// Social share End
    }
    
};

$(document).ready(function () {
    function init_swipers(){
        const swiperHome = new Swiper(".swiper-home", {
          direction: "horizontal",
          loop: false,
          pagination: {
            el: ".swiper-pagination",
            clickable: true,
          },
          on: {
            init: function () {
              console.log("swiper-home initialized");
            },
          },
         
        });

        const swiperBrands = new Swiper(".swiper-brands", {
          direction: "horizontal",
          loop: true,
          breakpoints: {
            300: {
                slidesPerView: 2,
                spaceBetween: 8,
              },
            500: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            575: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            767: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            991: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            1199: {
              slidesPerView: 4,
              spaceBetween: 8,
            },
          },
          pagination: {
            el: ".swiper-pagination",
            clickable: true,
          },
          on: {
            init: function () {
              console.log("swiper-brands initialized");
            },
          },
        });

        const swiperNovita = new Swiper(".swiper-novita", {
          direction: "horizontal",
          loop: false,

          pagination: {
            el: ".swiper-pagination-novita",
            clickable: true,
          },
          breakpoints: {
            300: {
                slidesPerView: 2,
                spaceBetween: 8,
              },
            500: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            575: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            767: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            991: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            1199: {
              slidesPerView: 4,
              spaceBetween: 8,
            },
          },
          on: {
            init: function () {
              console.log("swiper-novità initialized");
            },
          },
        });

        const swiperCorrelati = new Swiper(".swiper-correlati", {
          direction: "horizontal",
          loop: false,

          pagination: {
            el: ".swiper-pagination",
            clickable: true,
          },

          breakpoints: {
            300: {
                slidesPerView: 2,
                spaceBetween: 8,
              },
            500: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            575: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            767: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            991: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            1199: {
              slidesPerView: 4,
              spaceBetween: 8,
            },
          },
          on: {
            init: function () {
              console.log("swiper-correlati initialized");
            },
          },
        });

        const swiperTendenze = new Swiper(".swiper-tendenze", {
          direction: "horizontal",
          loop: true,
          breakpoints: {
            300: {
                slidesPerView: 2,
                spaceBetween: 8,
              },
            500: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            575: {
              slidesPerView: 2,
              spaceBetween: 8,
            },

            767: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            991: {
              slidesPerView: 3,
              spaceBetween: 8,
            },

            1199: {
              slidesPerView: 4,
              spaceBetween: 8,
            },
          },
          pagination: {
            el: ".swiper-pagination",
            clickable: true,
          },
          on: {
            init: function () {
              console.log("swiper-tendenze initialized");
            },
          },
        });

        const swiperOfferte = new Swiper(".swiper-offerte", {
          direction: "horizontal",
          loop: true,
          slidesPerView: 5,

          pagination: {
            el: ".swiper-pagination-offerte",
            clickable: true,
          },
          on: {
            init: function () {
              console.log("swiper-offerte initialized");
            },
          },
        });

        const swiperProdotto = new Swiper(".prodotto-swiper", {
          direction: "horizontal",
          slidesPerView: 1,
          autoHeight: true,
          loop: true,
          spaceBetween: 20,
          navigation: {
            nextEl: ".swiper-button-next-prd",
            prevEl: ".swiper-button-prev-prd",
          },

          breakpoints: {
            767: {
              slidesPerView: 3,
              spaceBetween: 20,
              direction: "vertical",
            },
          },
          on: {
            init: function () {
              console.log("swiper-prodotto initialized");
            },
          },
        });

    }
    

    $.when(init_swipers()).then(function () {
      custom_js.init();
      
      custom_js.cookie_settings();

      $("#slider-prezzo").slider({
        range: true,
        min: 0,
        max: 200,
        values: [0, 100],
        slide: function (event, ui) {
          $(".prezzo-show").text(
            "€" +
              $("#slider-prezzo").slider("values", 0) +
              " - €" +
              $("#slider-prezzo").slider("values", 1)
          );
          $('input[name="prezzo-start"]').val(
            $("#slider-prezzo").slider("values", 0)
          );
          $('input[name="prezzo-end"]').val(
            $("#slider-prezzo").slider("values", 1)
          );
        },
      });
      $(".prezzo-show").text(
        "€" +
          $("#slider-prezzo").slider("values", 0) +
          " - €" +
          $("#slider-prezzo").slider("values", 1)
      );

      $(".prodotto-swiper .swiper-slide").click(function (e) {
        e.preventDefault();
        var $selectedImage = $(this).attr('href');
        
        $(".prd-image").css("background-image", "url("+$selectedImage+")");
        $(".prd-image").attr('href',$selectedImage)
      });
    });
    

  $(".loader-wrapper").fadeOut("slow", function () {
    $(this).hide();
    loader_is_showed=false
  });
  
    window.addEventListener('load', function () {
        fetch('redirect-facebook-login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({getFbLoginUrl: 1})
        }).then(response => {
            //console.log('response', response);
            if (!response.ok) {
                throw new Error('Errore nella richiesta: ' + response.status);
            }
            return response.json();
            }).then(data => {
                let urlFbLogin = data,
                fbButton = document.querySelectorAll('.facebook-button');
                if(fbButton !== null){
                    fbButton.forEach(item =>{
                        item.setAttribute('href', urlFbLogin);
                    });
                }
                
            }).catch(error => {
                console.log('Errore:', error);
            });
        
    });
  
});