var jwsThemeWooModule;
(function($) {
    "use strict";
    jwsThemeWooModule = (function() {
        return {
            init: function() {
                this.jws_rent_price();
                this.product_rent_item();
                this.product_rent_single();
                this.jws_product_tabs_block();
                this.related_slider();
                this.quickViewInit();
                this.filterAjax();
                this.productImagesGallery();
                this.productImages();
                this.share_button();
                this.product_rent_cart();
                this.product_category_slider();
                this.shop_sidebar();
                this.addToCartAllTypes();
            },
               addToCartAllTypes: function() {
                // AJAX add to cart for all types of products
                
               $('body').on('click' , '.show_box_added' , function() {
                    $(this).parents('.wash_payment_list').toggleClass('active');
                    $(this).next('.box_added_content').slideToggle();
               });
                $('body').on('submit', '.main-product.product form.cart', function(e) {
                    e.preventDefault();
                    var $form = $(this),
                        $thisbutton = $form.find('.single_add_to_cart_button'),
                        data = $form.serialize();
                    data += '&action=jws_ajax_add_to_cart';
                    if ($thisbutton.val()) {
                        data += '&add-to-cart=' + $thisbutton.val();
                    }
                    $thisbutton.removeClass('added not-added');
                    $thisbutton.addClass('loading');
                    // Trigger event
                    $(document.body).trigger('adding_to_cart', [$thisbutton, data]);
  
                    $.ajax({
                        url: jws_script.ajax_url,
                        data: data,
                        method: 'POST',
                        success: function(response) {
                            if (!response) {
                                return;
                            }
                         
                            var this_page = window.location.toString();
                            this_page = this_page.replace('add-to-cart', 'added-to-cart');
                            if (response.error && response.product_url) {
                                window.location = response.product_url;
                                return;
                            }
                            // Redirect to cart option
                            if (wc_add_to_cart_params.cart_redirect_after_add === 'yes') {
                                window.location = wc_add_to_cart_params.cart_url;
                                return;
                            } else {
                                $thisbutton.removeClass('loading');
                                $('.jws-mini-cart-wrapper ').removeClass('acttive');
                                var fragments = response.fragments;
                                var cart_hash = response.cart_hash;
                                // Block fragments class
                                if (fragments) {
                                    $.each(fragments, function(key) {
                                        $(key).addClass('updating');
                                    });
                                }
                                // Replace fragments
                                if (fragments) {
                                    $.each(fragments, function(key, value) {
                                        $(key).replaceWith(value);
                                    });
                                }
                                // Show notices
                                if (response.notices.indexOf('error') > 0) {
                                    $('body').append(response.notices);
                                    $thisbutton.addClass('not-added');
                                } else {
                                    // Changes button classes
                                    $thisbutton.addClass('added');
                                    // Trigger event so themes can refresh other areas
                                    $(document.body).trigger('added_to_cart', [fragments, cart_hash, $thisbutton]);
                                }
                            }
                        },
                        error: function() {
                            console.log('ajax adding to cart error');
                        },
                        complete: function() {},
                    });
                });
            },
            shop_sidebar :function() { 
                 $(document).on("click", '.toggle-shop-sidebar' , function() {   
                    $('.shop-sidebar').toggleClass('active');
                 });  
                  $(document).on("click", function(e) {
                    if ($(e.target).is(".shop-sidebar,.shop-sidebar *,.toggle-shop-sidebar,.toggle-shop-sidebar *") === false) {
                      $('.shop-sidebar').removeClass('active');
                    }
                  }); 
            },
            product_category_slider: function(){
                $('.idealautoduct-category-list ul').not('.slick-initialized').slick({
                    swipeToSlide: true,
                    arrows: false,
                });  
             }, 
            related_slider: function(){
                $('.related-slider').not('.slick-initialized').slick({
                    swipeToSlide: true,
                    prevArrow: '<span class="jws-carousel-btn prev-item"><i class="jws-icon-arrow_carrot-left"></i></span>',
                    nextArrow: '<span class="jws-carousel-btn next-item "><i class="jws-icon-arrow_carrot-right"></i></span>',
                });  
             },   
           product_rent_single: function(){   
                if($('.rent-gallery').length > 0) {
                  var swiper = new Swiper('.rent-gallery', {
                  pagination: {
                    el: '.swiper-pagination',
                    dynamicBullets: true,
                    clickable: true,
                  },
                  navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                  },
                });      
                }
               
                         
                 $('.main-product.rent form.form-extras').on('change', function (event) {
                 
                  var local_in = $(this).find('.formSearchUpLocation2').val(),   
                  local_off = $(this).find('.formSearchOffLocation2').val(),
                  date_in = $(this).find('.jws-date-timepicker-start').val(),
                  date_off = $(this).find('.jws-date-timepicker-end').val();  
                  
                  if(local_in == 'none' || local_off == 'none' || date_in == '' || date_off == '') {
                    return;
                  }
              
                  $('.cal-price-total').addClass('loading');  
                   var form = $(this),
                  id =  form.data('product_id');
               
                  $.ajax({
                  type: 'post',
                  dataType: 'json',
                  url: jws_script.ajax_url,
                  data: {
                      id: id, 
                      form: form.serialize(),
                      action: 'jws_calculate_inventory_data',
                  },
                  success: function (response) {

                    
                    
                     if(response.check_available) {
                        $('.cal-price-total').html('<div class="check_available woocommerce-error" role="alert">'+response.check_available+'</div>');
                        $('.cal-price-total').removeClass('loading');
                       $('.extra-option-list , #request_car_btn , .btn-or , #reservation_car_btn').hide();
                        return false;
                     } 
                     
                     let priceBreakdownMarkupContent = '<ul class="ct_ul_ol">';
                      for (const key in response) { 
                      if(response[key]['name'] == 'Total') { priceBreakdownMarkupContent += '<div>';  }  
                      priceBreakdownMarkupContent += `<li class="${key}"><span class="name">${response[key]['name']}</span> <span class="price">${response[key]['cost']}</span></li>`;
                      if(response[key]['name'] == 'Total') { priceBreakdownMarkupContent += '</div>';  }  
                      }
                      priceBreakdownMarkupContent += '</ul>';
                      $('.cal-price-total').html(priceBreakdownMarkupContent);
                      $('.extra-option-list , #request_car_btn , .btn-or , #reservation_car_btn').show();
                      $('.cal-price-total').removeClass('loading');
                  },
                });  
                }); 
                 $('.more_extra_btn').on('click', function(e){
                    e.preventDefault();
                    $(this).toggleClass('active');
                   $(this).parents('.form-extras').find('.more_extra').slideToggle();
                });  
                $('.main-product.rent form.form-extras').change(); 
            },
            
           product_rent_item: function(){
            if (typeof($.fn.magnificPopup) == 'undefined') return;
            $(document).on('click', '.show-detail', function(e) {
                    e.preventDefault();
                    $(this).toggleClass('active');
                   $(this).parents('.product-item-inner').find('.content-detail').slideToggle();
                });  
                
                  $('.open-taxbox a').magnificPopup({
                  type: 'inline',
                  midClick: true,
                  mainClass: 'mfp-fade'
                });  
            },
            
            product_rent_cart: function(){  
            $(document).on('click', '.show-rent-info', function(e) {
                    $(this).toggleClass('active');
                   $(this).next('.jws_options_table').slideToggle();
                });  
             
            },
             
            jws_rent_price: function(){
                if (jQuery.ui) {
                    var priceSliderRange = jQuery('#slider-rent-range');
                    if (jQuery(priceSliderRange).length) {
                        var amount = jQuery(".slider-result");
                        var amount_price = jQuery("#amout_rating");
                        var space = '';
                        if (jws_script.currency_pos == 'right_space' || jws_script.currency_pos == 'left_space') {
                            space = ' ';
                        }
     
                        jQuery(priceSliderRange).slider({
                            range: true,
                            min: parseInt(amount.data('min')),
                            max: parseInt(amount.data('max')),
                            step: 10,
                            values: [amount.data('value_min'), amount.data('value_max')],
                            slide: function (event, ui) {
                        
                                if (jws_script.currency_pos == 'right' || jws_script.currency_pos == 'right_space') {
                                    amount.text(ui.values[0] + space + jws_script.currency + " - " + ui.values[1] + space + jws_script.currency);
                                    amount_price.val(ui.values[0] + ',' + ui.values[1]);
                                } else {
                   
                  
                                    amount.text(jws_script.currency + space + ui.values[0] + " - " + jws_script.currency + space + ui.values[1]);
                                    
                                    amount_price.val(ui.values[0] + ',' + ui.values[1]);
                                }
                            },
                            change: function( event, ui ) {
                
                				$( document.body ).trigger( 'price_slider_change', [ ui.values[0], ui.values[1] ] );
                			}
                        });
            
                        if (jws_script.currency_pos == 'right' || jws_script.currency_pos == 'right_space') {
                            amount.text(
                                priceSliderRange.slider("values", 0) + space + jws_script.currency +
                                " - " + priceSliderRange.slider("values", 1) + space + jws_script.currency
                            );
                        } else {
                            amount.text(
                                jws_script.currency + space + priceSliderRange.slider("values", 0) +
                                " - " + jws_script.currency + space + priceSliderRange.slider("values", 1)
                            );
                        }
                        amount_price.val(
                            priceSliderRange.slider("values", 0) + "," + priceSliderRange.slider("values", 1)
                        );
            
                    }
                    
                                                            
                } 
            },
            
            //Woo Popuop
            jws_product_popup: function(){
                $('.jws-popup-woo').magnificPopup({
                  type:'inline',
                  removalDelay: 500, //delay removal by X to allow out-animation
                  mainClass: 'mfp-zoom-in mfp-img-mobile',
                  midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href.
                });
            },
            //Product tabs
            jws_product_tabs_block: function(){
                $('.accordion-active .wc-tab').show();
                $(document).on('click', '.tabs li a', function () {
        
                    $('.jws-group-accordion.accordion-active').removeClass('accordion-active');
    
                    $($(this).attr('href')).closest('.jws-group-accordion').addClass('accordion-active');
                });
                $(document).on('click', '.jws-group-accordion .tab-heading', function () {
                
                    let tab_is_activated = $(this).closest('.accordion-active')[0];
                    $('.woocommerce-tabs .accordion-active .wc-tab').slideUp();
                    $('.woocommerce-tabs .accordion-active').removeClass('accordion-active');
                    if (!tab_is_activated) {
                        $(this).closest('.jws-group-accordion').toggleClass('accordion-active');
                        $(this).next('.wc-tab').slideToggle();
        
                        if ($('.woocommerce-tabs .tabs.wc-tabs')[0]) {
                            let id = $(this).next('.wc-tab').attr('id');
                            $('.woocommerce-tabs .tabs.wc-tabs .active').removeClass('active');
                            $('.woocommerce-tabs .tabs.wc-tabs a[href="#' + id + '"]').parent().addClass('active');
                        }
                    }
                });
            },
            
             woocommerceCategoryWidget: function() {
              $('.product-categories .cat-parent ').append("<span class='cat_btn lnr lnr-chevron-down'></span>");
              $("body").on("click", ".product-categories .cat-parent > .cat_btn", function(e) {
                var t = $(this).parent(),
                  n = $(t).parent();
                if ($(t).hasClass("active")) $(t).find("> ul").slideUp(200).parent().removeClass("active");
                else {
                  var s = $(n).children("li.active");
                  $(s).removeClass("active").children("ul").css({
                    height: "auto"
                  }).slideUp(200), $(t).children("ul").slideDown(200).parent().addClass("active")
                }
                return !1
              })
            },
   
             mobile_shop_filter: function(){
                $('.sidebar-mobile a').magnificPopup({
                  type:'inline',
                  mainClass: '',
                  midClick: true,
                  callbacks: {
                    beforeOpen: function() {
                        this.st.mainClass = 'shop-sidebar-click sidebar-mobile-wap';
                     },
                     afterClose: function() {
                           $('.shop-sidebar').removeClass('mfp-hide');
                     }},
                });
                   
            },
            

             
             swatchesVariations: function() {
                var $variation_forms = $('.variations_form'),
                    variationGalleryReplace = false;
                // Firefox mobile fix
                $('.variations_form .label').on('click', function(e) {
                    if ($(this).siblings('.value').hasClass('with-swatches')) {
                        e.preventDefault();
                    }
                });
                $variation_forms.each(function() {
                    var $variation_form = $(this);
                    if ($variation_form.data('swatches')) return;
                    $variation_form.data('swatches', true);
                    // If AJX
                    if (!$variation_form.data('product_variations')) {
                        $variation_form.find('.swatches-select').find('> div').addClass('swatch-enabled');
                    }
                    if ($('.swatches-select > div').hasClass('active-swatch')) {
                        $variation_form.addClass('variation-swatch-selected');
                    }
                    $variation_form.on('click', '.swatches-select > div', function() {
                            var value = $(this).data('value');
                            var id = $(this).parent().data('id');
                            $variation_form.trigger('check_variations', ['attribute_' + id, true]);
                            resetSwatches($variation_form);
                            if ($(this).hasClass('active-swatch')) {
                                return;
                            }
                            if ($(this).hasClass('swatch-disabled')) return;
                            $variation_form.find('select#' + id).val(value).trigger('change');
                            $(this).parent().find('.active-swatch').removeClass('active-swatch');
                            $(this).addClass('active-swatch');
                            resetSwatches($variation_form);
                        })
                        // On clicking the reset variation button
                        .on('click', '.reset_variations', function(event) {
                            $variation_form.find('.active-swatch').removeClass('active-swatch');
                        })
                        .on('reset_data', function() {
                            var all_attributes_chosen = true;
                            var some_attributes_chosen = false;
                            $variation_form.find('.variations select').each(function() {
                                var attribute_name = $(this).data('attribute_name') || $(this).attr('name');
                                var value = $(this).val() || '';
                                if (value.length === 0) {
                                    all_attributes_chosen = false;
                                } else {
                                    some_attributes_chosen = true;
                                }
                            });
                            if (all_attributes_chosen) {
                                $(this).parent().find('.active-swatch').removeClass('active-swatch');
                            }
                            $variation_form.removeClass('variation-swatch-selected');
                            var $mainOwl = $('.woocommerce-product-gallery__wrapper.owl-carousel'),
                                $slider_wap = $('.woocommerce-product-gallery');
                            resetSwatches($variation_form);
                            if (!isQuickShop($variation_form)) {
                                scrollToTop();
                            }
                            if (!$mainOwl.hasClass('owl-carousel')) return;
                            if ($slider_wap.hasClass('image_slider_center')) {
                                $mainOwl = $mainOwl.owlCarousel({
                                    center: true,
                                    loop: true,
                                    nav: true,
                                    navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                                    responsive: {
                                        979: {
                                            items: 3
                                        },
                                        768: {
                                            items: 3
                                        },
                                        479: {
                                            items: 1,
                                            center: false
                                        },
                                        0: {
                                            items: 1,
                                            center: false
                                        }
                                    },
                                })
                            } else {
                                $mainOwl = $mainOwl.owlCarousel({
                                    loop: false,
                                    margin: 10,
                                    nav: true,
                                    navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                                    items: 1
                                })
                            }
                            $mainOwl.trigger('refresh.owl.carousel');
                            $mainOwl.trigger('to.owl.carousel', 0);
                            replaceMainGallery('default', $variation_form);
                        })
                        // Update first tumbnail
                        .on('reset_image', function() {
                            var $thumb = $('.thumbnails .product-image-thumbnail img').first();
                            if (!isQuickView() && !isQuickShop($variation_form)) {
                                $thumb.wc_reset_variation_attr('src');
                            }
                        })
                        .on('show_variation', function(e, variation, purchasable) {
                            if (!variation.image.src) {
                                return;
                            }
                            // See if the gallery has an image with the same original src as the image we want to switch to.
                            if (isQuickView()) {
                                var galleryHasImage = $variation_form.parents('.single-product-content').find('.thumbnails .product-image-thumbnail img[data-o_src="' + variation.image.thumb_src + '"]').length > 0;
                                var $firstThumb = $variation_form.parents('.single-product-content').find('.thumbnails .product-image-thumbnail img').first();
                            } else {
                                var galleryHasImage = $variation_form.parents('body').find('.thumbnails .product-image-thumbnail img[data-o_src="' + variation.image.thumb_src + '"]').length > 0;
                                var $firstThumb = $variation_form.parents('body').find('.thumbnails .product-image-thumbnail img').first();
                            }
                            // If the gallery has the image, reset the images. We'll scroll to the correct one.
                            if (galleryHasImage) {
                                $firstThumb.wc_reset_variation_attr('src');
                            }
                            if (!isQuickShop($variation_form) && !replaceMainGallery(variation.variation_id, $variation_form)) {
                                if ($firstThumb.attr('src') != variation.image.thumb_src) {
                                    $firstThumb.wc_set_variation_attr('src', variation.image.src);
                                }
                                jwsThemeWooModule.initZoom();
                            }
                            $variation_form.addClass('variation-swatch-selected');
                            if (!isQuickShop($variation_form) && !isQuickView()) {
                                scrollToTop();
                            }
                            var $mainOwl = $('.woocommerce-product-gallery__wrapper.owl-carousel'),
                                $slider_wap = $('.woocommerce-product-gallery');
                            if (!$mainOwl.hasClass('owl-carousel')) return;
                            $variation_form.addClass('variation-swatch-selected');
                            if (!isQuickShop($variation_form)) {
                                scrollToTop();
                            }
                            if (!$mainOwl.hasClass('owl-carousel')) return;
                            $mainOwl.trigger('destroy.owl.carousel');
                            if ($slider_wap.hasClass('image_slider_center')) {
                                $mainOwl = $mainOwl.owlCarousel({
                                    center: true,
                                    loop: true,
                                    nav: true,
                                    navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                                    responsive: {
                                        979: {
                                            items: 3
                                        },
                                        768: {
                                            items: 3
                                        },
                                        479: {
                                            items: 1,
                                            center: false
                                        },
                                        0: {
                                            items: 1,
                                            center: false
                                        }
                                    },
                                })
                            } else {
                                $mainOwl = $mainOwl.owlCarousel({
                                    loop: false,
                                    margin: 10,
                                    nav: true,
                                    navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                                    items: 1
                                })
                            }
                            $mainOwl.trigger('refresh.owl.carousel');
                            var $thumbs = $('.images .thumbnails');
                            $mainOwl.trigger('to.owl.carousel', 0);
                            if ($thumbs.hasClass('owl-carousel')) {
                                $thumbs.owlCarousel().trigger('to.owl.carousel', 0);
                                $thumbs.find('.active-thumb').removeClass('active-thumb');
                                $thumbs.find('.product-image-thumbnail').eq(0).addClass('active-thumb');
                            } else if ($thumbs.hasClass('slick-slider')) {
                                $thumbs.slick('slickGoTo', 0);
                                if (!$thumbs.find('.product-image-thumbnail').eq(0).hasClass('active-thumb')) {
                                    $thumbs.find('.active-thumb').removeClass('active-thumb');
                                    $thumbs.find('.product-image-thumbnail').eq(0).addClass('active-thumb');
                                }
                            }
                        });
                })
                var resetSwatches = function($variation_form) {
                    // If using AJAX
                    if (!$variation_form.data('product_variations')) return;
                    $variation_form.find('.variations select').each(function() {
                        var select = $(this);
                        var swatch = select.parent().find('.swatches-select');
                        var options = select.html();
                        options = $(options);
                        swatch.find('> div').removeClass('swatch-enabled').addClass('swatch-disabled');
                        options.each(function(el) {
                            var value = $(this).val();
                            if ($(this).hasClass('enabled')) {
                                swatch.find('div[data-value="' + value + '"]').removeClass('swatch-disabled').addClass('swatch-enabled');
                            } else {
                                swatch.find('div[data-value="' + value + '"]').addClass('swatch-disabled').removeClass('swatch-enabled');
                            }
                        });
                    });
                };
                var scrollToTop = function() {
                    if (!$('body').hasClass('idealautoduct-design-sticky') || !$('.entry-summary').hasClass('block-sticked') || $(window).width() <= 1024) return;
                    $('html, body').animate({
                        scrollTop: $('.product-image-summary').offset().top - 150
                    }, 800);
                }
                var isQuickShop = function($form) {
                    return $form.parent().hasClass('quick-shop-form');
                };
                var isQuickView = function() {
                    return $('.single-product-content').hasClass('product-quick-view');
                };
                var isVariationGallery = function(key) {
                    var variation_gallery_data = isQuickView() ? '' : jws_variation_gallery_data;
                    return typeof variation_gallery_data !== 'undefined' && variation_gallery_data && variation_gallery_data[key];
                };
                var replaceMainGallery = function(key, $variationForm) {
                    var variation_gallery_data = isQuickView() ? '' : jws_variation_gallery_data;
                    if (!isVariationGallery(key) || isQuickShop($variationForm) || ('default' === key && !variationGalleryReplace)) {
                        return false;
                    }
                    var imagesData = variation_gallery_data[key];
                    if (isQuickView()) {
                        var $mainGallery = $variationForm.parents('.single-product-content').find('.woocommerce-product-gallery__wrapper');
                    } else {
                        var $mainGallery = $variationForm.parents('body').find('.woocommerce-product-gallery__wrapper');
                    }
                    $mainGallery.empty();
                    for (var index = 0; index < imagesData.length; index++) {
                        var $html = '<div class="product-image-wrap"><figure data-thumb="' + imagesData[index].data_thumb + '" class="woocommerce-product-gallery__image">';
                        if (!isQuickView()) {
                            $html += '<a href="' + imagesData[index].href + '">';
                        }
                        $html += imagesData[index].image;
                        if (!isQuickView()) {
                            $html += '</a>';
                        }
                        $html += '</figure></div>';
                        $mainGallery.append($html);
                    }
                    jwsThemeWooModule.productImagesGallery();
                    jwsThemeWooModule.quickViewCarousel();
                    $('.woocommerce-product-gallery__image').trigger('zoom.destroy');
                    if (!isQuickView()) {
                        jwsThemeWooModule.initZoom();
                    }
                    if ('default' === key) {
                        variationGalleryReplace = false;
                    } else {
                        variationGalleryReplace = true;
                    }
                    return true;
                }
            },
            productImagesGallery: function() {
                var $thumbs = $('.images .thumbnails'), // magnific photo-swipe
                    $mainOwl = $('.woocommerce-product-gallery__wrapper:not(.quick-view-gallery)'),
                    $slider_wap = $('.woocommerce-product-gallery'),
                    $mainGallery = $('.woocommerce-product-gallery__wrapper:not(.quick-view-gallery)');
                if ($slider_wap.hasClass('image_image_vertical') && $(window).width() < 767 ) { 
                    initMainGallery();
                }    
                if (!$slider_wap.hasClass('image_image_vertical')) {
                    initMainGallery();
                    initThumbnailsMarkup();
                    $(window).load(function() {
                  
                       
                        if (($slider_wap.hasClass('thumbnail_position_left') || $slider_wap.hasClass('thumbnail_position_right')) && jQuery(window).width() > 1024) {
                            initThumbnailsVertical();
                        } else {
                            initThumbnailsHorizontal();
                        }
                    });
                }
                
                
                function initMainGallery() {
                    $mainGallery.trigger('destroy.owl.carousel');
                    if ($slider_wap.hasClass('image_slider_center')) {
                        $mainGallery.addClass('owl-carousel').owlCarousel({
                            center: true,
                            loop: true,
                            nav: true,
                            navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                            responsive: {
                                979: {
                                    items: 3
                                },
                                768: {
                                    items: 3
                                },
                                479: {
                                    items: 1,
                                    center: false
                                },
                                0: {
                                    items: 1,
                                    center: false
                                }
                            },
                        })
                    } else {
                        $mainGallery.addClass('owl-carousel').owlCarousel({
                            loop: false,
                            margin: 10,
                            nav: true,
                            navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                            items: 1
                        })
                    }
                };

                function initThumbnailsMarkup() {
                    var markup = '';
                    $mainGallery.find('.woocommerce-product-gallery__image').each(function() {
                        var image = $(this).data('thumb'),
                            alt = $(this).find('a > img').attr('alt'),
                            title = $(this).find('a > img').attr('title');
                        markup += '<div class="product-image-thumbnail"><img alt="' + alt + '" title="' + title + '" src="' + image + '" /></div>';
                    });
                    if ($thumbs.hasClass('slick-slider')) {
                        $thumbs.slick('unslick');
                    } else if ($thumbs.hasClass('owl-carousel')) {
                        $thumbs.trigger('destroy.owl.carousel');
                    }
                    $thumbs.empty();
                    $thumbs.append(markup);
                };

                function initThumbnailsHorizontal() {
                    $thumbs.addClass('owl-carousel').owlCarousel({
                        rtl: $('body').hasClass('rtl'),
                        items: 4,
                        responsive: {
                            979: {
                                items: 4
                            },
                            768: {
                                items: 4
                            },
                            479: {
                                items: 4
                            },
                            0: {
                                items: 4
                            }
                        },
                        dots: false,
                        nav: true,
                        navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                    });
                    var $thumbsOwl = $thumbs.owlCarousel();
                    $thumbs.on('click', '.owl-item', function(e) {
                        var i = $(this).index();
                        $thumbsOwl.trigger('to.owl.carousel', i);
                        $mainOwl.trigger('to.owl.carousel', i);
                    });
                    $mainOwl.on('changed.owl.carousel', function(e) {
                        var i = e.item.index;
                        $thumbsOwl.trigger('to.owl.carousel', i);
                        $thumbs.find('.active-thumb').removeClass('active-thumb');
                        $thumbs.find('.owl-item').eq(i).addClass('active-thumb');
                    });
                    $thumbs.find('.owl-item').eq(0).addClass('active-thumb');
                };

                function initThumbnailsVertical() {
                   
                        $thumbs.slick({
                            slidesToShow: 4,
                            slidesToScroll: 1,
                            vertical: true,
                            verticalSwiping: true,
                            infinite: false,
                            focusOnSelect:true,
                            swipeToSlide: true,
                        });
                    
                    $thumbs.on('click', '.product-image-thumbnail', function(e) {
                        var i = $(this).index();
                        $mainOwl.trigger('to.owl.carousel', i);
                    });
                    $mainOwl.on('changed.owl.carousel', function(e) {
                        var i = e.item.index;
                        $thumbs.slick('slickGoTo', i);
                        $thumbs.find('.active-thumb').removeClass('active-thumb');
                        $thumbs.find('.product-image-thumbnail').eq(i).addClass('active-thumb');
                    });
                    $thumbs.find('.product-image-thumbnail').eq(0).addClass('active-thumb');
                };
            },
            initZoom: function() {
                if ($('.woocommerce-product-gallery').hasClass('image-action-popup')) {
                    return false;
                }
                var $mainGallery = $('.woocommerce-product-gallery__wrapper:not(.quick-view-gallery)');
                $mainGallery.find('.product-image-wrap').each(function() {
                    var $wrapper = $(this).find('.woocommerce-product-gallery__image');
                    var image = $wrapper.find('img');
                    var zoomOptions = {
                        touch: false
                    };
                    if ('ontouchstart' in window) {
                        zoomOptions.on = 'click';
                    }
                    // But only zoom if the img is larger than its container.
                    if (image.data('large_image_width') > $(this).width()) {
                        $wrapper.trigger('zoom.destroy');
                        $wrapper.zoom(zoomOptions);
                    }
                });
            },
            /**
             *-------------------------------------------------------------------------------------------------------------------------------------------
             * Product thumbnail images & photo swipe gallery
             *-------------------------------------------------------------------------------------------------------------------------------------------
             */
            productImages: function() {
                // Init photoswipe
                var currentImage,
                    $productGallery = $('.woocommerce-product-gallery'),
                    $mainImages = $('.woocommerce-product-gallery__wrapper'),
                    $thumbs = $productGallery.find('.thumbnails'),
                    currentClass = 'current-image',
                    PhotoSwipeTrigger = '.jws-show-product-gallery';
                    
                    
                $thumbs.addClass('thumbnails-ready');
                
                
                if ($productGallery.hasClass('image-action-popup')) {
                    PhotoSwipeTrigger += ', .woocommerce-product-gallery__image a';
                }
                $productGallery.on('click', '.woocommerce-product-gallery__image a', function(e) {
                    e.preventDefault();
                });
                $productGallery.on('click', PhotoSwipeTrigger, function(e) {
                    e.preventDefault();
                    currentImage = $(this).attr('href');
                    // build items array
                    var items = getProductItems();
                    jwsThemeWooModule.callPhotoSwipe(getCurrentGalleryIndex(e), items);
                });
                var getCurrentGalleryIndex = function(e) {
                    if ($mainImages.hasClass('owl-carousel') && !$productGallery.hasClass('image_slider_center'))
                        return $mainImages.find('.owl-item.active').index(); 
                    else if ($productGallery.hasClass('image_slider_center')) return $(e.currentTarget).parent().parent().parent().index();
                    else return $(e.currentTarget).parent().parent().index();
                };
                var getProductItems = function() {
                    var items = [];
                    $mainImages.find('figure a img').each(function() {
                        var src = $(this).attr('data-large_image'),
                            width = $(this).attr('data-large_image_width'),
                            height = $(this).attr('data-large_image_height'),
                            caption = $(this).data('caption');
                        items.push({
                            src: src,
                            w: width,
                            h: height,
                        });
                    });
                    return items;
                };
                /* Fix zoom for first item firstly */
                if ($productGallery.hasClass('image-action-zoom')) {
                    var zoom_target = $('.woocommerce-product-gallery__image');
                    var image_to_zoom = zoom_target.find('img');
                    // But only zoom if the img is larger than its container.
                    if (image_to_zoom.attr('width') > $('.woocommerce-product-gallery').width()) {
                        zoom_target.trigger('zoom.destroy');
                        zoom_target.zoom({
                            touch: false
                        });
                    }
                }
            },
            callPhotoSwipe: function(index, items) {
                var pswpElement = document.querySelectorAll('.pswp')[0];
                if ($('body').hasClass('rtl')) {
                    index = items.length - index - 1;
                    items = items.reverse();
                }
                // define options (if needed)
                var options = {
                    // optionName: 'option value'
                    // for example:
                    index: index, // start at first slide
                    shareButtons: [{
                        id: 'facebook',
                        label: 'Share on Facebook',
                        url: 'https://www.facebook.com/sharer/sharer.php?u={{url}}'
                    }, {
                        id: 'twitter',
                        label: 'Tweet',
                        url: 'https://twitter.com/intent/tweet?text={{text}}&url={{url}}'
                    }, {
                        id: 'pinterest',
                        label: 'Pin it',
                        url: 'http://www.pinterest.com/pin/create/button/?url={{url}}&media={{image_url}}&description={{text}}'
                    }, {
                        id: 'download',
                        label: 'Download image',
                        url: '{{raw_image_url}}',
                        download: true
                    }],

                };
                // Initializes and opens PhotoSwipe
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
                gallery.init();
            },
               /**
               *-------------------------------------------------------------------------------------------------------------------------------------------
               * Tabs
               *-------------------------------------------------------------------------------------------------------------------------------------------
               */
              
               woo_tabs : function() {
             
                   $('.woocommerce-tabs').eq(0).each(function() {
                                 var $this = $(this);
            
                                /** Line magic tabs filter **/
                                var leftPos, newWidth, $magicLine;
                                if ($this.find('.wc-tabs').length) {
                                    $this.find('.wc-tabs').append("<li id='magic_line'></li>");
                                    $magicLine = $this.find('#magic_line');
                                    $magicLine
                                    .width($this.find('.active').width())
                                    .css('left', $this.find('.active a').position().left)
                                    .data('origLeft', $magicLine.position().left)
                                    .data('origWidth', $magicLine.width())
                                    $this.find('.wc-tabs li a').on("click", function() {  
                                        var $this = $(this);
                                        $(document).trigger('resize');
                                        $magicLine
                                            .data('origLeft', $this.position().left)
                                            .data('origWidth', $this.parent().width())
                                   
                                    });
            
                                    /*Magicline hover animation*/
                                    $this.find('.wc-tabs li').find('a').click(function () {
                                         $magicLine.css({
                                            "left": $magicLine.data('origLeft'),
                                            "width": $magicLine.data('origWidth'),
                                        });
                                    });
                                }
                    });
                },
             quickViewInit: function() {
             // Open popup with product info when click on Quick View button
             $(document).on('click', '.quickview-button', function(e) {
                    e.preventDefault();
                    var productId = $(this).data('product_id'),
                        loopName = $(this).data('loop-name'),
                        closeText = 'close_view',
                        loadingText = 'loading_view',
                        loop = $(this).data('loop'),
                        prev = '',
                        next = '',
                        loopBtns = $('.quick-view').find('[data-loop-name="' + loopName + '"]'),
                        btn = $(this);
                    btn.addClass('loading');
                    if(typeof addthis == 'undefined') { 
                         var s = document.createElement("script");
                        s.src = "//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-562f7aa6d38d8980";
                        document.getElementsByTagName("body")[0].appendChild(s); 
                    }
                   
                    if (typeof loopBtns[loop - 1] != 'undefined') {
                        prev = loopBtns.eq(loop - 1).addClass('quick-view-prev');
                        prev = $('<div>').append(prev.clone()).html();
                    }
                    if (typeof loopBtns[loop + 1] != 'undefined') {
                        next = loopBtns.eq(loop + 1).addClass('quick-view-next');
                        next = $('<div>').append(next.clone()).html();
                    }
                    jwsThemeWooModule.quickViewLoad(productId, btn, prev, next, closeText, loadingText);
                });
            },
            quickViewLoad: function(id, btn, prev, next, closeText, loadingText) {
                var data = {
                    id: id,
                    action: "jws_ajax_load_product_quickview",  
                };
                $.ajax({
                    url: jws_script.ajax_url,
                    data: data,
                    method: 'get',
                    success: function(data) {
                        // Open directly via API
                        $.magnificPopup.open({
                            items: {
                                src: '<div id="jws-quickview" class="mfp-with-anim popup-quick-view">' + data + '</div>', // can be a HTML string, jQuery object, or CSS selector
                                type: 'inline'
                            },
                            tClose: closeText,
                            tLoading: loadingText,
                            removalDelay: 500, //delay removal by X to allow out-animation
                            callbacks: {
                                beforeOpen: function() {
                                    this.st.mainClass = 'quick-view-main';
                                },
                                open: function() {
                                    $('.popup-quick-view').find('.variations_form').each(function() {
                                        $(this).wc_variation_form().find('.variations select:eq(0)').change();
                                        if (typeof $.fn.tawcvs_variation_swatches_form !== 'undefined') {
                                            $(this).tawcvs_variation_swatches_form();
                                        }
                                    });
                                    $('.variations_form').trigger('wc_variation_form');
                                    $('body').trigger('jws-quick-view-displayed');
                                    jwsThemeWooModule.quickViewCarousel();
                                    jwsThemeWooModule.swatchesVariations();
                                    jwsThemeWooModule.share_button(); 
                                    $('.jws-summary-wrap').find('> *').addClass('strike');
                                    
                                    $('form.cart select').select2({  dropdownAutoWidth : true });
                                    
                                    
                                      
                                }
                            },
                        });
                    },
                    complete: function() {
                        btn.removeClass('loading');
                        
                        $(".jws-summary-wrap > .strike").delay(400).each(function(i) {
                            $(this).delay(100 * i).queue(function() {
                              $(this).addClass("show");
                              $(this).dequeue();
                            })
                        });

                        addthis.toolbox('.addthis_inline_share_toolbox', {} , {'media':$('.quick-view-gallery img').attr('src'),'title':$('.addthis_inline_share_toolbox').data('title'),'url': $('.addthis_inline_share_toolbox').data('url')});
                    },
                    error: function() {},
                });
            },
            quickViewCarousel: function() {
                $('#jws-quickview .woocommerce-product-gallery__wrapper').trigger('destroy.owl.carousel');
                $('#jws-quickview .woocommerce-product-gallery__wrapper').addClass('owl-carousel').owlCarousel({
                      loop: false,
                      margin: 10,
                      nav: true,
                      navText: ["<span class='nav-left'></span>", "<span class='nav-right'></span>"],
                      items: 1
                });
            },
            
            share_button: function() {
                var $container = $('.popup-list'),
                    $item = $container.find('.item');
                $().gallery_popup($container,$item);  
                $('.product-share button').on('click', function(){
                       var parents = $(this).parents('.product-share'); 
                       parents.find(".addthis_inline_share_toolbox").toggleClass('opened'); 
                       if(parents.find(".addthis_inline_share_toolbox").hasClass('opened')) {
                            parents.find(".addthis_inline_share_toolbox a").delay(100).each(function(i) {
                            $(this).delay(50 * i).queue(function() {
                              $(this).addClass("show");
                              $(this).dequeue();
                            })
                          });
                       }else {
                            parents.find(".addthis_inline_share_toolbox a").removeClass('show');
                       }
               }); 
            } ,
            
            
        priceSlider: function() {
		// woocommerce_price_slider_params is required to continue, ensure the object exists
		if (typeof woocommerce_price_slider_params === 'undefined') {
			return false;
		}

		if ($('.siderbar-inner').find('.widget_price_filter').length <= 0) {
			return false;
		}

		// Get markup ready for slider
		$('input#min_price, input#max_price').hide();
		$('.price_slider, .price_label').show();

		// Price slider uses jquery ui
		var min_price = $('.price_slider_amount #min_price').data('min'),
			max_price = $('.price_slider_amount #max_price').data('max'),
			current_min_price = parseInt(min_price, 10),
			current_max_price = parseInt(max_price, 10);

		if ($('.price_slider_amount #min_price').val() != '') {
			current_min_price = parseInt($('.price_slider_amount #min_price').val(), 10);
		}
		if ($('.price_slider_amount #max_price').val() != '') {
			current_max_price = parseInt($('.price_slider_amount #max_price').val(), 10);
		}

		$(document.body).bind('price_slider_create price_slider_slide', function (event, min, max) {
			if (woocommerce_price_slider_params.currency_pos === 'left') {

				$('.price_slider_amount span.from').html(woocommerce_price_slider_params.currency_symbol + min);
				$('.price_slider_amount span.to').html(woocommerce_price_slider_params.currency_symbol + max);

			} else if (woocommerce_price_slider_params.currency_pos === 'left_space') {

				$('.price_slider_amount span.from').html(woocommerce_price_slider_params.currency_symbol + ' ' + min);
				$('.price_slider_amount span.to').html(woocommerce_price_slider_params.currency_symbol + ' ' + max);

			} else if (woocommerce_price_slider_params.currency_pos === 'right') {

				$('.price_slider_amount span.from').html(min + woocommerce_price_slider_params.currency_symbol);
				$('.price_slider_amount span.to').html(max + woocommerce_price_slider_params.currency_symbol);

			} else if (woocommerce_price_slider_params.currency_pos === 'right_space') {

				$('.price_slider_amount span.from').html(min + ' ' + woocommerce_price_slider_params.currency_symbol);
				$('.price_slider_amount span.to').html(max + ' ' + woocommerce_price_slider_params.currency_symbol);

			}

			$(document.body).trigger('price_slider_updated', [min, max]);
		});
		if (typeof $.fn.slider !== 'undefined') {
			$('.price_slider').slider({
				range  : true,
				animate: true,
				min    : min_price,
				max    : max_price,
				values : [current_min_price, current_max_price],
				create : function () {

					$('.price_slider_amount #min_price').val(current_min_price);
					$('.price_slider_amount #max_price').val(current_max_price);

					$(document.body).trigger('price_slider_create', [current_min_price, current_max_price]);
				},
				slide  : function (event, ui) {

					$('input#min_price').val(ui.values[0]);
					$('input#max_price').val(ui.values[1]);

					$(document.body).trigger('price_slider_slide', [ui.values[0], ui.values[1]]);
				},
				change : function (event, ui) {

					$(document.body).trigger('price_slider_change', [ui.values[0], ui.values[1]]);
				}
			});
		}
	},        
            
            	// Filter Ajax
	filterAjax :function() {
         
         $(document).on('click','.sort-product-checkbox',function(){ 

            if($(this).data('name') == 'rating') {
                
                $(this).parents('.checkbox').find('.sort-product-checkbox').removeClass('active');
                $(this).addClass('active');
     
            }else{
                if ($(this).hasClass('active')) {
                    $(this).removeClass('active');
                } else {
                    $(this).addClass('active');
                }
            }

            var slug = $( this ).data('name');  
            var checked = []
            $("[data-name='"+slug+"'].active").each(function ()
            {
                checked.push($(this).data('value'));
            });
            $(this).parents('.checkbox').find('.file_checkbox_value').val(checked);
         
            
            var $form = $(this).parents('.checkbox').find('form'),
			url = $form.attr('action') + '?' + $form.serialize();

			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
                      
         });  
         
         $(document.body).on('change', '.widget-filter-checkbox select', function (e) {
         
            var url = $(this).val();
            $(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));

		});

        $(document.body).on('submit', '.woocommerce-ordering ', function (e) {
            e.preventDefault(); 
        });
        
        $(document.body).on('submit', '.jws-adsearch-filter.yes form', function (e) {
            e.preventDefault(); 
            
            var form_data =  $(this).serialize();
            form_data = form_data.replace(/[^&]+=\.?(?:&|$)/g,'');
            form_data = form_data.replace(/&$/,'');
            var url = $(this).attr('action') + '?' + form_data;

			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
        });
                     
        $(document.body).on('submit', '.shop-sidebar-top .form-filter-product-cars form', function (e) {
            e.preventDefault();

			var url = $(this).attr('action') + '?' + $(this).serialize();

			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
   
		});
        
        
        $(document.body).on('change', '#pgs_product_pp , .orderby', function (e) {

			var url = $(this).parents('form').attr('action') + '?' + $(this).parents('form').serialize();

			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
   
		});


		$(document.body).on('price_slider_change', function (event, ui) {
			var form = $('.price_slider,#slider-rent-range').closest('form').get(0),
				$form = $(form),
				url = $form.attr('action') + '?' + $form.serialize();

			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
		});

        
        $(document.body).on('submit', '.woocommerce-widget-layered-nav-dropdown', function (e) {
            e.preventDefault();

			var url = $(this).attr('action') + '?' + $(this).serialize();


			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
   
		});
        
        
        $(document.body).on('click', '.change-view-button a', function (e) {
			e.preventDefault();
            $('.change-view-button a').removeClass('sel-active')
            $(this).addClass('sel-active');
			var url = $(this).attr('href');
			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
		});
        

		$(document.body).on('click', ' #remove-filter-actived', function (e) {
			e.preventDefault();
			var url = $(this).attr('href');
			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
		});
        
        $(document.body).on('click', '.jws-pagination-number .page-numbers a', function (e) {
			e.preventDefault();
      
			var url = $(this).attr('href');
			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
		});
        
        $(document.body).on('click', ' .wc-col-filter a', function (e) {
			e.preventDefault();
            $(this).addClass('active');
            
			var url = $(this).attr('href');
			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
		});

		$(document.body).find('#jws-shop-product-cats').on('click', '.cat-link', function (e) {
			e.preventDefault();
			var url = $(this).attr('href');
			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
		});

		$(document.body).find('#jws-shop-toolbar').find('.woocommerce-ordering').on('click', 'a', function (e) {
			e.preventDefault();
			$(this).addClass('active');
			var url = $(this).attr('href');
			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
		});

		$(document.body).find('#jws-categories-filter').on('click', 'a', function (e) {
			e.preventDefault();
			$(this).addClass('selected');
			var url = $(this).attr('href');
			$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
            
		});


		$(document.body).find('#jws-shop-topbar, .siderbar-inner').on('click', 'a', function (e) {
			var $widget = $(this).closest('.widget');
    
			if ($widget.hasClass('widget_product_tag_cloud') ||
				$widget.hasClass('widget_product_categories') ||
				$widget.hasClass('widget_layered_nav_filters') ||
				$widget.hasClass('widget_layered_nav') ||
				$widget.hasClass('product-sort-by') ||
                $widget.hasClass('product_reset') ||
				$widget.hasClass('woocommerce-widget-layered-nav')) {
				e.preventDefault();
				$(this).closest('li').addClass('chosen');
				var url = $(this).attr('href');
				$(document.body).trigger('idealauto_catelog_filter_ajax', url, $(this));
			}

			if ($widget.hasClass('widget_product_tag_cloud')) {
				$(this).addClass('selected');
			}

			if ($widget.hasClass('product-sort-by')) {
				$(this).addClass('active');
			}
		});

		$(document.body).on('idealauto_catelog_filter_ajax', function (e, url, element) {
            
            $('html,body').animate({
    			scrollTop: $(".shop-container").offset().top
    		}, 600);
                
            $('.product-container').addClass('idealauto-animated-products');
            
			$('.products').addClass('loading');

            
			if ('?' == url.slice(-1)) {
				url = url.slice(0, -1);
			}

			url = url.replace(/%2C/g, ',');

			history.pushState(null, null, url);

			$(document.body).trigger('idealauto_ajax_filter_before_send_request', [url, element]);

			

			 $.get(url, function (res) {

				$('.siderbar-inner').html($(res).find('.siderbar-inner').html());
                $('.content-area').html($(res).find('.content-area').html());
                $('.jws-title-bar-wrap').html($(res).find('.jws-title-bar-wrap').html());
                $('.jws-title-bar-wrap').html($(res).find('.jws-title-bar-wrap').html());

                jwsThemeWooModule.jws_rent_price(); 
                jwsThemeWooModule.priceSlider();
                jwsThemeWooModule.shop_sidebar();
                jQuery('select').select2({  dropdownAutoWidth : true });
				$(document.body).trigger('idealauto_ajax_filter_request_success', [res, url]);
              
			}, 'html');


		});

		$(document.body).on('idealauto_ajax_filter_before_send_request', function () {
			if ($('#jws-shop-toolbar').hasClass('on-mobile') || $('#jws-shop-topbar').hasClass('on-mobile')) {
				$('#jws-toggle-cats-filter').removeClass('active');
				$('.jws-filter').removeClass('active');
			}
		});

	   }
  
            
        } // End Class
    }())
})(jQuery);
jQuery(document).ready(function() {
    jQuery(document.body).on('click' , '.toggle-this' , function () {
      jQuery('.single-form-popp').toggleClass('active'); 
    });
    if(jQuery('.checkout_coupon .input-text').val() != '') {
       jQuery('.checkout_coupon button').click(); 
    }
    jQuery(document.body).on('submit', '.jws-adsearch-filter.no form', function (e) {
        e.preventDefault(); 
        var form_data =  jQuery(this).serialize();
        form_data = form_data.replace(/[^&]+=\.?(?:&|$)/g,'');
        form_data = form_data.replace(/&$/,'');
        var url = jQuery(this).attr('action') + '?' + form_data;
        console.log();
        window.location.href = url;
    });
    
    jwsThemeWooModule.init();
});