(function ($) {
    $(document).ready(function () {
        console.log('newtheme2');

        //14-09-2022
        //Пуш сообщений по комерции в аналитику при успешной оплате
        $ga_order_section = $('#ga_order_id');
        if($ga_order_section.length){
            $.get("/ga/"+$ga_order_section.data('order_id'), function (data) {
                console.log('ga_DATA', data);
                window.dataLayer = window.dataLayer || [];

                if(data.obj_dr !== undefined){
                    window.dataLayer.push (data.obj_dr);
                    console.log('data.obj_dr',data.obj_dr);
                }
                if(data.obj_dr !== undefined){
                    window.dataLayer.push (data.obj_dr_ecommerce);
                    console.log('data.obj_dr_ecommerce',data.obj_dr_ecommerce);
                }

            }, "json");
        }

        //26-01-2024
        $fb_order_section = $('#fb_order_id');
        if($fb_order_section.length){
            $.get("/fb_order/"+$fb_order_section.data('order_id'), function (data) {
                console.log('FB_DATA', data);

                if(data.obj_fb !== undefined){
                    if(fbq){
                        fbq('track', 'Purchase', data.obj_fb);
                        console.log('Purchase');
                        console.log('data.obj_fb',data.obj_fb);
                    }
                }
            }, "json");
        }

        function vdzOpenCartPopup(){
            $('.cart-info-block').addClass('open');
            $('.back-block').addClass('open-cart');
            $('body').addClass('open-cart');
        }

        $('#cart,#cart a').on('click', function (e){
            e.preventDefault()
            vdzOpenCartPopup();
        });

        if($('body.site-index section.grid-banner-section').length){
            $('body.site-index section.grid-banner-section .grid-item').on('click', function (){
                window.location = $(this).find('a').attr('href') || '#';
            });
        }


        //Подписка
        $('form#vdz_subscribe').on('submit', function (e) {
            e.preventDefault();
            var $form = $(this);
            $.post($(this).attr('action'),$form.serialize())
                .done(function( data ) {
                    console.log('data:');
                    console.log(data);

                    if(data.error !== undefined){
                        Swal.fire({
                            title: data.error,
                            showCloseButton: true,
                            showCancelButton: false,
                            closeOnConfirm: true,
                            confirmButtonText: 'Попробовать еще',
                        });
                    }
                    //Если данные сохранены - обновляем блок формы
                    else if(data.success !== undefined){
                        Swal.fire({
                            title: 'Вы успешно подписались',
                            showCloseButton: true,
                            text: data.success,
                            showCancelButton: false,
                            showConfirmButton: false,
                            closeOnConfirm: false,
                            confirmButtonText: 'Продолжить',
                            //cancelButtonText: 'Продолжить',
                        });
                        if(window.Cookies){
                            Cookies.set('vdz_subscribe', 'TRUE', { expires: 365 })
                            console.log('set vdz_subscribe cookie');
                        }
                        //$('#vdz_subscribe').parent('.well').slideUp();
                    }
                    $form.trigger('reset');
                    //$form.get(0).reset();
                });
        });


        //ФИльтр по акциям в категориях и каталоге
        if($('a.vdz_sale').length){
            //console.log(window.location.search);
            var href = '#';
            if(window.location.search){
                href = window.location.pathname + window.location.search.replace('&filter_sale=1','')+'&filter_sale=1';
            }else{
                href = window.location.pathname +'?filter_sale=1';
            }
            $('a.vdz_sale').attr('href',href);
            $('a.vdz_sale').on('click',function (){
                if(/filter_sale/.test(window.location.search)){
                    window.location = window.location.pathname + window.location.search.replace('&filter_sale=1','').replace('?filter_sale=1','').replace('&filter_sale=1','');
                }else{
                    window.location = $(this).attr('href');
                }
            });
        }


        //Сортировка товаров на мобе
        $('select#vdz_sort').on('change', function (){
            var $selected = $('select#vdz_sort option:selected');
            console.log($selected.val());
            console.log($selected.data('url'));
            if($selected.data('url') !== undefined){
                window.location = $selected.data('url');
            }else{
                window.location = window.location.pathname;
            }
        });



        //Filter
        $('#filters a.filter_item_link').on('click', function (){
            window.location = $(this).attr('href');
        });
        //Filter
        // Price range.

        if($('#price_values').length) {
            var slider_min = parseInt($("#min_price").attr('min') || 0);
            var slider_max = parseInt($("#max_price").attr('max') || 1000);
            $('#slider-range').slider({
                range: true,
                orientation: 'horizontal',
                min: slider_min,
                max: slider_max,
                step: 1,
                values: [slider_min,slider_max],
                slide: function (event, ui) {
                    if (ui.values[0] == ui.values[1]) {
                        return false;
                    }

                    $('#min_price').val(ui.values[0]);
                    $('#max_price').val(ui.values[1]);
                    $('#min_price,#max_price').trigger('change');
                }
            });

            // $('#min_price').val($('#slider-range').slider('values', $("#min_price").attr('min') || 0));
            // $('#max_price').val($('#slider-range').slider('values', $("#max_price").attr('max') || 1000));



            $('#min_price, #max_price').on('change', function () {
                var min_price_range = parseInt($('#min_price').val() || 0);
                var max_price_range = parseInt($('#max_price').val() || 1000);

                if (min_price_range > max_price_range) {
                    $('#max_price').val(min_price_range);
                }

                $('#slider-range').slider({
                    values: [min_price_range, max_price_range]
                });

            });

            $('#min_price, #max_price').on('paste keyup', function () {
                var min_price_range = parseInt($('#min_price').val() || 0);
                var max_price_range = parseInt($('#max_price').val() || 1000);

                if (min_price_range == max_price_range) {

                    max_price_range = min_price_range + 10;

                    $('#min_price').val(min_price_range);
                    $('#max_price').val(max_price_range);
                }

                $('#slider-range').slider({
                    values: [min_price_range, max_price_range]
                });

            });
            var $filter_price_link = $('#filter_price_link');
            var $filter_price_min = $('#price_values input#min_price');
            var $filter_price_max = $('#price_values input#max_price');
            $('#min_price, #max_price').on('input change paste keyup', function (){
                $filter_price_link.trigger('change2new');
                //console.log($(this).val());
            });
            $filter_price_link.on('change2new',function(e){
                $(this).attr({
                    'href' : $(this).data('price_path') + 'price-' + $filter_price_min.val() + '_' + $filter_price_max.val()
                });
            });
        }




        //Обновление малой корзины в шапке и для значений в самой корзине #all_product_total
        $('#cart').on('update_small_cart', function () {
            $.get("/cart/get-small-cart-data", function (data) {
                // console.log(data);
                //Малая корзина
                $('#cart_count')
                    .text(data.count)
                    .parents('a')
                    .attr('title', data.total + ' евро');
                //
                // //Итого в корзине (на странице и в попапе)
                // $('#all_product_total').text(data.total);
                // $('#all_product_discount').text(data.discount);
                // $('#all_product_delivery').text(data.delivery);

            }, "json");
        });



        //Добавление товара в корзину
        //$('.add_to_cart').on('click', function (e) {
        //Добавление товара в корзину и для простых товаров при подгрузке
        $(document).on('click','.add_to_cart', function (e) {
            e.preventDefault();
            var fb_product_price = parseFloat($(this).data('product_price'));
            var fb_product_id = $(this).data('product_id');

            $.ajax({
                type: 'POST',
                url: '/cart/add-to-cart',
                data: {
                    'product_id': $(this).data('product_id'),
                    'product_count': 1,
                    'product_type': 'products',
                    'product_size': '',
                    'product_size_id': '',
                    'product_size_quantity': '',
                    'product_price': $(this).data('product_price'),
                    //'product_bonus': $('#add_to_cart_with_bonus').data('bonus') || 0,//Со страницы товара - сразу используем бонус
                    'product_bonus': 0,//Используем бонус только в корзине
                    // _csrf: yii.getCsrfToken(),
                    _csrf: $('meta[name="csrf-token"]').attr('content'),
                },
                success: function (data, textStatus, jqXHR) {
                    // console.log(data);
                    // console.log(textStatus);
                    // console.log(jqXHR);
                    // // var mydata = $.parseJSON(data);
                    // console.log(mydata);
                    $('#vdzCartPopup').html(data);
                    $('#cart').trigger('update_small_cart');

                    if($('#checkout').length){
                        window.location.reload();
                    }

                    // $('#cart_popup').html(data);
                    // $('#cart_widget').modal('show');

                    //25-01-2024
                    let obj_fb = {
                        value: fb_product_price,
                        currency: 'EUR',
                        content_ids: [''+fb_product_id+''],
                        content_type: 'product',
                    }
                    if(fbq){
                        fbq('track', 'AddToCart', obj_fb);
                        console.log('AddToCart');
                        console.log('obj_fb',obj_fb);
                    }


                    vdzOpenCartPopup();

                },
                error: function () {
                    $('#cart_popup').html('<div class="alert callout" data-closable>Ошибка отправки запроса.<button class="close-button" aria-label="Dismiss alert" type="button" data-close><span aria-hidden="true">&times;</span></button></div>');
                },
            });
        });

        $(document).on('click','.swal2-html-container ul.size-list a', function (e){
            e.preventDefault();
            console.log($(this).attr('href'));
            console.log(parseInt($(this).data('size_id')));
            $('#product ul.size-list a.product_sizes[data-size_id="'+parseInt($(this).data('size_id'))+'"]').trigger('click').addClass('active').parent('li').siblings().find('a').removeClass('active');
            Swal.close();
            $('#product #add_to_cart').trigger('click');
        });
        $(document).on('click','ul.size-list a.product_sizes', function (e){
            e.preventDefault();
            $size = $(this);
            $('#product #add_to_cart')
                .attr('data-product_size',$size.data('size_value'))
                .attr('data-product_size_id',$size.data('size_id'))
                .attr('data-product_size_quantity',$size.data('quantity') || 1)
                .attr('data-product_price',$size.data('price'))
            $('#product input#product_quantity').attr('max',$size.data('quantity')||1).trigger('change').trigger('input');
        });

        //Добавление товара на странице продукта с размерами
        $(document).on('click','#product #add_to_cart', function (e) {
            e.preventDefault();
            $btn = $(this);

            if(($('ul.size-list').length > 0) && !$btn.data('product_size')){
                Swal.fire({
                    title: 'Необходимо выбрать размер',
                    showCloseButton: true,
                    html: $('ul.size-list').prop('outerHTML'),
                    showCancelButton: false,
                    closeOnConfirm: true,
                    confirmButtonText: 'Ok',
                });
                return;
            }

            //У нас не может быть заказано больше чем максимальное значение
            if(($('input#product_quantity').val()*1 > $('input#product_quantity').attr('max')*1)){
                $('input#product_quantity').val($('input#product_quantity').attr('max'));
                Swal.fire({
                    title: 'Ой, у нас осталось только '+ $('input#product_quantity').attr('max') + 'шт.',
                    showCloseButton: true,
                    showCancelButton: false,
                    closeOnConfirm: true,
                    confirmButtonText: 'Ok',
                });
                //alert('Ой, у нас осталось только '+ $('input#product_quantity').attr('max') + 'шт.');
            }

            var fb_product_price = parseFloat($(this).data('product_price'));
            var fb_product_id = $(this).data('product_id');

            $.ajax({
                type: 'POST',
                url: '/cart/add-to-cart',
                data: {
                    'product_id': $(this).data('product_id'),
                    'product_count': $('input#product_quantity').val() || 1,//количество товаров которое добавляем в корзину по умолчанию 1 для страницы категорий и input#product_quantity для страницы продукции
                    'product_type': 'products',
                    'product_size': $btn.data('product_size') || '',
                    'product_size_id': $btn.data('product_size_id') || '',
                    'product_size_quantity': $btn.data('product_size_quantity') || '',
                    'product_price': $btn.data('product_price'),
                    //'product_bonus': $('#add_to_cart_with_bonus').data('bonus') || 0,//Со страницы товара - сразу используем бонус
                    'product_bonus': 0,//Используем бонус только в корзине
                    // _csrf: yii.getCsrfToken(),
                    _csrf: $('meta[name="csrf-token"]').attr('content'),
                },
                success: function (data, textStatus, jqXHR) {
                    // console.log(data);
                    // console.log(textStatus);
                    // console.log(jqXHR);
                    // // var mydata = $.parseJSON(data);
                    // console.log(mydata);
                    $('#vdzCartPopup').html(data);
                    $('#cart').trigger('update_small_cart');

                    // $('#cart_popup').html(data);
                    // $('#cart_widget').modal('show');

                    //25-01-2024
                    let obj_fb = {
                        value: fb_product_price,
                        currency: 'EUR',
                        content_ids: [''+fb_product_id+''],
                        content_type: 'product',
                    }
                    if(fbq){
                        fbq('track', 'AddToCart', obj_fb);
                        console.log('AddToCart');
                        console.log('obj_fb',obj_fb);
                    }
                    vdzOpenCartPopup();

                },
                error: function () {
                    $('#cart_popup').html('<div class="alert callout" data-closable>Ошибка отправки запроса.<button class="close-button" aria-label="Dismiss alert" type="button" data-close><span aria-hidden="true">&times;</span></button></div>');
                },
            });
        });


        //Управление количеством на странице товара
        $('#product input#product_quantity').on('change',function (){
            $('#add_to_cart').attr('data-product_count', $(this).val());
        });
        //Для моба кропка купить
        $('#product input.product_count_mobile').on('change',function (){
            $('#product input#product_quantity').val($(this).val());
            $('#product input#product_quantity').trigger('change');
            $('#add_to_cart').attr('data-product_count', $(this).val());
        });
        //Для моба кропка купить
        $('#add_to_cart_mobile').on('click',function (){
            $('#add_to_cart').trigger('click');
        });
        //Добавление кнопок для управления количеством в корзине
        $(document).on('click', '#vdzCartPopup .minus, #vdzCartPopup .plus, #product .number .minus, #product .number .plus',function(){
            var $input = $(this).siblings('input.product_count');
            var input_val = Number($input.val());
            var input_val_max = Number($input.attr('max'));

            if($(this).hasClass('plus')){
                if(input_val_max >= (input_val + 1)){
                    $input.val(input_val + 1);
                }else{
                    Swal.fire({
                        title: 'Ой, у нас осталось только '+ input_val_max + 'шт.',
                        showCloseButton: true,
                        showCancelButton: false,
                        closeOnConfirm: true,
                        confirmButtonText: 'Ok',
                    });
                }
            }else{
                //нельзя заказать меньше единицы
                if(input_val == 1) return;

                $input.val(input_val - 1);
            }
            $input.trigger('change');
            //$('#recalculation_cart').trigger('click');
            $('#vdzCartPopup').trigger('recalculation_cart');
            // console.log($input);
        });

        /*
        $('.minus').click(function () {
            var $input = $(this).parent().find('input');
            var count = parseInt($input.val()) - 1;
            count = count < 1 ? 1 : count;
            $input.val(count);
            $input.change();
            return false;
        });

        $('.plus').click(function () {
            var $input = $(this).parent().find('input');
            $input.val(parseInt($input.val()) + 1);
            $input.change();
            return false;
        });

         */


        //пересчет корзины с новыми значениями количества товаров
        $(document).on('recalculation_cart', '#vdzCartPopup', function (e) {
            e.preventDefault();
            var products_arr = [];
            $('#vdzCartPopup input.product_count').each(function (index) {
                var product_obj = {};
                // console.log((($(this).val()*1) > ($(this).attr('max')*1)));
                // console.log($(this).val())
                // console.log($(this).attr('max'))
                // console.log(typeof($(this).val()))
                // console.log(typeof($(this).attr('max')))

                //У нас не может быть заказано больше чем максимальное значение
                if(($(this).val()*1 > $(this).attr('max')*1)){
                    //alert('Доступно максимум '+ $(this).attr('max') + 'шт. товара');
                    Swal.fire({
                        title: 'Доступно максимум '+ $(this).attr('max') + 'шт. товара',
                        showCloseButton: true,
                        showCancelButton: false,
                        closeOnConfirm: true,
                        confirmButtonText: 'Ok',
                    });
                    product_obj.count = $(this).attr('max');
                }else{
                    product_obj.count = $(this).val();
                }
                // product_obj.count = ($(this).val()*1 > $(this).attr('max')*1) ?  $(this).attr('max') : $(this).val();
                $(this).val(product_obj.count);
                //  console.log(product_obj.count);
                product_obj.product_id = $(this).data('product_id');
                products_arr[index] = product_obj;
            });
            //console.log(products_arr);
            $.ajax({
                type: 'POST',
                url: '/cart/recalculation-cart',
                data: {
                    'products_arr': products_arr,
                    //_csrf: yii.getCsrfToken(),
                    _csrf: $('meta[name="csrf-token"]').attr('content'),
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.status == 'success') {
                        $('#cart').trigger('update_small_cart');
                        if(data.html){
                            $('#vdzCartPopup').html(data.html);
                        }
                    }
                    else {
                        $('#vdzCartPopup').prepend('<div class="alert callout" data-closable>Не удалось обновить корзину попробуйте снова или обновите страницу<button class="close-button" aria-label="Dismiss alert" type="button" data-close><span aria-hidden="true">&times;</span></button></div>');
                    }
                },
                error: function () {
                    $('#vdzCartPopup').prepend('<div class="alert callout" data-closable>Ошибка отправки запроса.<button class="close-button" aria-label="Dismiss alert" type="button" data-close><span aria-hidden="true">&times;</span></button></div>');
                },
            });
        });

        //Закрытие попапа
        $(document).on('click', '#vdzCartPopup .title-wrap .close', function (e) {
            e.preventDefault();
            $('.back-block').trigger('click');
        });
        //Закрытие ошибки в попапе
        $(document).on('click', '#vdzCartPopup .alert .close', function (e) {
            e.preventDefault();
            $(this).parent('.alert').remove();
        });

        //Удаление товаров в корзине
        $(document).on('click', '#vdzCartPopup .delete_cart_item, #checkout .delete_cart_item', function (e) {
            // console.log($(this));
            e.preventDefault();
            var product_id = $(this).data('product_id');
            $.ajax({
                type: 'POST',
                url: '/cart/delete-from-cart',
                data: {
                    'product_id': product_id,
                    // _csrf: yii.getCsrfToken(),
                    _csrf: $('meta[name="csrf-token"]').attr('content'),
                },
                success: function (data, textStatus, jqXHR) {
                    //Для страницы корзины
                    //$('#cart_table').prepend('<div class="success callout" data-closable>Товар удачно удален<button class="close-button" aria-label="Dismiss alert" type="button" data-close><span aria-hidden="true">&times;</span></button></div>');
                    //Удаляем HTML удаленного товара
                    //console.log($('#cart_table').find('#product_id_' + product_id));
                    $('#vdzCartPopup').find('#product_id_' + product_id).remove();
                    $('#checkout').find('#product_id_' + product_id).remove();
                    //Для попапа
                    $('#vdzCartPopup').html(data);
                    $('#cart').trigger('update_small_cart');
                    if($('#checkout').length){
                        window.location.reload();
                    }

                },
                error: function () {
                    $('#vdzCartPopup').html('<div class="alert callout" data-closable>Ошибка отправки запроса.<button class="close-button" aria-label="Dismiss alert" type="button" data-close><span aria-hidden="true">&times;</span></button></div>');
                },
            });

        });

        //Промокод
        $('form#promocode_enter').on('submit', function (e) {
            e.preventDefault();
            var $form = $(this);
            $.post($(this).attr('action'),$form.serialize())
                .done(function( data ) {
                    console.log('data:');
                    console.log(data);

                    if(data.error !== undefined){
                        Swal.fire({
                            title: data.error,
                            showCloseButton: true,
                            showCancelButton: false,
                            closeOnConfirm: true,
                            confirmButtonText: 'Попробовать еще',
                        });
                    }
                    //Если данные сохранены - обновляем блок формы
                    else if(data.success !== undefined){
                        Swal.fire({
                            title: 'Промокод успешно применен',
                            showCloseButton: true,
                            text: data.success,
                            showCancelButton: false,
                            closeOnConfirm: false,
                            confirmButtonText: 'Продолжить',
                            //cancelButtonText: 'Продолжить',
                        }).then((result) => {
                            // Reload the Page
                            window.location.reload();
                        });;
                    }
                });
        })


        $('#full_form ul.payment li a').on('click', function (e){
            e.preventDefault();
            var $a = $(this);
            $a.parent('li').siblings().find('input').prop('checked', false).attr('checked', false).trigger('change');
            $a.find('input').prop('checked', true).attr('checked', true);
            $('#payment_step input[type="hidden"]').val($a.find('input:checked').val())

            $('#fullcartbuyform-payment_service input[type="radio"]').prop('checked', false).attr('checked', false).trigger('change');
            $('#fullcartbuyform-payment_service input[type="radio"][value="'+$('#payment_step input[type="hidden"]').val()+'"]').prop('checked', true).attr('checked', true).trigger('change');

        })
        $('#full_form ul.payment input[checked]').parent('a').trigger('click');


        //Быстрый заказ в корзине
        $('a[href="#simple_form"]').on('click',function (e){
            e.preventDefault();
            $('#simple_form').toggleClass('d-none');
            $('.full_btn_wrap.end_step').toggleClass('d-none');
            $(this).toggleClass('active');
        });
        $(document).on('click','ul.payment a[data-payment]', function (){
            $('#simple_form').addClass('d-none');
            $('.full_btn_wrap.end_step').removeClass('d-none');
            $('a[href="#simple_form"]').removeClass('active');
        })

        //Быстрый заказ в корзине
        //frontend\web\js\intlTelInputSet.js - переписал под свое событие т.к. отправляло форму без проверки
        $(document).on('submit.send','form#simple_form', function (e) {
            e.preventDefault();
            // console.log($('#simple_form input[name="simple_full_phone"]').length,$('#simple_form input[name="simple_full_phone"]').val(),$('#simple_form input#customer_phone').val())
            // return;
            //if(e.namespace != 'send') return false;
            $.ajax({
                type: 'POST',
                url: '/ajax/simple-order',
                data: {
                    'name': $('#simple_form input#customer_name').val(),
                    'phone': $('#simple_form input[name="simple_full_phone"]').length ? $('#simple_form input[name="simple_full_phone"]').val() : $('#simple_form input#customer_phone').val(),
                    // _csrf: yii.getCsrfToken(),
                    _csrf: $('meta[name="csrf-token"]').attr('content'),
                },
                success: function (data, textStatus, jqXHR) {
                    $('#checkout .cart_product ').remove();
                    //Обновляем данные корзины и общей стоимости по 0
                    $('#cart').trigger('update_small_cart');
                    //Вставляем полученный HTML в попап
                    let script = $(data).find('script');
                    $('body').append(script);
                    if(window.simple_form_dr){
                        window.simple_form_dr();
                    }
                    Swal.fire({
                        title: 'Заказ отправлен',
                        showCloseButton: true,
                        html: data,
                        showCancelButton: false,
                        closeOnConfirm: true,
                        confirmButtonText: 'Ok',
                    }).then((result) => {
                        // Reload the Page
                        window.location.reload();
                    });

                },
                error: function () {
                    console.log('ERROR');
                },
            });
        });


        /*
        08-02-2022 отключение бонусов
        //Бонус на странице оформления

        //защита от 2го отправления бонусов при автоматическом применении
        let do_bonus_enter_time = 0;
        $(document).on('submit','form#bonus_enter',function (e) {
            e.preventDefault();
            if(do_bonus_enter_time > 0) return;
            do_bonus_enter_time = e.timeStamp;
            // e.stopImmediatePropagation();
            // e.stopPropagation();
            console.log(e);
            var $form = $(this);
            $.post($(this).attr('action'),$form.serialize())
                .done(function( data ) {
                    console.log('data:');
                    console.log(data);

                    if(data.error !== undefined){
                        Swal.fire({
                            title: data.error,
                            showCloseButton: true,
                            showCancelButton: false,
                            closeOnConfirm: true,
                            confirmButtonText: 'Попробовать еще',
                        });
                    }
                    //Если данные сохранены - обновляем блок формы
                    else if(data.success !== undefined){
                        Swal.fire({
                            title: 'Бонус успешно применен',
                            showCloseButton: true,
                            text: data.success,
                            showCancelButton: false,
                            closeOnConfirm: false,
                            confirmButtonText: 'Продолжить',
                            //cancelButtonText: 'Продолжить',
                        }).then((result) => {
                            // Reload the Page
                            window.location.reload();
                        });
                    }
                });
        })
        if((window.location.pathname == '/cart/checkout') && (window.location.hash == '')){
            $('form#bonus_enter').trigger('submit');
        }
        //Удаление бонуса
        $(document).on('click','#remove_bonus', function (){
            url = $(this).data('url')
            if(url){
                window.location = url;
            }
        });
         */


        //cart-checkout
        if($('body.cart-checkout').length){
            $(document).on('click','a[href="#cart"]', function (e){
                e.preventDefault();
                $('#cart').trigger('click');
            });
        }


        //Register
        $('form#registration_form').on('submit', function(e){
            e.preventDefault();
            $form = $(this);
            console.log('form::send'+$form.attr('id'));
            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: $form.serialize(),
                success: function (data, textStatus, jqXHR) {
                    var action = $form.attr('action');
                    console.log('action=',action);
                    // console.log(data);
                    // console.log(textStatus);
                    // console.log(jqXHR);
                    console.log($form.parent('.form_block'));
                    if (data.success !== undefined) {
                        //Сброс формы и скрытие
                        $form.trigger('reset')
                        // .slideUp();
                        if (data.url !== undefined) {
                            //window.location = data.url;
                        }
                        // if(action == '/ajax/auth/login'){
                        //     if( window.location.pathname == '/site/login'){
                        //         window.location.pathname = '/profile';
                        //         return;
                        //     }else{
                        //         //Перезагрузка страницы c сервера
                        //         window.location.reload(true);
                        //     }
                        // }

                        if(( action == '/ajax/auth/registration')){
                            $form.hide();
                            //Перезагрузка страницы c сервера
                            //window.location.reload(true);
                        }

                        Swal.fire({
                            title: 'Спасибо',
                            showCloseButton: true,
                            html: data.success,
                            showCancelButton: false,
                            confirmButtonText: 'Ok',
                        }).then((result) => {
                            // Reload the Page
                            if (data.url !== undefined) {
                                window.location = data.url;
                            }
                            window.location = '/';
                        });

                    } else if (data.error !== undefined){
                        Swal.fire({
                            title: 'Ошибка',
                            showCloseButton: true,
                            html: data.error,
                            showCancelButton: false,
                            confirmButtonText: 'Ok',
                        });
                    } else {
                        Swal.fire({
                            title: 'Ошибка, попробуйте снова #1',
                            showCloseButton: true,
                            showCancelButton: false,
                            confirmButtonText: 'Ok',
                        });
                    }
                },
                error: function () {
                    Swal.fire({
                        title: 'Данные не удалось отправить, попробуйте снова #2',
                        showCloseButton: true,
                        showCancelButton: false,
                        confirmButtonText: 'Ok',
                    });
                }
            });
            return false;
        });


        if($('body[class*="profile"]').length){
            $('ul.profile-menu a').each(function (e){
                if($(this).attr('href') == window.location.pathname){
                    $('ul.profile-menu a').removeClass('active');
                    $(this).addClass('active');
                }
            });

        }
        if($('body.profile-profile #user_form').length){
            $(document).on('change input','#user_form input',function(){
                $('#user_form button[type="submit"]').removeClass('hidden');
            });
        }

        $('a.track_price').on('click',function (e){
            e.preventDefault();
            Swal.fire({
                title: 'Сообщить о снижении цены',
                showCloseButton: true,
                text: 'Оставьте свой e-mail и мы уведомим вас об изменениях цены',
                input: 'email',
                // inputLabel: '',
                inputPlaceholder: 'Email',
                validationMessage: 'Неверный адрес электронной почты',
                inputAutoTrim: true,
                confirmButtonText: 'Следить за ценой',
                showLoaderOnConfirm: true,
                preConfirm: (email) => {
                    Swal.showLoading();
                    console.log('email',email);
                    $.ajax({
                        url: '/ajax/subscribe/price-track',
                        type: 'POST',
                        data: {
                            email: email,
                            link: window.location.href,
                        },
                        success: function (data, textStatus, jqXHR) {
                            // console.log(data);
                            // console.log(data.error.length);
                            // console.log(textStatus);
                            // console.log(jqXHR);
                            if(data.success){
                                Swal.fire({
                                    title: `${data.success}`,
                                    showCloseButton: true,
                                })
                            }else if(data.error){
                                Swal.showValidationMessage(
                                    `${data.error}`
                                )
                            }
                        },
                        error: function () {
                            Swal.showValidationMessage(
                                `Request failed: ${error}`
                            )
                            console.log('Error');
                        },
                    });
                },
                //allowOutsideClick: () => !Swal.isLoading()
            })


        })


        /*Сохраненние данных от оператора для быстрой оплаты заказов оформленных в 1С*/
        $('#fast_payment_operator').on('submit', function (e) {
            e.preventDefault();
            var form = $(this);
            // submit form
            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: form.serialize(),
                success: function (data, textStatus, jqXHR) {
                    // console.log(data);
                    // console.log(data.error.length);
                    // console.log(textStatus);
                    // console.log(jqXHR);
                    if(data.error.length === 0){
                        //$('.callout').hide();
                        $('.callout').removeClass('d-none');
                        $('#fast_payment_operator_content .success.callout .content').html(data.success);
                        $('#fast_payment_operator_content .success.callout').show()
                        //form.slideUp();
                        var clipboard = new ClipboardJS('span[data-clipboard-target="#vdz_link_copy"]');
                        clipboard.on('success', function(e) {
                            console.info('Action:', e.action);
                            console.info('Text:', e.text);
                            console.info('Trigger:', e.trigger);
                            e.clearSelection();
                        });

                    }else{
                        //$('.callout').hide();
                        $('.callout').removeClass('d-none');
                        $('#fast_payment_operator_content .alert.callout .content').text(data.error);
                        $('#fast_payment_operator_content .alert.callout').show();

                    }
                },
                error: function () {
                    $('#fast_payment_operator_content .alert.callout .content').text('Произошла ошибка, попробуйте снова');
                    $('#fast_payment_operator_content .alert.callout').show();
                },
            });

            //Возвращаем FALSE что бы не отправлять форму обычным методом
            return false;
        });



        //Reviews
        $(document).on('submit','form#reviews_form', function(e){
            e.preventDefault();
            $form = $(this);
            console.log('form::send'+$form.attr('id'));
            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: $form.serialize(),
                success: function (data, textStatus, jqXHR) {
                    var action = $form.attr('action');
                    console.log('action=',action);
                     console.log('data=',data);
                    $('.jBox-closeButton').trigger('click');
                    // console.log(textStatus);
                    // console.log(jqXHR);
                    if (data.success !== undefined) {
                        //Сброс формы и скрытие
                        $form.trigger('reset');
                        // .slideUp();
                        if (data.url !== undefined) {
                            //window.location = data.url;
                        }

                        Swal.fire({
                            title: 'Спасибо',
                            showCloseButton: true,
                            html: data.success,
                            showCancelButton: false,
                            confirmButtonText: 'Ok',
                        }).then((result) => {
                            // Reload the Page
                            if (data.url !== undefined) {
                                //window.location = data.url;
                            }
                            //window.location = '/';
                        });

                    } else if (data.error !== undefined){
                        Swal.fire({
                            title: 'Ошибка',
                            showCloseButton: true,
                            html: data.error,
                            showCancelButton: false,
                            confirmButtonText: 'Ok',
                        });
                    } else {
                        Swal.fire({
                            title: 'Ошибка, попробуйте снова #1',
                            showCloseButton: true,
                            showCancelButton: false,
                            confirmButtonText: 'Ok',
                        });
                    }
                },
                error: function () {
                    Swal.fire({
                        title: 'Данные не удалось отправить, попробуйте снова #2',
                        showCloseButton: true,
                        showCancelButton: false,
                        confirmButtonText: 'Ok',
                    });
                }
            });
            return false;
        });


        // console.log('phone_mask newtheme2');
        // var $phones_inputs_fields = $('input#registrationform-phone')
        //     .add('input#f_customer_phone')
        //     .add('input#customer_phone')
        // ;
        // //$phones_inputs_fields.attr('type','number');
        // $phones_inputs_fields.mask('+999999999999?9999999')

        /*2024*/
        if($('input#f_customer_phone').length){
            const customer_phone = document.querySelector('input#f_customer_phone');

            window.intlTelInput(customer_phone, {
                initialCountry: "auto",
                nationalMode: true,
                // onlyCountries: ["at", "be", "bg", "hr", "cy", "cz", "dk",
                //     "ee", "fi", "fr", "de", "gr", "hu", "ie", "il", "it", "lv",
                //     "lt", "lu", "mt", "nl", "pl", "pt", "ro", "sk", "si", "es", "se", "gb", 'ua'],
                hiddenInput: () => "full_phone",
                geoIpLookup: callback => {
                    fetch("https://ipapi.co/json")
                        .then(res => res.json())
                        .then(data => callback(data.country_code))
                        .catch(() => callback("de"));
                },
                utilsScript: "/new_js/vendor/intl-tel-input_2024/js/utils.js?1709392860975" // just for formatting/placeholders etc
            });
            const simple_form_customer_phone = document.querySelector('form#simple_form input#customer_phone');

            window.intlTelInput(simple_form_customer_phone, {
                initialCountry: "auto",
                nationalMode: true,
                // onlyCountries: ["at", "be", "bg", "hr", "cy", "cz", "dk",
                //     "ee", "fi", "fr", "de", "gr", "hu", "ie", "il", "it", "lv",
                //     "lt", "lu", "mt", "nl", "pl", "pt", "ro", "sk", "si", "es", "se", "gb", 'ua'],
                hiddenInput: () => "simple_full_phone",
                geoIpLookup: callback => {
                    fetch("https://ipapi.co/json")
                        .then(res => res.json())
                        .then(data => callback(data.country_code))
                        .catch(() => callback("de"));
                },
                utilsScript: "/new_js/vendor/intl-tel-input_2024/js/utils.js?1709392860975" // just for formatting/placeholders etc
            });
        }

        $('#f_customer_country').prepend('<option value="">Выберите страну...</option>');
        $('#f_customer_country').select2({
            // templateSelection: function (data) {
            //     console.log('data',data)
            //     if (data.id === '') { // adjust for custom placeholder values
            //         return 'Custom styled placeholder text';
            //     }
            //
            //     return data.text;
            // },
            placeholder: 'Выберите страну...',
            // placeholder: {
            //     id: '-1', // the value of the option
            //     text: 'Select an option'
            // },
        });
        // setTimeout(function (){
        // },500)
        /*2024*/


    });
})(jQuery);