jQuery(document).ready(function ($){
    if($(window).width() > 768){
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.fixed_menu').length) {
                $('.fixed_menu').removeClass('active');
            }
        });
    }
    $('.banner_items').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        infinite: true,
        adaptiveHeight: true,
        autoplaySpeed: 5000,
        dots: true,
        prevArrow: false,
        nextArrow: false,
        customPaging : function(slider, i) {
            return `<svg width="8" height="8" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="4" cy="4" r="4" fill="#C4C4C4"/>
                </svg>`;
        },
    });
    $('#toogle_menu').on('click', function (e){
        e.preventDefault();
        e.stopPropagation();
        $('.fixed_menu').toggleClass('active');
        $('body').toggleClass('show_menu')

    });
    $('.close_menu').on('click', function (){
        $('.fixed_menu').removeClass('active');
    });
    var sticky = $('.site-header').offset().top;
    var summary = $('.entry-summary').length > 0 ? $('.entry-summary').offset().top : 0;

    function stickyMenu(){
        // if(window.pageYOffset > sticky){
        //     $('.site-header').addClass('sticky');
        // }else{
        //     $('.site-header').removeClass('sticky');
        // }
        if($('.woocommerce-product-gallery').length > 0){
            var gallery = $('.woocommerce-product-gallery').offset().top + $('.woocommerce-product-gallery').height() - $(window).height();

            if(window.pageYOffset > summary) {
                if(window.pageYOffset > gallery){
                    $('.entry-summary').removeClass('sticky');
                }else{
                    $('.entry-summary').addClass('sticky');
                }
            }
        }

    }
    $(window).on('scroll', stickyMenu);
    function slideImageProduct(){

        $('.product-slider__cat').slick({
            infinite: true,
            speed: 500,
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: true,
            prevArrow: `<button type="button" class="slick-prev"><svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.0572 7.05715C11.5778 6.53645 12.4221 6.53645 12.9428 7.05715L20.9428 15.0572C21.4635 15.5778 21.4635 16.4221 20.9428 16.9428L12.9428 24.9428C12.4221 25.4635 11.5778 25.4635 11.0572 24.9428C10.5365 24.4221 10.5365 23.5779 11.0572 23.0572L18.1143 16L11.0572 8.94277C10.5365 8.42207 10.5365 7.57785 11.0572 7.05715Z" fill="#111111"/>
</svg>
</button>`,
            nextArrow: '<button type="button" class="slick-next"><svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n' +
                '<path fill-rule="evenodd" clip-rule="evenodd" d="M11.0572 7.05715C11.5778 6.53645 12.4221 6.53645 12.9428 7.05715L20.9428 15.0572C21.4635 15.5778 21.4635 16.4221 20.9428 16.9428L12.9428 24.9428C12.4221 25.4635 11.5778 25.4635 11.0572 24.9428C10.5365 24.4221 10.5365 23.5779 11.0572 23.0572L18.1143 16L11.0572 8.94277C10.5365 8.42207 10.5365 7.57785 11.0572 7.05715Z" fill="#111111"/>\n' +
                '</svg></button>'
        });
    }
    slideImageProduct();
    $('button.slick-next,button.slick-prev').on('click', function(event) {
        event.preventDefault();
    });
    $('.menu_parent').on('click', function (e){
        $('.menu_item').removeClass('active');
        $(this).parents('.menu_item').addClass('active');
        e.preventDefault();
    });
    $('.menu_item.first svg').on('click' , function (e){
        e.preventDefault();
        $(this).parents('.menu_item.active').removeClass('active');
    })
    if($("#video_intro").length){
        $("#video_intro")[0].play().catch(function(error) {
            console.error('Lỗi khi phát video:', error);
        });
        setTimeout(function () {
            $("#video_intro")[0].pause();
            $("#video_intro").hide();
        }, 9000);
    }
    $('.variation').on('click', function (e){
        e.preventDefault();
        var dom = $(this).attr('data-target');
        $(dom).addClass('show');
        $('body').addClass('open_modal');
    });
    $('.single_add_to_cart_button').append('<span class="spinner"></span>');
    $('.single_add_to_cart_button').attr('data-target', '#minicart');
    $('.single_add_to_cart_button').on('click', function(event) {
        if($(this).hasClass('disabled')) return;
        event.preventDefault();
        var form = $(this).closest('form.cart');
        data = {
            action: 'woocommerce_add_to_cart',
            product_id: $("[name=variation_id]").val() ? $("[name=variation_id]").val() : $("[name=add-to-cart]").val(),
            variation_id: $("[name=variation_id]").val(),
            quantity: 1
        }
        data = fillVariationInput(data);
        var formData = form.serialize();
        var dom = $(this).attr('data-target');
        var $thisbutton = $(this);
        $(this).addClass('loading');

        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: data,
            success: function(response) {
                if (response.error & response.product_url) {
                    window.location = response.product_url;
                    return;
                }
                if (response.fragments) {
                    $thisbutton.removeClass('loading');
                    $(dom).find('.modal-content').html(response.fragments['div.mini_cart_vn']);
                    $(dom).find('.modal-footer').html(response.fragments['cart_footer'])
                    $(dom).addClass('show');
                    $('body').addClass('open_modal');
                }
            }
        });
    });
    $('.color_filter').on('click', function (){
        $('.color_filter').removeClass('active');
        $(this).addClass('active')
    });
    $('.size_filter').on('click', function (){
        $('.size_filter').removeClass('active');
        $(this).addClass('active')
    });
    function updateQuantityItem(cart_item_key, quantity){
        var parentDiv = jQuery('.woocommerce-cart-form').length > 0 ? jQuery('.woocommerce-cart-form') : jQuery('.cart-modal .modal-content');
        parentDiv.addClass('rminiitem');
        parentDiv.addClass( 'processing' ).block({
            message: null,
            overlayCSS: {
                background: '#fff',
                opacity: 0.6
            }
        });
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: {
                action: 'update_qty_cart_item',
                cart_item_key: cart_item_key,
                quantity: quantity
            },
            beforeSend: function(response) {

            },
            complete: function(response) {
                parentDiv.removeClass( 'processing' ).unblock();
            },
            success: function(response) {
                if(response.success == false){
                    console.log(response);
                }else{
                    parentDiv.html(response.data['mini_cart']);
                    if(jQuery('.woocommerce-cart-form').length > 0){
                        parentDiv.append(response.data['cart_footer']);
                    }else{
                        jQuery('.cart-modal .modal-footer').html(response.data['cart_footer'])
                    }

                    $(document.body).trigger('wc_fragment_refresh');
                }
                parentDiv.removeClass('rminiitem');
                parentDiv.removeClass( 'processing' ).unblock();
            }
        });
    }
    $(document).on('change', '.product-quantity .qty', function(e) {
        e.preventDefault();
        var key = $(this).attr('data-key');
        var qty = $(this).val()
        qty = qty ? parseInt(qty) : 1;
        // updateQuantityItem(key, qty);
    });
    $(document).on('click', '.product-quantity .tru', function(e) {
        e.preventDefault();
        var key = $(this).attr('key');
        var qty = $(`.inp_${key}`).val()
        qty = qty ? parseInt(qty) : 1;
        if(qty > 1) qty = qty - 1;
        $(`.inp_${key}`).val(qty)
        updateQuantityItem(key, qty);
    });
    $(document).on('click', '.product-quantity .plus', function(e) {
        e.preventDefault();
        var key = $(this).attr('key');
        var qty = $(`.inp_${key}`).val()
        qty = qty ? parseInt(qty) : 0;
        qty = qty + 1;
        $(`.inp_${key}`).val(qty)
        updateQuantityItem(key, qty);
    });
    $(document).on('click', '#clear-cart', function(e) {
        e.preventDefault();
        var parentDiv = jQuery('.cart-modal .modal-content');
        parentDiv.addClass('rminiitem');
        parentDiv.addClass( 'processing' ).block({
            message: null,
            overlayCSS: {
                background: '#fff',
                opacity: 0.6
            }
        });

        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: {
                action: 'remove_cart_all_item',
            },
            beforeSend: function(response) {
            },
            complete: function(response) {
                parentDiv.removeClass('rminiitem');
                parentDiv.removeClass( 'processing' ).unblock();
            },
            success: function(response) {
                $('#minicart').find('.modal-content').html(`<p class="cart-item_empty">Chưa có sản phẩm nào trong giỏ hàng</p>`);
                jQuery('.cart-modal .modal-footer').html('')
                $(document.body).trigger('wc_fragment_refresh');
                parentDiv.removeClass('rminiitem');
                parentDiv.removeClass( 'processing' ).unblock();
            }
        });
    });
    $('#toggle_mode').on('click', function (e){
        e.preventDefault();
        $('body').toggleClass('dark')
        $(this).toggleClass('active')
    })
    const fixHeightTitle = function (){
        var width = $(window).width();
        var limit = 2;
        if(width > 768){
            limit = 4
        }
        $('.products').each(function (){
            var total = $(this).find('.product').length;
            let max = Math.floor(total / limit);
            var key = 0;

            for (var i = 0 ; i <= max ; i++){
                var heights = [];
                for (var j= 1 ; j <= limit ; j++){
                    console.log(j , 'j');
                    console.log(limit * key + j - 1 , 'j*key')
                    if($(this).find('.product').eq(limit * key + j - 1).length > 0){
                        heights.push($(this).find('.product').eq(limit * key + j - 1).find('h2').height());
                    }

                }
                console.log(heights);
                var realHeight = Math.max(...heights);
                console.log(realHeight , 'realHeight');
                for (var j= 1 ; j <= limit ; j++){
                    $(this).find('.product').eq(limit * key + j - 1).find('h2').css('height' , realHeight + 'px');
                }
                key++;
            }
        })

    }
    fixHeightTitle()
    $('#btn_search').on('click', function (e){
        e.preventDefault();
        $('.search_box').toggleClass('active');
    })

    $(document).on('click', '.product-remove', function(e) {
        e.preventDefault();
        var $thisbutton = $(this).find('.remove-mini_cart');
        var cart_item_key = $thisbutton.data('cartkey');

        var parentDiv = jQuery('.woocommerce-cart-form').length > 0 ? jQuery('.woocommerce-cart-form') : jQuery('.cart-modal .modal-content');
        parentDiv.addClass('rminiitem');
        parentDiv.addClass( 'processing' ).block({
            message: null,
            overlayCSS: {
                background: '#fff',
                opacity: 0.6
            }
        });
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: {
                action: 'remove_cart_item',
                cart_item_key: cart_item_key
            },
            beforeSend: function(response) {
                $thisbutton.addClass('loading');
            },
            complete: function(response) {
                $thisbutton.removeClass('loading');
                parentDiv.removeClass( 'rminiitem' )
                parentDiv.removeClass( 'processing' ).unblock();
            },
            success: function(response) {
                if(response.success == false){
                    console.log(response);
                }else{
                    parentDiv.html(response.data['mini_cart']);
                    if(jQuery('.woocommerce-cart-form').length > 0){
                        parentDiv.append(response.data['cart_footer']);
                    }else{
                        jQuery('.cart-modal .modal-footer').html(response.data['cart_footer'])
                    }

                    $(document.body).trigger('wc_fragment_refresh');
                    parentDiv.removeClass( 'rminiitem' )
                    parentDiv.removeClass( 'processing' ).unblock();
                    if(response.data.redirect != '' && jQuery('.woocommerce-cart-form').length > 0) location.href = response.data.redirect
                }

            }
        });
    });
    $('.size_list ul li').on('click', function (){
        if($(this).hasClass('disabled')) return;
        $('.size_list ul li').removeClass('active');
        $(this).addClass('active');
        $('#val_size').text($(this).text())
    });
    $('.close_modal').on('click', function (){
       $(this).parents('.modal-product').removeClass('show');
        $('body').removeClass('open_modal');
    });
    $('.color_list ul li').on('click', function (e){
        e.preventDefault();
        $('.color_list ul li').removeClass('active');
        $(this).addClass('active');
        changeVariation()
        $('#val_color').text($(this).find('p').text());
        $('.current_color').css('background', $(this).attr('data-code'))
    });
    var compage_page = 0;
    function loadCompareProducts(){
        var btn = $('#btn_compare');
        compage_page++;
        btn.addClass('loading');
        var data = {
            nonce: ethan_frontend.nonce,
            action: 'load_compare_products',
            product_id: ethan_frontend.product_id,
            page: compage_page,
        };
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: data,
            success: function(response) {
                console.log(response)
                btn.removeClass('loading')
                $('.compare_loading').removeClass('active');
                $('.list_compare_products').append(response.data.content)
                $('#compare_products').addClass('show');
                $('body').addClass('open_modal');
                if(response.data.content.trim() == ''){
                    $('.compare_loading').hide();
                }
            },
            error: function (err){
                $('.compare_loading').removeClass('active');
                console.log(err)
                btn.removeClass('loading');
            }
        });
    }
    $('#btn_compare').on('click', function (e){
        e.preventDefault();
        loadCompareProducts();

    });
    $('#compare_products').on('scroll', function (){
        var element = $(this);
        var scrollTop = element.scrollTop();
        var scrollHeight = element.prop('scrollHeight');
        var clientHeight = element.innerHeight();
        if (scrollTop + clientHeight >= scrollHeight - 10) {
            if(!$('.compare_loading').hasClass('active')){
                console.log('cccc');
                $('.compare_loading').addClass('active');
                loadCompareProducts();
            }

        }
    })
    $(document).on('click', '.start_compare', function (e){
        e.preventDefault();
        var product_id = $(this).attr('data-productid');
        $.ajax({
            url: ethan_frontend.ajaxurl,
            method: 'POST',
            data: {nonce: ethan_frontend.nonce, product_id: product_id, action: 'ethan_data_product'},
            success: function (response) {
                var data = response.data;
                $('.modal-content .other_product .product_name').html(data.title);
                $('.modal-content .other_product .product_price .price').html(data.price);
                $('.modal-content .item_compare:not(.item_left) .product_image').html(data.image);
                $('.modal-content .other_product .brands').html(data.brand);
                $('.modal-content .other_product .before_brand').html(data.sku);
                $('#table_right').html(data.table_html)
                $('#right_desc p').html(data.description);
                $('#compare_product').addClass('show');
                $('#compare_products').removeClass('show');
            },
            error: function (error) {
                console.error('Lỗi:', error);
            }
        })
    })
    $('.product_modal_bg').on('click', function (){
        $('.modal-product').removeClass('show')
        $('body').removeClass('open_modal');
    })
    $('.end-checkout').on('click',function(){
        $(this).hide();
        $('.button_action_ql-mobie').show();
        $('.checkout-container__sp').hide();
        $('.checkout-container__tt').show();
        window.scrollTo(0, 0);
    });

    $('.button_action_ql-mobie').on('click',function(){
        $(this).hide();
        $('.end-checkout').show();
        $('.checkout-container__sp').show();
        $('.checkout-container__tt').hide();
        window.scrollTo(0, 0);
    });

    function changeVariation (){
        if($('.variations_form').length > 0){
            let jsonData = $('.variations_form').attr('data-product_variations');
            let variations = JSON.parse(jsonData);
            let size = $('.size.active').length > 0 ? $('.size.active').attr('data-value') : '';
            let color = $('.color.active').length > 0 ? $('.color.active').attr('data-value') : '';
            let findVariation = variations.find((variation) => {
                let flag = false
                if(size){
                    flag = variation['attributes']['attribute_pa_kich-thuoc'] == size;
                }
                if(color){
                    flag = variation['attributes']['attribute_pa_mau-sac'] == color
                }
                if(!size && !color) flag = true
                return flag
            });
            console.log(findVariation);
            if(findVariation.image){
                $('.woocommerce-product-gallery__image img').attr('src' , findVariation.image.full_src)
                $('.woocommerce-product-gallery__image img').attr('srcset' , findVariation.image.full_src)
                $('.woocommerce-product-gallery__image img').attr('data-src' , findVariation.image.full_src)

                $('.woocommerce-product-gallery__image img').attr('data-large_image' , findVariation.image.full_src)
            }
            $('.before_brand').text(findVariation.sku)
            $('.summary .price').text(convertPriceVND(findVariation.display_price))
            // $('.product_title').text()
        }
    }

    function fillVariationInput(data){
        if($('.variations_form').length > 0){
            let jsonData = $('.variations_form').attr('data-product_variations');
            let variations = JSON.parse(jsonData);
            let size = $('.size.active').length > 0 ? $('.size.active').attr('data-value') : '';
            let color = $('.color.active').length > 0 ? $('.color.active').attr('data-value') : '';
            let findVariation = variations.find((variation) => {
                let flag = false
                if(size){
                    flag = variation['attributes']['attribute_pa_kich-thuoc'] == size;
                }
                if(color){
                    flag = variation['attributes']['attribute_pa_mau-sac'] == color
                }
                if(!size && !color) flag = true
                return flag
            });
            data.attributes = {}
            console.log(findVariation);
            $.each(findVariation.attributes , function (index,attribute){
                data.attributes[index] = attribute
            });
            $('input[name=variation_id]').val(findVariation.variation_id)
        }
        return data
    }

    function getColorProperty(){
        if($('.variations_form').length > 0){
            let jsonData = $('.variations_form').attr('data-product_variations');
            let variations = JSON.parse(jsonData);
            let firstVariation = variations[0];
            $('input[name=variation_id]').val(firstVariation.variation_id);
            console.log(firstVariation)
            $('.woocommerce-product-gallery__image img').attr('src' , firstVariation.image.full_src)
            $('.woocommerce-product-gallery__image img').attr('srcset' , firstVariation.image.full_src)
            $('.woocommerce-product-gallery__image img').attr('data-src' , firstVariation.image.full_src)
            $('.woocommerce-product-gallery__image img').attr('data-large_image' , firstVariation.image.full_src)
            $('.before_brand').text(firstVariation.sku)
            $('.summary .price').text(convertPriceVND(firstVariation.display_price))
            if(firstVariation.is_in_stock){
                $('.single_add_to_cart_button').removeClass('disabled')
                $('.single_add_to_cart_button').text('Thêm vào giỏ hàng')
            }else{
                $('.single_add_to_cart_button').addClass('disabled')
                $('.single_add_to_cart_button').text('Tạm hết hàng')
            }
            let sizeText = $('.size.active').length > 0 ? $('.size.active').text() : '';
            $('#val_size').text(sizeText)
            if($('.color').length == 0) return;

            let size = $('.size.active').length > 0 ? $('.size.active').attr('data-value') : false;
            let newVariations = variations.filter((variation, index) => {
                if(typeof variation['attributes']['attribute_pa_kich-thuoc'] != 'undefined'){
                    if(variation['attributes']['attribute_pa_kich-thuoc'] == size){
                        return true;
                    }
                }
                return index < $('.color').length;
            });
            $('.color').each(function (index){
                let color = $(this).attr('data-value');
                let findVariation = newVariations.find((variation) => {
                    if(typeof variation['attributes']['attribute_pa_mau-sac'] != 'undefined'){
                        if(variation['attributes']['attribute_pa_mau-sac'] == color){
                            return true;
                        }
                    }
                    return false;
                })
                if(findVariation){
                    if(index == 0){
                        $('.current_color').css({
                            'background' : findVariation.color
                        })
                        $('#val_color').text($(this).find('.color_name').text());
                        $('.current_color').css('background', $(this).attr('data-code'))
                        $('input[name=variation_id]').val(findVariation.variation_id);
                    }
                    $(this).find('.color_image').attr('src' , findVariation.image.url);
                    $(this).find('.color_image').attr('alt' , findVariation.image.alt);
                }
            });
        }
    }
    if($('body').hasClass('single-product')){
        getColorProperty();
    }


    var $popup = $('#popupct');

    function openPopup() {
        $popup.fadeIn();
    }

    function closePopup() {
        $popup.fadeOut();
    }

    $('.button_action_dh').on('click',function(){

    });

    $(window).on('click', function(event) {
        if ($(event.target).is($popup)) {
            closePopup();
        }
    });
    $('.btn_filter').on('click' , function (e){
        e.preventDefault();
        $('#filter').addClass('show');
        $('body').addClass('open_modal');
    })
    function convertPriceVND (number){
        number = parseInt(number);
        return new Intl.NumberFormat('es-US', { style: 'currency', currency: 'VND' }).format(
            number
        );
    }
    var startSlider = document.getElementById('slider-range');

    if(startSlider){
        var sliderStart = jQuery('#slider-range').attr('data-start')
        var sliderEnd = jQuery('#slider-range').attr('data-end')
        noUiSlider.create(startSlider, {
            start: [sliderStart, sliderEnd],
            behaviour: 'drag',
            connect: true,
            limit: 500000000,
            step: 10000,
            range: {
                'min': 10000,
                'max': 500000000
            }
        });
        startSlider.noUiSlider.on('update', function (values, handle, unencoded) {
            $("#rangeMin").text(convertPriceVND(values[0]));
            $("#rangeMax").text(convertPriceVND(values[1]));
        });
    }
    // $("#slider-range").slider({
    //     range: true,
    //     min: 10000,
    //     max: 500000000,
    //     values: [10000, 10000],
    //     step: 10000,
    //     slide: function(event, ui) {
    //         var from = convertPriceVND(ui.values[0])
    //         var to = convertPriceVND(ui.values[1])
    //         $("#rangeMin").text(from);
    //         $("#rangeMax").text(to);
    //     }
    // });


    // $("#rangeMin").text(convertPriceVND($("#slider-range").slider("values", 0)));
    // $("#rangeMax").text(convertPriceVND($("#slider-range").slider("values", 1)));
    $('#filter_product').on('click' , function (e){
        e.preventDefault();
        var fields = [
            {
                key : 'orderby',
                name: 'orderby',
                val : jQuery('[name="orderby"]:checked').val()
            },
            {
                key : 'brand',
                name: 'brand',
                val : jQuery('[name="brand"]:checked')
            },
            {
                key : 'price',
                name: 'price',
            },
            {
                key : 'size',
                name: 'size',
                val : jQuery('.size_filter.active').length > 0 ?
                    jQuery('.size_filter.active').attr('data-value') : ''
            },
            {
                key : 'color',
                name: 'color',
                val : jQuery('.color_filter.active').length > 0 ?
                    jQuery('.color_filter.active').attr('data-value') : ''
            },
        ]
        var href = location.href;
        fields.forEach(field => {
            if(field.key == 'price'){
                var values = startSlider.noUiSlider.get();
                var from = parseInt(values[0]);
                var to = parseInt(values[1]);
                if(from > 0 && to > 10000){
                    href = addParameter(href ,'price_from' ,from);
                    href = addParameter(href ,'price_to' ,to);
                }
                return;
            }
            if(field.key == 'brand'){
                var brands = []
                field.val.each(function (){
                    var b_val = $(this).val();
                    brands.push(b_val)
                });

                if(brands.length > 0){
                    href = addParameter(href ,field.name ,brands.join(','));
                }
                return;
            }
            var val = field.val;
            if(val){
                href = addParameter(href ,field.name ,val);
            }
        });
        location.href = href;
    });
    jQuery('.remove_filter a').on('click' , function (e){
        e.preventDefault();
    });

    $('.choose_other').on('click', function(e){
        e.preventDefault();
        $('#compare_product').removeClass('show');
        $('#compare_products').addClass('show');
    });
    var paged = 3;
    $('#more_product').on('click', function (e){
        e.preventDefault();
        var btn = $(this);
        btn.addClass('loading');
        paged++;
        var fields = [
            {
                key : 'orderby',
                name: 'orderby',
                dom : jQuery('[name="orderby"]:checked')
            },
            {
                key : 'brand',
                name: 'brand',
                dom : jQuery('[name="brand"]:checked')
            },
            {
                key : 'price',
                name: 'price',
            }
        ];
        var data = {
            nonce: ethan_frontend.nonce,
            action: 'more_products',
            page: paged,
            category: ethan_frontend.category_id,
        };
        fields.forEach(field => {
            if(field.key == 'price'){
                var values = startSlider.noUiSlider.get();
                var from = parseInt(values[0]);
                var to = parseInt(values[1]);
                if(from > 0 && to > 10000){
                    data.price_from = from;
                    data.price_to = to;
                }
                return;
            }
            var val = field.dom.val();
            if(val){
                data[field.name] = val;
            }
        });
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: data,
            success: function(response) {
                btn.removeClass('loading')
                jQuery('.products .row').append(response.data.content);
                $('.product-slider__cat.slick-initialized').slick('unslick');
                slideImageProduct()
            },
            error: function (err){
                console.log(err)
                btn.removeClass('loading');
            }
        });
    })
    var post_paged = 3;
    $('#more_post').on('click' , function (e){
        post_paged++;
        var data = {
            nonce: ethan_frontend.nonce,
            action: 'more_posts',
            page: post_paged,
            category: ethan_frontend.category_id ? ethan_frontend.category_id : 0,
        };
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: data,
            success: function(response) {
                btn.removeClass('loading')
                jQuery('.post_wrap .row').append(response.data.content);
                // $('.product-slider__cat.slick-initialized').slick('unslick');
                // slideImageProduct()
            },
            error: function (err){
                console.log(err)
                btn.removeClass('loading');
            }
        });
    });
    $('#all_post').on('click' , function (e){
        e.preventDefault();
        var data = {
            nonce: ethan_frontend.nonce,
            action: 'store_task',
        };
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: data,
            success: function(response) {

            },
            error: function (err){
                console.log(err)
            }
        });
    });
});
function addParameter(url, parameterName, parameterValue, atStart/*Add param before others*/) {
    var replaceDuplicates = true;
    var urlhash = '';
    if (url.indexOf('#') > 0) {
        var cl = url.indexOf('#');
        urlhash = url.substring(url.indexOf('#'), url.length);
    } else {
        urlhash = '';
        cl = url.length;
    }
    var sourceUrl = url.substring(0, cl);
    var urlParts = sourceUrl.split("?");
    var newQueryString = "";
    if (urlParts.length > 1){
        var parameters = urlParts[1].split("&");
        for (var i = 0; (i < parameters.length); i++)
        {
            var parameterParts = parameters[i].split("=");
            if (!(replaceDuplicates && parameterParts[0] == parameterName))
            {
                if (newQueryString == "")
                    newQueryString = "?";
                else
                    newQueryString += "&";
                newQueryString += parameterParts[0] + "=" + (parameterParts[1] ? parameterParts[1] : '');
            }
        }
    }
    if (newQueryString == "") newQueryString = "?";
    if (atStart) {
        newQueryString = '?' + parameterName + "=" + parameterValue + (newQueryString.length > 1 ? '&' + newQueryString.substring(1) : '');
    } else {
        if (newQueryString !== "" && newQueryString != '?')
            newQueryString += "&";
        newQueryString += parameterName + "=" + (parameterValue ? parameterValue : '');
    }
    return urlParts[0] + newQueryString + urlhash;
};
