/*global rad_data */
var rad = rad || {};

(function( $ ) {
    'use strict';

    /**************************************************
     * The main function to init the theme
     **************************************************/
    rad.init = function() {
        this.data = rad_data || {};

        //add hierarchical calling of methods to be more clean!
        
        this.setup();
        this.lazy_on_load('#rad-wrapper, .toggle-aside');
        this.embed_video();
        this.carousel_gallery();
        this.cat_widget();
        this.blocks();
        this.card_blog();
        this.card_blog_load_more();
        this.scatter_parallax_init();
        this.scroll_parallax_init();
        this.mouse_parallax_init();
        this.slideshow_block();
        this.reveal_slideshow_block();
        this.video_bg();
        this.video_bg_size();
        this.fit_videos();
        this.comment_respond();
        this.mega_menu();
        this.carousel();
        this.element_animation();
        this.cookies_notice();
        this.popup();
        this.modals();
        this.size_chart();

        //woocomerce
        this.product_single_lightbox();
        this.products_layout();
        this.sticky_products_layout();
        this.products_pagination();
        this.product_thumbnails();
        this.add_to_cart_events();
        this.woocommerce_filter();
        this.woocommerce_column_switcher();
        this.shop_grid_animation();
        this.woocommerce_cats();
        this.product_tabs();
        this.product_variation();
        this.product_quickview();
        this.product_hover();
        this.product_quantity();
        this.wishlist_widget_update();
        this.wishlist_actions();
        this.card_widget_update();
        this.woocommerce_ajax_wrapper();
        this.init_niceselect();
        this.woocommerce_variation_attributes();
        this.show_more_tag();
        this.wc_header_categories();
        this.wc_top_categories();
        this.update_widget_cart_on_cart_page();
        this.add_to_cart();
        this.responsive_product_social_share();
        this.wc_notice_close();

        this.built_in_slider();
        this.toggle_aside();
        this.toggle_aside_scrollbar();
        this.custom_cursor();
        this.social_share_pop_up();
        this.go_up();
        this.menu_states();
        this.mobile_menu_states();
        this.preloader_hide();
        this.detect_scroll_bar_width();
        this.lazy_load_on_hover();
        this.custom_heading_block();
        this.ajax_search_form();
        this.responsive_menu();
        this.ios_double_tap();
        this.toggle_widgets_childs();
        this.bind();
        this.frontend_editor();
        this.vc_frontend_editor();

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

    /**************************************************
     *  Update document height, window height & width
     **************************************************/
    rad.setup = function () {

        rad.$window = $(window);
        rad.$scroll = null;
        rad.w_width = rad.$window.width();
        rad.w_height = rad.$window.height();
        rad.msie = window.navigator.userAgent.indexOf("self.msie ");
        rad.msie11 = navigator.userAgent.match(/Trident.*rv\:11\./);
        rad.is_touch_device = (Modernizr.touchevents) ? true : false;
        rad.is_mobile = (rad.w_width <= 767) ? true : false;
        rad.is_tablet = (rad.w_width >=768 && rad.w_width <= 1140) ? true : false;
        rad.is_mobile_or_tablet = (rad.w_width <= 1140) ? true : false;
        rad.is_mobile_or_vertical_tablet = (rad.w_width <= 979) ? true : false;
        rad.active_wc = ($('body').hasClass('woocommerce')) ? true : false;
        rad.shop_height = $('.wc-ajax-wrapper').height();
    }

    /**************************************************
     *  Overlayscrollbars
     **************************************************/
    rad.stop_scroll = function () {
        $('body').addClass('disable-scroll');
    }

    rad.start_scroll = function () {
        $('body').removeClass('disable-scroll');
    }

    /**************************************************
     *  Update document height, window height & width
     **************************************************/
    rad.bind = function () {

        //bind resize functions
        rad.$window.resize(function () {

            rad.re_setup_sizes();
            rad.products_layout();
            rad.update_doc_height();
            rad.shop_grid_animation();
            rad.video_bg_size();
            rad.card_blog();
            rad.mobile_menu_states();

            //Use settimeout to run function only when resizing is finished
            if ($('.carousel').length > 0) {
                rad.updateCarousel();
            }

        });
    };

    /************************************************
     * bakery page builder
     **************************************************/
    rad.vc_frontend_editor = function () {
        //bind resize functions
        $('body').bind('frontend_editor_update',function() {
            rad.lazy_on_load('#rad-wrapper');
            rad.embed_video();
            rad.carousel_gallery();
            rad.cat_widget();
            rad.blocks();
            rad.card_blog();
            rad.card_blog_load_more();
            rad.scatter_parallax_init();
            rad.scroll_parallax_init();
            rad.mouse_parallax_init();
            rad.slideshow_block();
            rad.reveal_slideshow_block();
            rad.video_bg();
            rad.video_bg_size();
            rad.fit_videos();
            rad.carousel();
            rad.element_animation();
            rad.size_chart();

            //woocomerce
            rad.products_layout();
            rad.sticky_products_layout();
            rad.products_pagination();
            rad.product_thumbnails();
            rad.shop_grid_animation();
            rad.woocommerce_cats();
            rad.product_tabs();
            rad.init_niceselect();
            rad.lazy_load_on_hover();
            rad.custom_heading_block();
        });
    }

    /**************************************************
     *  Run functions in live editor of page builders
     **************************************************/
    rad.frontend_editor = function () {
        //Call functions on WP Bakery front-end editor update
        $('body').bind('frontend_editor_update', rad.live_editor_functions);

        //Call functions on Elementor front-end editor update
        if ( window.elementorFrontend ) {
            try {
                window.elementorFrontend.hooks.addAction( 
                    "frontend/element_ready/widget", 
                    function( $scope ) {
                        rad.live_editor_functions();
                } );
            } catch (error) {
                console.log( error.message );
            }
        }

        if ( typeof elementor != "undefined" && typeof elementor.settings.page != "undefined") {

            var style_table = {
                'header_overlay' : 'inherit',
                'text_color' : 'inherit',
                'initial_shop_cart_text_color' : 'inherit',
                'shop_cart_text_color' : 'inherit',
                'initialMenuTextColor' : 'inherit',
                'menuTextColor' : 'inherit',
                'initialMenuBorderColor' : 'inherit',
                'menuBorderColor' : 'inherit',
                'initialMenuBorderColor' : 'inherit',
                'initialMenuBorderColor' : 'inherit',
            };

            var update_style = function(key, value) {
                if(value == '')
                {
                    style_table[key] = 'inherit';
                }
                else
                {
                    style_table[key] = value;
                }

                update_style_tag();
            }

            var update_style_tag = function() {
                var style_template = $('document').find('script#rad_elementor_editor_style_template').html();
                var style_tag = $('head').find('style#rad_elementor_live_editor_style');
                for (var key in style_table) {
                    if(style_table[key] != null)
                    {
                        style_template.replace("%" + key + "%",style_table[key]);
                    }
                }

                if(style_tag !== 'undefined')
                {
                    style_tag.html(style_template);
                }
                else
                {
                    var head = document.head || document.getElementsByTagName('head')[0];
                    style_tag = document.createElement('style');

                    head.appendChild(style_tag);

                    style_tag.type = 'text/css';
                    if (style_tag.styleSheet){
                      // This is required for IE8 and below.
                      style.styleSheet.cssText = style_template;
                    } else {
                      style_tag.appendChild(document.createTextNode(style_template));
                    }
                }
            }

            // Page Layout Options
            elementor.settings.page.addChangeCallback( 'shop-cart-text-color', function( newValue ) {
                update_style("",newValue);
            } );

            elementor.settings.page.addChangeCallback( 'page-header-bg', function( newValue ) {

            } );
        }
    };

    /**************************************************
     *  Functions that need to run in the live editor
     **************************************************/
    rad.live_editor_functions = function() {
        rad.lazy_on_load('#rad-wrapper');
        rad.embed_video();
        rad.carousel_gallery();
        rad.cat_widget();
        rad.blocks();
        rad.card_blog();
        rad.card_blog_load_more();
        rad.scatter_parallax_init();
        rad.scroll_parallax_init();
        rad.mouse_parallax_init();
        rad.slideshow_block();
        rad.reveal_slideshow_block();
        rad.video_bg();
        rad.video_bg_size();
        rad.fit_videos();
        rad.carousel();
        rad.element_animation();
        rad.size_chart();

        //woocomerce
        rad.products_layout();
        rad.sticky_products_layout();
        rad.products_pagination();
        rad.product_thumbnails();
        rad.shop_grid_animation();
        rad.woocommerce_cats();
        rad.product_tabs();
        rad.init_niceselect();
        rad.lazy_load_on_hover();
        rad.custom_heading_block();
    }

    /**************************************************
     *  Update device size detector
     **************************************************/
    rad.re_setup_sizes  = function () {
        rad.w_width = rad.$window.width();
        rad.is_mobile = (rad.w_width <= 767) ? true : false;
        rad.is_tablet = (rad.w_width >=768 && rad.w_width <= 1140) ? true : false;
        rad.is_mobile_or_tablet = (rad.w_width <= 1140) ? true : false;
        rad.is_mobile_or_vertical_tablet = (rad.w_width <= 979) ? true : false;
    };

    /**************************************************
     *  Update document height, window height & width
     **************************************************/
    rad.update_doc_height  = function () {
        rad.$window.trigger('document-height-changed');
    };

    /**************************************************
    /*  modal
    **************************************************/
    rad.modals = function ( ) {

        // Close quickview by click close button
        $(".aside-close,#modal-bg").on('click', function (e) {
            e.preventDefault();
            rad.modals_close();
        });

        // Close box with esc key
        $(document).keyup(function (e) {
            if (e.keyCode === 27)
                rad.modals_close();
        });
    }
    rad.modals_open = function ( type, classes ) {
        var $modal = $('#modalbox'),
            $modal_content = $modal.find('#modal-content');

        if ( $modal.length <= 0 )
                return;

        rad.stop_scroll();
        $modal.addClass(type).removeClass('closed').attr('data-type',type);
        $modal_content.addClass(classes);
        if (!$modal.hasClass('open')) {
            $modal.addClass('open');
        }

    }
    rad.modals_show = function ( data ) {
        var $modal = $('#modalbox'),
            $modal_content = $modal.find('#modal-content');

            if ( $modal.length <= 0 )
                return;

            $modal.removeClass('loading');
            $modal_content.html($(data));
            setTimeout(function () {
                $modal.addClass('shown'); // content is ready, so show it
            },100);
 
    };

    rad.modals_close = function () {
        var $modal = $('#modalbox'),
            $modal_content = $modal.find('#modal-content'),
            type = $modal.data('type');

        $modal.removeClass('shown loading').addClass('closed');

        setTimeout(function () {
            $modal.removeClass('open');
        }, 400);

        setTimeout(function () {
            rad.start_scroll();
        }, 300);

        setTimeout(function () {
            $modal_content.html('');
            $(document).trigger(type + '-modal-close');
        }, 1100);
    };

    /**************************************************
    /*  ReInit variation functionality by recalling woocommerce wc_variation_form function
    **************************************************/
    rad.re_init_wc_variation = function ($container) {
        var $form_variation = $container.find('.variations_form');

        if ($form_variation.length > 0) {
            $form_variation.wc_variation_form().find('.variations select:eq(0)').change();
            $form_variation.trigger('check_variations');
        }
    };

    /**************************************************
    /*  niceSelect For Restyle SELECT OPTION 
    **************************************************/
    rad.init_niceselect = function (action) {
        if ($('.woocommerce').length > 0) {
            setTimeout(function(){
                $('.woocommerce .composite_form .component .component_options_select').niceSelect(action);
            },500)
            $('.woocommerce-ordering select.orderby').niceSelect(action);
            $('form.cart .variations .attr-container').not('.image-attr, .size-attr, .color-attr').find('select').niceSelect(action);
        }

        $('.widget_archive select, .widget_categories select.postform, .widget_product_categories select.dropdown_product_cat,.widget_layered_nav select,.widget select,.wp-block-categories select, .wp-block-archives-dropdown select').niceSelect(action);

        $('.widget_product_categories select.dropdown_product_cat, select.dropdown_layered_nav').niceSelect(action);

    };

    /**************************************************
    /* woocommerce variation select
    **************************************************/
    rad.woocommerce_variation_img_attributes = function () {
        setTimeout(function () {

            $('form.cart .variations select').each(function (index, el) {

                var $select = $(this),
                    $attr_items = $select.siblings('.attr-item'),
                    attr_values = new Array();

                $select.find('option').each(function () {
                    if($(this).val() != '')
                    {
                        attr_values.push($(this).val());
                    }
                });

                $attr_items.removeClass('deactive');

                $attr_items.each(function () {
                    var $this = $(this),
                        data_val = $this.attr('data-value');

                    if(!attr_values.includes(data_val))
                    {
                        $this.addClass('deactive');
                    }
                })


                // Update nice select 
                $('form.cart .variations select').niceSelect('update');


            });
        }, 200)
    };

    rad.woocommerce_variation_attributes_trigger = function () {

        if ($('form.cart .variations select').length <= 0)
            return;

        $('body').trigger('update_variation_values');

    };

    rad.woocommerce_variation_attributes = function () {

        if ($('form.cart .variations select').length <= 0)
            return;


        $('body').unbind('update_variation_values', rad.woocommerce_variation_img_attributes);
        $('body').on('update_variation_values', rad.woocommerce_variation_img_attributes);

        var $attr_container = $('.woocommerce form.cart .variations .attr-container'),
            $attr_items = $attr_container.find('.attr-item');

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

            $(this).siblings('.attr-item').removeClass('selected');
            $(this).addClass('selected');

            var $term = $(this).data('value');

            //change select element to trigger events
            $attr_container.find('select').find('option[value="' + $term + '"]').prop('selected', true).trigger('change');
            
        });

        // On clicking the reset variation button
        $(document.body).on('click', '.reset_variations', function (event) {

            $attr_items.removeClass('selected deactive');

            $('.nice-select').each(function () {

                var $this = $(this);

                var $dropdownLi = $this.find('.list li');

                //reset DropDown 
                $dropdownLi.removeClass('selected');
                var $chooseAnoptionText = $this.find('.list li:first-child').text();

                var $currentText = $this.find('.current');
                $currentText.html($chooseAnoptionText);

            });
        })
    };

    /**************************************************
    /*  woocomerce -  product quantity input
    **************************************************/
    rad.product_quantity = function () {

        $(document).on("click", '.quantity .quantity-button', function () {
            var $button = $(this),
                $quantityInput = $button.siblings('input[type="number"]'),
                val = ($quantityInput.val() != '')? parseFloat($quantityInput.val()) : 0;

            if ($button.hasClass("plus")) {
                val++;
            }
            else {
                if (val > 0) {
                    val--;
                } else {
                    val = 0;
                }
            }

            $quantityInput.val(val).trigger('change');

        });

        $(document).on('change', '.woocommerce .quantity input[type="number"]', function () {
            $(this).parent('.quantity').siblings('.add_to_cart_button').attr('data-quantity', $(this).val());
        });
    };

    /**************************************************
    /*  product  detail - tabs
    **************************************************/
    //Modified version of Woocommerce/assets/js/frontend/single-product.js
    rad.product_tabs = function () {

        var self = this,
            ratingInitCount = 1, // Control to init rating Run Once time,
            tab_in_summary = ($('.summary .woocommerce-tabs').length > 0) ? true : false; // Control to init rating Run Once time 

        // wc_single_product_params is required to continue, ensure the object exists
        if (typeof wc_single_product_params === 'undefined') {
            return false;
        }

        // Tabs
        $('body').on('init', '.wc-tabs-wrapper, .woocommerce-tabs', function () {
            $('.wc-tab, .woocommerce-tabs .panel:not(.panel .panel)').hide();

            var hash = window.location.hash,
                url = window.location.href,
                $tabs = $(this).find('.wc-tabs, ul.tabs').first();

            if (hash.toLowerCase().indexOf('comment-') >= 0 || hash === '#reviews' || hash === '#tab-reviews') {
                $tabs.find('li.reviews_tab a').click();
            } else if (url.indexOf('comment-page-') > 0 || url.indexOf('cpage=') > 0) {
                $tabs.find('li.reviews_tab a').click();
            } else {
                $tabs.find('li:first a').click();
            }
        })
        //Rado codes (custom version of click event for tabs)
        .on('click', '.wc-tabs li a, ul.tabs li a', function () {
            var $this = $(this),
                $currentPanelID = $this.attr('href'),
                $currentPanel = $('.woocommerce-tabs').find($currentPanelID),
                $visiblePanel = $currentPanel.siblings('.panel').filter(':visible');

            if(tab_in_summary && $currentPanelID == '#tab-reviews')
            {
                rad.scroll_to('#main-tab-reviews');
                return;
            }

            $this.parent().siblings().removeClass('active').end().addClass('active');

            if ($visiblePanel.length <= 0) {
                $currentPanel.addClass('current').fadeIn(300, function () {
                    rad.update_doc_height();
                });
            }
            else {
                $visiblePanel.stop().fadeOut(300, function () {
                    $currentPanel.siblings('.panel').removeClass('current');
                    $currentPanel.addClass('current').stop().fadeIn(300, function () {
                        rad.update_doc_height();
                    });
                });
            }


            return false;
        })
        // Review link
        .on('click', 'a.woocommerce-review-link', function () {
            $('.reviews_tab a').click();
            return true;
        } )
        //Rado code  : modified version
        .on('init', '#rating', function () {
            if (ratingInitCount == 1) { // Control to init rating Run Once time 
                $('#rating').hide().before('<p class="stars review_rating"><span><a class="star-1" href="#">1</a><a class="star-2" href="#">2</a><a class="star-3" href="#">3</a><a class="star-4" href="#">4</a><a class="star-5" href="#">5</a></span></p>');
                ratingInitCount++;
            }
        } )
        .on( 'click', '#respond p.stars a', function() {
            var $star       = $( this ),
                $rating     = $( this ).closest( '#respond' ).find( '#rating' ),
                $container  = $( this ).closest( '.stars' );

            $rating.val( $star.text() );
            $star.siblings( 'a' ).removeClass( 'active' );
            $star.addClass( 'active' );
            $container.addClass( 'selected' );

            return false;
        } )
        .on('click', '#respond #submit', function () {
            var $rating = $(this).closest('#respond').find('#rating'),
                rating = $rating.val();

            if ($rating.length > 0 && !rating && wc_single_product_params.review_rating_required === 'yes') {
                window.alert(wc_single_product_params.i18n_required_rating_text);

                return false;
            }
        })

        //Rado code  : modified version
        if (ratingInitCount === 1) { // Control to init rating Run Once time 
            //Init Tabs and Star Ratings    
            $('.wc-tabs-wrapper, .woocommerce-tabs, #rating').trigger('init');
            ratingInitCount++;
        }

    };

    /**************************************************
    /*  Woocommerce categories
    **************************************************/
    rad.woocommerce_cats = function () {
        var $cats = $(".wc-categories.general-layout.cat-style-1:not(.swiper-wrapper), .wc-categories.general-layout.cat-style-2:not(.swiper-wrapper)");

        if ($cats.length <= 0)
            return;

        if (rad.is_mobile)
        {
            $cats.removeClass('masonry-g i2a i3a i3b i4a i4b i5a i5b i5c');
            return;
        }

        $cats.each(function(){
            var $cat = $(this),
                layout_mode = 'masonry',
                perfectMasonrySettings = {
                    layout: 'vertical'
                };

            if($cat.hasClass('masonry-g'))
            {
                layout_mode = 'perfectMasonry'
            }

            if($cat.hasClass('i4a') || $cat.hasClass('i5a'))
            {
                perfectMasonrySettings = {
                    layout: 'vertical',
                    columnWidth: $cat.find('.product-category').eq(3).outerWidth(),
                    rowHeight: $cat.find('.product-category').eq(3).outerHeight(),
                    cols:3
                }
            }

            $cat.isotope({
                itemSelector: '.product-category',
                layoutMode: layout_mode,
                perfectMasonry: perfectMasonrySettings,
            });

            $cat.waitForImages(function () {
                $cat.isotope('reLayout');
            });
        });

        var woocommerce_cats_resize_handler = function ()
        {
            setTimeout(function () {
                $cats.each(function(){
                    var $cat = $(this);

                    if($cat.hasClass('i4a') || $cat.hasClass('i5a'))
                    {
                        $cat.isotope({
                            itemSelector: '.product-category',
                            layoutMode: 'perfectMasonry',
                            perfectMasonry: {
                                layout: 'vertical',
                                columnWidth: $cat.find('.product-category').eq(3).outerWidth(),
                                rowHeight: $cat.find('.product-category').eq(3).outerHeight(),
                                cols:3
                            },
                        });
                    }
                    else
                    {
                        $cat.isotope('reLayout');
                    }
                    
                });
            }, 500);
        }
        rad.$window.on('resize', woocommerce_cats_resize_handler);
    };

    /**************************************************
    /*  product  Quick view
    **************************************************/
    rad.product_quickview = function () {
        $('.quick-view-button').on('click', function (e) {
            e.preventDefault();

            var $this = $(this),
                ajaxurl,
                data = { product_id: $this.data('product_id') },
                $modal_content = $('#modal-content');

            rad.modals_open('quickview-modal','woocommerce single-product');

            // Use new WooCommerce endpoint URL if available
            if (typeof wc_add_to_cart_params !== 'undefined') {
                ajaxurl = wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'load_quick_view'); // WooCommerce Ajax endpoint URL (available since 2.4)
            } else {
                ajaxurl = rad.data.ajax_url;
                data['action'] = 'load_quick_view';
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: data,
                dataType: 'html',
                cache: false,
                headers: { 'cache-control': 'no-cache' },
                success: function (data) {
                    rad.modals_show( data);
                    setTimeout(function () {
                        rad.product_thumbnails($modal_content); // enable gallery slider of product
                    }, 200);
                    rad.init_niceselect();
                    rad.woocommerce_variation_attributes(); // enable variation attributes
                    rad.woocommerce_variation_attributes_trigger(); // update image attributes
                    rad.re_init_wc_variation($modal_content); // Variation Form
                    rad.add_to_cart(); // add to cart - open side bar add to cart
                }
            });
        });
    }

    /**************************************************
    /*  product variation
    **************************************************/
    rad.product_variation = function () {
        if ($("form.variations_form").length <= 0)
            return;

        //Use passed parameter for getting variation images
        //variation.image_link : original image size
        //variation.image_src : smaller image ( shop_single size )
        $.fn.wc_variations_image_update = function (variation) {

            //check existnace of image for this variation
            if (variation && variation.image.url && variation.image.url.length > 1) {
                var url = variation.image.url.split('.').slice(0, -1).join('.');
                
                if ($('#product-fullview-thumbs .swiper-container').length > 0)
                {
                    //Find the index of variation slide and slide to it
                    var index = $("#product-fullview-thumbs").find('.swiper-slide[data-variableimageurl^="' + url + '"]').data('slide'),
                        $image_slider = $('#product-fullview-thumbs .swiper-container')[0].swiper;

                    if (index === undefined || typeof $image_slider === undefined)
                        return;

                    $image_slider.slideTo(index);
                    $('#product-thumbs').add($('#product-fullview-thumbs')).addClass('stop-by-variations');//Stop slider when select an varaition that has image
                    $image_slider.autoplay.stop();
                }
                else
                {
                    var $target = $(".images").find('.p-g-item[data-variableimageurl^="' + url + '"]');
                    rad.scroll_to($target,300,100);
                }
                
                

            }
        };
    };


    rad.card_widget_update = function () {

        $(document).on("click", ".mini_cart_item a.remove", function (e) {

            e.preventDefault();
            var $this = $(this);

            $this.closest('li').addClass('removing');
            $('.cart-aside-wrapper').addClass('updatingCart');
        });
    };

    /**************************************************
    /*  product  wishlist widget
    **************************************************/
    rad.wishlist_widget_update = function () {
        //Update it when a product added or removed to/from wishlist
        $('body').on('added_to_wishlist removed_from_wishlist', function () {
            $('.toggle-aside .yith-wcwl-form').removeClass('removing');


            var ajaxurl = '',
                send_data = {
                    'security': rad.data.nonce
                };

            // Use new WooCommerce endpoint URL if available
            if (typeof wc_add_to_cart_params !== 'undefined') {
                ajaxurl = wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_wishlist_quantity'); // WooCommerce Ajax endpoint URL (available since 2.4)
            } else {
                ajaxurl = rad.data.ajax_url;
                send_data['action'] = 'get_wishlist_quantity';
            }

            $.ajax({
                url: ajaxurl,
                data: send_data,
                method: 'GET',//Use get to retrive data from server faster
                success : function (data) {
                    $(".wishlist-btn .number").html(data['wishlist_count_products']);
                    if(data['wishlist_count_products'] > 0)
                    {
                        $('.wishlist-aside .wishlist-more').removeClass('empty-wishlist');
                    }
                    else
                    {
                        $('.wishlist-aside .wishlist-more').addClass('empty-wishlist');
                    }
                }
            });

            var $clicked_add_to_wishlist = $(document).find('.add_to_wishlist.adding');
            $clicked_add_to_wishlist.find('.wc-loading').addClass('hide');
            $clicked_add_to_wishlist.fadeOut(400).siblings('.wishlist-link').fadeIn(400);

            rad.add_to_cart();
        });
    };

    /**************************************************
    /* Wishlist actions
    **************************************************/
    rad.wishlist_actions = function () {

        $(document).on('click', '.add_to_wishlist', function () {
            $(this).addClass('adding');
        });

        $(document).on('click', '.remove_from_wishlist', function (e) {
            e.preventDefault();
            $(this).parents('.yith-wcwl-form').addClass('removing');
            $(this).parents('li').addClass('removing');
            $(this).addClass('show-loading').find('.wc-loading').removeClass('hide');
        });
    };

    /**************************************************
    /* Filter drop down ( select ) functionality after ajax request 
    **************************************************/
    rad.layer_nav_ajax_dropdown = function () {
        $('.dropdown_layered_nav').change(function () {

            var slug = $( this ).val(),
                filtername = $(this).closest('select').attr('data-filtername'),
                url = window.location.href; // get current url 

            slug = '?filter_' + filtername + '=' + slug;
            url += slug;
            location.href = url;
        });

    };

    /**************************************************
    /*  product hover
    **************************************************/
    rad.product_hover = function () {
        
        //check existance of woocommerce class
        if ($('.woocommerce').length <= 0)
            return;

        if (rad.is_mobile_or_tablet) {
            $('ul.products li.product').addClass('disable-hover');
        }
    };

    /**************************************************
    /*  product single - gallery 
    **************************************************/
    rad.product_single_lightbox = function (type) {

        if($('#product-fullview-thumbs.rad-product-zoom-popup').length <= 0 || rad.is_mobile_or_tablet)
            return;

        $('#product-fullview-thumbs img, .creative-gallery-first img').on('click',function(){
            var $this = $(this),
                $gallery = $('#product-fullview-thumbs'),
                $lightbox_container = $('#p-g-lightbox'),
                $cursor = $('#p-g-cursor'),
                attributes = {
                    'left' : $this.offset().left ,
                    'top'  : $this.offset().top - rad.$window.scrollTop(),
                    'width': $this.outerWidth()
                },
                $clone = $this.clone(),
                diff = 0,
                lastMousePosition = { y: 0 };
        
            
            rad.stop_scroll();
            $clone.addClass('lightbox-cloned').css({'top': attributes['top'],'left':attributes['left'], 'width': attributes['width']});
            $clone.appendTo($lightbox_container);
            $lightbox_container.addClass('active');
            $clone.addClass('lightbox-open');
            var $clone2 = null;
            setTimeout(function(){
                $clone.css({'top': 0,'left':0,'width': rad.w_width});
                $clone2 = $clone.clone();
                $clone2.css('width','100%');
                $clone2.attr('sizes','');
                
            },100);

            $cursor.addClass('g-opened');
            setTimeout(function(){
                diff = $clone.outerHeight() - rad.w_height;
                document.addEventListener('mousemove', onMouseMove, false);
                $clone2.appendTo($lightbox_container);
            },600);

            if($gallery.hasClass('carousel-gallery'))
            {
                //update position after sliding to clicked slide
                setTimeout(function(){
                    attributes = {
                        'left' : $this.offset().left ,
                        'top'  : $this.offset().top - rad.$window.scrollTop(),
                        'width': $this.outerWidth()
                    };
                },600);
            }

            $lightbox_container.on('click',function(){
                if(!$lightbox_container.hasClass('active'))
                    return;

                rad.start_scroll();
                $cursor.removeClass('g-opened');
                $clone.add($clone2).removeClass('lightbox-open').css('transform','matrix(1, 0, 0,1,0,0)');

                setTimeout(function(){
                    $clone.add($clone2).removeClass('lightbox-open').css({'top': attributes['top'],'left':attributes['left'], 'width': attributes['width']});
                },500);
                setTimeout(function(){
                    $clone.remove();
                    $clone2.remove();
                    $lightbox_container.removeClass('active');
                },1000);
            });
            
            function onMouseMove(evt) {
              lastMousePosition.y = evt.clientY;
              requestAnimationFrame(update);
            }

            function update() {
                var val = ((lastMousePosition.y * diff)/rad.w_height);
                $('.lightbox-open').css('transform','matrix(1, 0, 0,1,0,-' + val+')');
            }

        });
    };

    /**************************************************
    /*  product  detail - gallery 
    **************************************************/
    rad.product_single_sticky = function (type) {
        var mode = {
          sticky_content : false, 
          sticky_addtocart: false, 
        };

        if(type != 'classic' && type != 'carousel')
        {
            mode.sticky_content = true;
        }
        
        if($('body').hasClass('sticky-addtocart'))
        {
            mode.sticky_addtocart = true;
        }
        
        if(rad.is_mobile_or_tablet || (mode.sticky_content == false && mode.sticky_addtocart == false) || !$('body').hasClass('single-product'))
        {
            return;
        }

        var latestKnownScrollPosition = 0,
            tick = false,
            $element = $('body.single-product .summary').eq(0),
            element_height = $element.height(),
            element_width = $element.outerWidth(),
            $social_icons = $('#social-share'),
            $target = $('body.single-product .images'),
            breadcrumb_height = $('body.single-product .woocommerce-breadcrumb').length ? $('body.single-product .woocommerce-breadcrumb').outerHeight() : 0,
            target_top_distance = $target.offset().top + $target.outerHeight(),
            summary_pos = {
                'abs_top' :$element.position().top,
                'abs_left' :$element.position().left,
                'fxd_left' :$element.offset().left,
                'fxd_top' :$element.offset().top
            },
            social_pos = null;

            if($social_icons.length > 0)
            {
                social_pos = {
                    'abs_top' : parseInt($social_icons.css('top').replace(/[^-\d\.]/g, '')),
                    'abs_left' :$social_icons.position().left,
                    'fxd_left' :$social_icons.offset().left,
                    'fxd_top' :$social_icons.offset().top
                };
            }

        if(element_height >= $target.outerHeight())
        {
            mode.sticky_content = false; 
        }

        if(mode.sticky_content)// Just set width in sticky-contetn style
        {
            $element.css('width',element_width);
        }

        if($element.length <= 0)
            return;

        if($('.product-fitgrid-style').length > 0)
        {
            breadcrumb_height = 0;
        }

        var element_treshold = target_top_distance,
            social_treshold = target_top_distance - rad.w_height,
            element_top = 0,
            sticky_addtocart_factor = rad.w_height + 100;


        if((element_height + $target.offset().top) >= rad.w_height)
        {
            if((element_treshold - element_height - $target.offset().top) > 0)
            {
                element_treshold -= (element_height + $target.offset().top);
            }            
        }
        else
        {
            if((element_treshold - rad.w_height) > 0)
            {
                element_treshold -= rad.w_height;
            }
            else
            {
                element_treshold -= element_height ;
            }
        }


        var update_summary_position  = function () {

            if (latestKnownScrollPosition > element_treshold + sticky_addtocart_factor) {
                if(mode.sticky_addtocart == true )
                {
                    $element.addClass('show');
                    $('body').addClass('show-sticky-bar');
                }
            }
            else if (latestKnownScrollPosition > (element_treshold + sticky_addtocart_factor - 50)) {
                if(mode.sticky_addtocart == true )
                {
                    $element.removeClass('show').addClass('sticky-visible');
                    $('body').removeClass('show-sticky-bar');
                }

                if(mode.sticky_content == true )
                {
                    $element.css({
                        position: 'fixed',
                        top: '100%',
                        left: '10px',
                        width: 'calc(100% - 20px)'
                    });
                }
            }
            else if (latestKnownScrollPosition > element_treshold) {
                if(mode.sticky_addtocart == true )
                {
                    $element.removeClass('sticky-visible show');
                }

                if(mode.sticky_content == true )
                {
                    $element.css({
                        position: 'absolute',
                        top: element_treshold+breadcrumb_height,
                        left:summary_pos['abs_left'],
                        width: element_width
                    });
                }
            } else {
                if(mode.sticky_addtocart == true )
                {
                    $element.removeClass('sticky-visible show');
                }
                
                if(mode.sticky_content == true )
                {
                    $element.css({
                        position: 'fixed',
                        top: summary_pos['fxd_top'],
                        left:summary_pos['fxd_left'],
                        width: element_width
                    });
                }
            }

            if(mode.sticky_content == true && social_pos !== null)
            {
                if (latestKnownScrollPosition > social_treshold) {
                    $social_icons.css({
                        position: 'absolute',
                        top: social_treshold + social_pos['abs_top'],
                        left:social_pos['abs_left']
                    });
                } else {
                    $social_icons.css({
                        position: 'fixed',
                        top: social_pos['fxd_top'],
                        left:social_pos['fxd_left']
                    });
                }
            }
            tick = false;
        }

        update_summary_position();

        var requestTick  = function () {
            if (tick == false) {
                window.requestAnimationFrame(update_summary_position);
            }
            tick = true;
        }

        var onScroll  = function () {
            latestKnownScrollPosition = rad.$window.scrollTop();
            requestTick();
        }

        rad.$window.on('scroll', onScroll);
            
    }
    rad.product_thumbnails = function ($target) {

        if ($target === undefined)
            $target = $('body');

        var $product_gallery = $target.find("#product-fullview-thumbs"),
            type = 'classic';

        if($product_gallery.hasClass('fitgrid-gallery'))
        {
            type = 'fitgrid';
        }
        else if($product_gallery.hasClass('creative-gallery'))
        {
            type = 'creative';
        }
        else if($product_gallery.hasClass('massonry-gallery'))
        {
            type = 'massonry';
        }
        else if($product_gallery.hasClass('carousel-gallery'))
        {
            type = 'carousel';
        }
        else if($product_gallery.hasClass('vartical-gallery'))
        {
            type = 'vertical';
        }

        rad.set_img_height($product_gallery);

        
        if(rad.is_mobile_or_vertical_tablet)
        {   
            if(type == 'creative')
            {
                var $first_slide = $('.images > .p-g-item');
                if($first_slide)
                {
                    $first_slide.appendTo($product_gallery);
                }
            }

            if(type == 'vertical' || type == 'fitgrid' || type == 'massonry'  || type == 'creative')
            {
                $product_gallery.find('.p-g-item').addClass( "swiper-slide");
                $product_gallery.addClass( "swiper-container");
                $product_gallery.wrapInner( '<div class="swiper-container clearfix"><div class="swiper-wrapper"></div><div class="swiper-pagination"></div></div>');
            }
            
            
            setTimeout(function(){
                var $g_swiper = new Swiper($product_gallery.find('.swiper-container'), {
                        speed: 700,
                        longSwipesMs: 800,
                        touchAngle: 30,
                        grabCursor: true,
                        touchRatio: 3,
                        followFinger: false,
                        preventClicks: false,
                        spaceBetween: 0,
                        slidesPerView: 1,
                        preloadImages: false,
                        lazy: true,
                        navigation: {
                            nextEl: $product_gallery.find('.rad-carousel-next'),
                            prevEl: $product_gallery.find('.rad-carousel-prev'),
                        },
                        pagination : {
                            el : $product_gallery.find('.swiper-pagination'),
                        },
                    });
            },100);

            return;
        }

        if(type == 'vertical' || $product_gallery.hasClass('.no-gallery'))
        {
            rad.product_single_sticky(type);
            return;
        }
        else if(type == 'fitgrid' || type == 'creative' || type == 'massonry')
        {
            $product_gallery.waitForImages(function () {
                $product_gallery.isotope({
                    itemSelector: '.p-g-item',
                    layoutMode: 'masonry',
                    perfectMasonry: {
                        layout: 'vertical'
                    },
                });

                rad.product_single_sticky(type);
            });
        }
        else
        {
            rad.product_single_sticky(type);

            var $thumbnails = $target.find("#product-thumbs"),
                slidesNum = $thumbnails.find('.swiper-slide').length,
                $thumbnails_swiper_container = $thumbnails.find(".swiper-container"),
                $gallery_swiper_container = $product_gallery.find('.swiper-container'),
                $gallery_swiper = undefined;

            if (rad.w_width > 979) {

                if($thumbnails.length > 0)
                {
                    var virtualTranslate = false,
                        height = slidesNum * $thumbnails.find('.swiper-slide').outerHeight() + (slidesNum - 1)* 20;
                    
                    if(height <= $gallery_swiper_container.outerHeight())
                    {
                        virtualTranslate = true;
                    }

                    $thumbnails.css('height',$product_gallery.outerHeight());
                    var $thumbnails_swiper = new Swiper($thumbnails_swiper_container, {
                        speed: 700,
                        longSwipesMs: 800,
                        touchAngle: 30,
                        grabCursor: true,
                        touchRatio: 3,
                        preventClicks: false,
                        slideToClickedSlide: true,
                        spaceBetween: 20,
                        slidesPerView: 1,
                        virtualTranslate : virtualTranslate,
                        direction: 'vertical',
                        preloadImages: false,
                        lazy: true,
                        on : {
                            slideChange : function (swiper) {
                                var swiper = this;
                                if($gallery_swiper !== undefined)
                                    $gallery_swiper.slideTo(swiper.activeIndex);
                                }
                        }
                    });
                }

                var isLoop = false,
                    autoplay = false,
                    slidesPerView = 1,
                    freeMode = false;

                if ( rad.w_width < 768) {
                    isLoop = true;
                }

                if(type == 'carousel')
                {
                    slidesPerView = 'auto';
                    freeMode = true;
                }                    

                if ($thumbnails_swiper_container.hasClass('auto-play'))
                {
                    autoplay = {
                        delay: 6500,
                        disableOnInteraction: false,
                    };         
                }

                $gallery_swiper = new Swiper($gallery_swiper_container, {
                    autoplay: autoplay,
                    speed: 500,
                    longSwipesMs: 700,
                    touchAngle: 30,
                    loop: isLoop,
                    spaceBetween: 0,
                    slidesPerView: slidesPerView,
                    followFinger: false,
                    freeMode : freeMode,
                    slideToClickedSlide : true,
                    navigation: {
                        nextEl: $gallery_swiper_container.find('.rad-carousel-next'),
                        prevEl: $gallery_swiper_container.find('.rad-carousel-prev'),
                    },
                    on: {
                        slideChange : function (swiper) {
                            var swiper = this;
                            
                            if ( !rad.is_touch_device) {
                                if ($thumbnails_swiper !== undefined) {
                                    if(!swiper.isBeginning)
                                    {
                                        $thumbnails_swiper.slideTo(swiper.activeIndex);
                                    }
                                    else
                                    {
                                        $thumbnails_swiper.slideTo(0);
                                    }
                                    
                                }
                            }

                        }
                    }
                });

                if (!rad.is_touch_device) {
                    //stop and start slider on hover in product single page
                    if(autoplay != false && $gallery_swiper.autoplay.running)
                    {
                        $gallery_swiper_container.hover(function () {
                            $gallery_swiper.autoplay.stop();
                        }, function () {
                            $gallery_swiper.autoplay.start();
                        });
                    }

                    //Start autoplay if clicked when slider is disabled by product variation choosing
                    $thumbnails.add($product_gallery).on('click', function () {
                        if ($(this).hasClass('stop-by-variations')) {
                            $gallery_swiper.autoplay.start();
                            $thumbnails.add($product_gallery).removeClass('stop-by-variations');
                        }
                    });
                }

            }
        }
    };


    /**************************************************
    /*  Set correct image height
    **************************************************/
    rad.set_img_height = function($target) {
        $target.find('img').each(function(){
            var $img = $(this);
            if($img.attr('height') == '')
            {
                $img.attr('height',$img.height());
            }
        });
    }

    /**************************************************
    /*  carousel Shortcode
    **************************************************/
    rad.carousel = function ($container) {

        var self = this,
            $carousel;

        if ($container === undefined)
            $carousel = $('.carousel');
        else
            $carousel = $container.find('.carousel');

        if ($carousel.length <= 0)
            return;

        // FullWidth Carousel remove col12 paddings
        $carousel.parents('.fullWidth').find('.vc_col-sm-12').css({
            'padding-right': '0px',
            'padding-left': '0px',
        });
        
        $carousel.each(function () {

            var $this = $(this),
                $container = $this.find('.products'),
                set_visible_number = parseInt($this.find('.swiper-container').attr('data-visibleitems')),
                visibleItems = rad.getVisibleItemNum($this, set_visible_number),
                loopSlideNum = visibleItems + 1,
                gutter = 20,
                slideClass = 'swiper-slide',
                freemode = false,
                loop = true,
                autoplay = false,
                scrollbar = false;

            if ($this.data('autoplay') == 'on') {
                autoplay = {
                    delay: 5000,
                    disableOnInteraction: false,
                };
            }

            if ($this.hasClass('freemode')) {
                freemode = true;
                loop = false;
                loopSlideNum = 0,
                visibleItems = 'auto';
            }

            if ($this.hasClass('wc-shortcode')) // wc-shortcode carousels
            {
                if($this.find('ul.products').hasClass('two-unit-gutter'))
                    gutter = 40;

                if ( visibleItems == 1) {
                    gutter = 0;
                }

                if ( $this.find('li.product').length <= visibleItems ) {
                    return;
                }

                slideClass = 'product';
                autoplay = false;
                if ($this.find('ul.products').data('autoplay') == 'on') {
                    autoplay = {
                        delay: 3000,
                        disableOnInteraction: false,
                    };
                }

            } 
            else if ($this.hasClass('testimonial-block'))
            {
                gutter = 10;
            }
            else if ($this.hasClass('post-media')) {//blog
                gutter = 0;
                autoplay = {
                    delay: 3000,
                    disableOnInteraction: false,
                };
            }
            else // image carousels
            {

                if ($this.hasClass('no-gutter') || visibleItems == 1) {
                    gutter = 0;

                } else {
                    gutter = 20;
                }

            }

            if($this.find('.swiper-scrollbar').length > 0)
            {
                scrollbar = {
                    el : $this.find('.swiper-scrollbar'),
                    hide:false,
                    snapOnRelease : true,
                    draggable: true,
                }
                
                loop = false;

            }

            if(rad.is_mobile_or_vertical_tablet && visibleItems == 1)
            {
                gutter = 0;
            }

            if(rad.is_mobile_or_vertical_tablet)
            {
                freemode = false;
            }

            var swiper = new Swiper($this.find('.swiper-container').eq(0), {
                autoplay: autoplay,
                touchAngle: 45,
                speed: 600,
                longSwipesMs: 800,
                loop: loop,
                slidesPerView: visibleItems,
                loopedSlides: loopSlideNum,
                slideClass: slideClass,
                spaceBetween: gutter,
                watchSlidesVisibility: true,
                preloadImages: false,
                freeMode : freemode,
                pagination: {
                    el: $this.find('.swiper-pagination'),
                    clickable: true,
                },
                scrollbar: scrollbar,
                navigation: {
                    nextEl: $this.find('.rad-carousel-next'),
                    prevEl: $this.find('.rad-carousel-prev'),
                },
                on: {
                    init : function () {
                        if ($container.length) {
                            rad.showAnimation($container, 'carousel');
                        }
                        else {
                            rad.showAnimation($this, 'image-carousel');
                        }
                    },
                    slideChangeTransitionEnd : function (swiper) { 

                        if ($this.hasClass('wc-shortcode')) {
                            rad.showAnimation($container, 'carousel');
                        }
                        else {
                            rad.showAnimation($this, 'image-carousel');
                        }

                    },
                    autoplayStop : function (swiper) {

                        if (autoplay != 0) {
                            swiper.startAutoplay();
                        }

                    },
                    touchEnd : function (swiper) {

                        if ($this.hasClass('wc-shortcode')) {
                            rad.showAnimation($container, 'carousel');
                        }
                        else
                        {
                            rad.showAnimation($this, 'image-carousel');
                        }

                    },
                    transitionStart : function (swiper) {
                        if ($this.hasClass('wc-shortcode')) {
                            $this.find('li.last-visible-item').removeClass("last-visible-item");
                            var $last_visible_item = $this.find('.swiper-slide-visible').last().addClass("last-visible-item");
                        }
                    },
                    loopFix : function(swiper) {
                        //Remove fetching class and prepare it for images lazy loading
                        $this.find('.swiper-slide-duplicate .lazy-load-on-load').removeClass('fetching');
                        rad.lazy_on_load($this.find('.swiper-slide-duplicate'));                        
                    }
                }
            });
        });
    };

    rad.getVisibleItemNum = function ($container, visibleItems) {

        if (($container.hasClass('wc-shortcode')) || ($container.hasClass('testimonial-block')) ) {
            if (rad.w_width <= 1140) {
                if (visibleItems > 3) {
                    visibleItems = 3; //3columns in vertical tablet devices
                }
                //2column in mobiles
                if (rad.w_width <= 979) {
                    if (visibleItems >= 2) {
                        visibleItems = 2;//2columns in mobile devices
                    }

                    if (rad.w_width <= 767) {
                        visibleItems = 1;//1column in mobile devices
                    }
                }
            }
        } 
        else {
            if (rad.w_width <= 979) {
                if (visibleItems > 3) {
                    visibleItems = 3; //3columns in vertical tablet devices
                }
                //2column in mobiles
                if (rad.w_width <= 767) {
                    if (visibleItems >= 2) {
                        visibleItems = 2;//2columns in mobile devices
                    }

                    if (rad.w_width <= 480) {
                        visibleItems = 1;//1column in mobile devices
                    }
                }
            }

        }

        return visibleItems;
    };

    rad.updateCarousel = function () {
        $('.carousel').each(function () {

            var $this = $(this),
                $swiperContainer = $this.find('.swiper-container');

            if ($swiperContainer[0].swiper != undefined) {
                var visibleItems = rad.getVisibleItemNum($this, $swiperContainer.attr('data-visibleitems'));
                
                if(!$this.hasClass('freemode'))
                {
                    $swiperContainer[0].swiper.params.slidesPerView = visibleItems;
                    $swiperContainer[0].swiper.params.loopedSlides = visibleItems + 1;
                }
                
                if ($this.hasClass('wc-shortcode')) // wc-shortcode carousels
                {
                    $swiperContainer[0].swiper.update(true);
                    rad.showAnimation($this.find('.products'), 'carousel');
                } 
                else if (($this.hasClass('testimonial-block')))
                {
                    $swiperContainer[0].swiper.update(true);
                
                }
                else {
                    rad.showAnimation($this, 'image-carousel'); 
                    $swiperContainer[0].swiper.update(true);
                }

            }
        });
    };

    /**************************************************
    /*  progress bar with animation Function
    **************************************************/
    rad.progressbar = function () { // progressbar run in document ready and call after Ajax

        var $progressbar = $('.progress-bar-block:not(.elem-anim), .progress-bar-block.elem-anim.no-resp-anim');

        if (!$progressbar.length) return;

        rad.progressbarAnimate($progressbar);
    };

    /* Animate progressbar */
    rad.progressbarAnimate = function ($element) { // call when its appeared on viewport


        $element.each(function () {
            var $this = $(this),
                percentage = $this.find('.fill').data('percentage');
            $this.find('.value').addClass("complete");
            $this.find('.fill').css('width', percentage + '%');

        });
    };

    /**************************************************
    /*  Easy Pie Chart Function
    **************************************************/

    rad.chart = function () {


        var $chart_block = $('.chart-block:not(.elem-anim), .chart-block.elem-anim.no-resp-anim');

        if (!$chart_block.length) return;

        rad.chartAnimate($chart_block);
    };

    /* Animate Chart */
    rad.chartAnimate = function ($element) { // call when its appeared on viewport

        var animation = false;

        if (!rad.is_mobile && !rad.is_tablet) {
            animation = { duration: 2500, enabled: true };
        }

        $element.each(function () {
            var $chart_wrapper = $(this).find('.chart-wrapper');
            $chart_wrapper.easyPieChart({
                scaleColor: false,
                barColor: $chart_wrapper.attr('data-bar-color'),
                lineWidth: 2,
                trackColor: $chart_wrapper.attr('data-track-color'),
                lineCap: 'round',
                easing: 'easeOutQuint',
                animate: animation,
                size: 120,
            });
        });
    };

    /**************************************************
    /*  Count-down
    **************************************************/
    rad.countdown = function() {
        $(".countdown-timer").each(function() {
            var $this = $(this);
            if($this.hasClass('initiated'))
                return;

            $this.addClass('initiated');

            var updateCountDown = function() {
                var date = Date.parse($this.data("end")) / 1000,
                now = Math.floor($.now() / 1000),
                $day = $this.find(".days"),
                $hours = $this.find(".hours"),
                $min = $this.find(".minutes"),
                $second = $this.find(".seconds"),
                day_distance = date - now;

                if (day_distance > 0) {
                    var day = Math.floor(day_distance / 86400);
                    day_distance -= 60 * day * 60 * 24;
                    var hours = Math.floor(day_distance / 3600);
                    day_distance -= 60 * hours * 60;
                    var min = Math.floor(day_distance / 60);
                    day_distance -= 60 * min,
                    10 > day && (day = "0" + day),
                    10 > hours && (hours = "0" + hours),
                    10 > min && (min = "0" + min),
                    10 > day_distance && (day_distance = "0" + day_distance),
                    1 > $day.length || "00" == day ? $day.parent().hide() : $day.text(day),
                    $hours.text(hours),
                    $min.text(min),
                    $second.text(day_distance)
                }
            };
            setInterval(updateCountDown, 1000),
            updateCountDown()
        })
    };

    /**************************************************
    /*  Counter Box
    **************************************************/

    rad.counter_block = function () { // counterBox run in document ready and call after Ajax

        var $counterBoxContainers = $('.counter-block:not(.elem-anim), .counter-block.elem-anim.no-resp-anim');
        if (!$counterBoxContainers.length) return;
        rad.counter_blockAnimate($counterBoxContainers);
    };

    /* Counter Box With Animation */
    rad.counter_blockAnimate = function ($element) { // call in appear function - run when element come to screen view

        $element.each(function () {
            var countNmber = $(this).attr('data-count-num');
            $(this).find('.number').countTo({
                from: 0,
                to: countNmber,
                speed: 2500,
                refreshInterval: 10,
            });
        });
    };

    /**************************************************
    /*  Animation For elements
    **************************************************/
    rad.element_animation = function () {
        var self = this,
            $shortcodes = $('.elem-anim,.img-anim').not('.elem-grid-anim');

        if($shortcodes.length <= 0)
            return;

        var animate_shortcodes = function (item) {
            var $this = item,
                delay = parseInt($this.attr('data-delay'));

            if((rad.is_mobile || rad.is_tablet) && $this.hasClass('no-resp-anim'))
            {
                $this.addClass('no-resp-animated');
                return;
            }

            $this.css('transition-delay', delay + 'ms');
            $this.addClass('animated');

            //Run Counter Box
            if ($this.hasClass("counter-block")) {
                rad.counter_blockAnimate($this);
            }

            //Run Pie Chart
            if ($this.hasClass("chart-block")) {
                rad.chartAnimate($this);
            }

            //Run Progress bar
            if ($this.hasClass("progress-bar-block")) {
                rad.progressbarAnimate($this);
            }

        }

        $shortcodes.waypoint({
            handler : function () {
                var $item = $(this.element);
                animate_shortcodes($item);
                this.destroy();
            },
            offset: '80%'
        });

    };

    /**************************************************
    /*  tabs
    **************************************************/
    rad.tabs_tour_accordion = function () {

        //Tab & Tour
        $('.tab-block .tab-nav li').on('click', function () {
            var $current_tab = $(this),
                $block = $current_tab.closest('.tab-block'),
                id = $current_tab.data('id'),
                $new_block = $block.find('.tab-content').eq(id);

            if ($current_tab.hasClass('active'))
                return;

            //activate new tab
            $block.find('.tab-content').removeClass('active');
            $block.find('.tab-nav li').removeClass('active');
            $current_tab.addClass('active');
            $new_block.addClass('active');

            rad.product_thumbnails();//Products
            rad.product_variation();
            rad.shop_grid_animation($new_block);
            rad.blocks(true);//shortcodes
            rad.sticky_products_layout();

        });
    };

    rad.pagable_container = function () {

        $('.vc_tta-container .vc_pagination li').on('click', function (e) {
            e.preventDefault();
            var $current_tab_nav = $(this),
                $container = $current_tab_nav.closest('.vc_tta-panels-container'),
                index = $current_tab_nav.index(),
                $new_block = $container.find('.vc_tta-panels .vc_tta-panel').eq(index);

            if ($current_tab_nav.hasClass('vc_active'))
                return;

            //activate new tab
            $container.find('.vc_tta-panel').removeClass('vc_active');
            $container.find('.vc_pagination li').removeClass('vc_active');
            $current_tab_nav.addClass('vc_active');
            $new_block.addClass('vc_active');

            rad.product_thumbnails();//Products
            rad.product_variation();
            rad.shop_grid_animation($new_block);
            rad.carousel($new_block);//Carousel
            rad.blocks(true);//shortcodes

        });
    };

    /**************************************************
    /*  toggle - FAQ
    **************************************************/
    rad.toggle = function () {

        var $toggle_blocks = $('.toggle-block');

        if (!$toggle_blocks.length) return;

        $toggle_blocks.each(function () {
            var $block = $(this),
                $title = $block.find('.title'),
                $content = $block.find('.toggle-content'),
                is_accordion = $block.hasClass('accordion'),
                collapse_all = $block.hasClass('allow-collapse-all');

            if ($block.hasClass('open')) {
                $content.slideDown();

            } else {
                $content.slideUp();

            }

            $title.off("click").on('click',function (e) {

                if(is_accordion && !collapse_all)
                {
                    if ($block.hasClass('open'))
                        return;

                    $block.addClass('open');
                    $content.slideDown();
                    $block.siblings('.toggle-block').removeClass('open').find('.toggle-content').slideUp();

                }
                else
                {
                    $block.toggleClass('open');
                    if ($block.hasClass('open')) {
                        $content.slideDown();
                    } else {
                        $content.slideUp();
                    }                   
                }
            });
        });
    };

    /**************************************************
    /*  Navigation
    **************************************************/
    rad.show_overlay = function(time, toAddClass, toRemoveClass, extraClassTime) {
        time = typeof time  === 'undefined' ? 0 : time;
        toAddClass = typeof toAddClass  === 'undefined' ? '' : toAddClass;
        toRemoveClass = typeof toRemoveClass  === 'undefined' ? '' : toRemoveClass;
        extraClassTime = typeof extraClassTime  === 'undefined' ? 0 : extraClassTime;

        var $overlay = $('#overlay-layer');
        $(document).trigger('clear_hide_overlay_timeouts');
        setTimeout(function(){
            $overlay.addClass('open');
        },time);
        
        setTimeout(function(){
            $overlay.addClass(toAddClass);
            $overlay.removeClass(toRemoveClass);
        },extraClassTime);
    };

    rad.hide_overlay = function(time, toRemoveClass, extraClassTime) {
        time = typeof time  === 'undefined' ? 0 : time;
        toRemoveClass = typeof toRemoveClass  === 'undefined' ? '' : toRemoveClass;
        extraClassTime = typeof extraClassTime  === 'undefined' ? 0 : extraClassTime;

        var $overlay = $('#overlay-layer'),
            remove_open_time_out,
            remove_extra_class_time_out;

        remove_open_time_out = setTimeout(function(){
            $overlay.removeClass('open');
        },time);
        
        remove_extra_class_time_out = setTimeout(function(){
            $overlay.removeClass(toRemoveClass);
        },extraClassTime);

        $(document).on('clear_hide_overlay_timeouts',function(){
            clearTimeout(remove_open_time_out);
            clearTimeout(remove_extra_class_time_out);
        })
    };

    rad.mega_menu = function () {

        if( rad.w_width <= 1140)
            return;

        var $menuItem = $('.navigation > ul > .mega-menu-parent'),
            space = 0,
            bg_initial_height = $('#menu-bg').outerHeight();

            if($('#rad-menu').hasClass('edge-with-space'))
            {
                space = 20;
            }

        var set_megamenu_position = function ($menu) {

            var $menuWrapper = $menu.find('.menu-item-wrapper'),
                $secondlevelItems = $menuWrapper.find('> div > ul > li'),
                rightOffset = 0;//store the offset of megamenu from right side of screen
            
            $menuWrapper.css("margin-left",'');
            $menuWrapper.css("width",'');
            $menuWrapper.css("height",'');

            if($menuWrapper.length <= 0)
            {
                return;//skip current itteration
            }

            if ($menu.hasClass('mega-menu-parent')) {
                $menuWrapper.outerWidth(rad.w_width - space);
                $menuWrapper.outerHeight($menuWrapper.find('> .container').height()+ 'px');
                $menuWrapper.css('margin-left', '');//Reset margin-left to calculate correct position
                rightOffset = rad.w_width - (space/2) - ($menuWrapper.offset().left + $menuWrapper.outerWidth());
                if (rightOffset < 0) {
                    $menuWrapper.css('margin-left', rightOffset); // cause mega menu be in window 
                }
                return $menuWrapper.outerHeight();
            }
            else {
                var $subMenuWidth = $menu.find('> ul').eq(0).outerWidth();
                rightOffset = rad.w_width - ($menu.offset().left + $subMenuWidth);
                if (rightOffset < $subMenuWidth) {
                    $menu.addClass('left-submenus');
                }
            }
        }
        

        $menuItem.mouseenter(function () {
            var $this = $(this),
            height = set_megamenu_position($this);
            rad.show_overlay(200,'low-zindex','high-zindex',0);
            rad.set_menu_bg_height(height + bg_initial_height - 3);
        }).mouseleave(function (e) {
            $('#menu-bg').css("height", "" );
        });

        $('#rad-menu nav').mouseleave(function() {
            if(!$('#rad-menu').hasClass('collection-active'))
            {
                rad.hide_overlay(300,'low-zindex',500);
            }
        });
    };

    rad.set_menu_bg_height = function(height) {

        if(typeof height === 'undefined')
        {
            $('#menu-bg').css("height",'');
        }
        else
        {
            $('#menu-bg').css("height",height);
        }
        
    }

    /**************************************************
    /* Built-in Slider
    **************************************************/
    rad.built_in_slider = function () {
        var $slider = $('#slider'),
            $slides,
            $second_slide,
            $first_slide,
            $firstDuplicateSlide,
            $secondDuplicateSlide,
            pagination_type = 'bullets',
            slides_count = $slider.find('.swiper-slide').length;

        if($slider.hasClass('progress-pagination'))
        {
            pagination_type = 'progressbar';
        }

        if ($slider.hasClass('slide')) {
            var initiated = false,
                swiper = new Swiper('#slider .swiper-container', {
                loop: true,
                loopedSlides: 0,
                speed: 1000,
                keyboardControl: true,
                followFinger: true,
                longSwipesRatio: 1,
                longSwipesMs: 200,
                mousewheel: false,
                autoplay: {
                    disableOnInteraction: false,
                    delay: 4500,
                },
                navigation: {
                    nextEl: '.rad-slider-next',
                    prevEl: '.rad-slider-prev',
                },
                pagination : {
                    el: '#slider .swiper-pagination',
                    type : pagination_type,
                    clickable : true,
                    renderProgressbar: function (progressbarFillClass) {
                        return '<span class="current">01</span><span class="swiper-pagination-progressbar-fill"></span><span class="total">'+ ('0' + slides_count).slice(-2) +'</span>';
                    }
                },
                slidesPerView: 1,
                on : {
                    init : function () {
                        initiated = true;
                        $first_slide = $slider.find('.swiper-slide').eq(1);
                        $firstDuplicateSlide = $slider.find('.swiper-slide-duplicate').eq(0);
                        $secondDuplicateSlide = $slider.find('.swiper-slide-duplicate').eq(1);
                    },
                    slideChangeTransitionStart : function () {
                        var swiper = this;
                        if (initiated) // check it because onSetTranslate fire before onInit
                        {
                            if ($secondDuplicateSlide.hasClass('swiper-slide-active')) {
                                $first_slide.addClass('swiper-slide-active');

                            } else if ($firstDuplicateSlide.hasClass('swiper-slide-active')) {
                                $slider.find('.swiper-slide').eq(slides_count).addClass('swiper-slide-active');
                            }
                        }

                        if(pagination_type == 'progressbar')
                        {   var index = swiper.activeIndex;
                            if(index > slides_count )
                            {
                                index = 1;
                            }
                            $('#slider .current').html(('0' + index).slice(-2));
                        }
                    },
                }
            });
        }
        else {
            var initiated = false,
                swiper = new Swiper('#slider .swiper-container', {
                loop: true,
                speed: 1000,
                keyboard: true,
                autoplay : {
                    delay: 4500,
                    disableOnInteraction: false,
                },
                effect: 'fade',
                mousewheel: false,
                navigation: {
                    nextEl: '.rad-slider-next',
                    prevEl: '.rad-slider-prev',
                },
                slidesPerView: 1,
                pagination : {
                    el: '#slider .swiper-pagination',
                    type : pagination_type,
                    clickable : true,
                    renderProgressbar: function (progressbarFillClass) {
                        return '<span class="current">01</span><span class="swiper-pagination-progressbar-fill"></span><span class="total">'+ ('0' + slides_count).slice(-2) +'</span>';
                    }
                },
                on : {
                    init : function () {
                        initiated = true;
                        $slides = $slider.find('.swiper-slide');
                        $second_slide = $slides.eq(2);
                        $first_slide = $slides.eq(1);
                        $firstDuplicateSlide = $slides.filter('.swiper-slide-duplicate').eq(0);
                        $secondDuplicateSlide = $slides.filter('.swiper-slide-duplicate').eq(1);
                    },
                    slideChangeTransitionStart : function () {
                        var swiper = this;

                        if (initiated) // check it becouse onSetTranslate fire before onInit
                        {
                            //Reset
                            $slides.css("visibility", "").filter('.fake-active').removeClass('fake-active');

                            if ($secondDuplicateSlide.hasClass('swiper-slide-active')) {
                                //Active slides
                                $first_slide.addClass('fake-active swiper-slide-active');
                            }

                            //correct position of slide when slide are at the end of slide
                            if ($firstDuplicateSlide.hasClass('swiper-slide-active')) {
                                $slides.eq(slides_count).addClass('fake-active swiper-slide-active');
                            }
                        }

                        if(pagination_type == 'progressbar')
                        {   var index = swiper.activeIndex;
                            if(index > slides_count )
                            {
                                index = 1;
                            }
                            $('#slider .current').html(('0' + index).slice(-2));
                        }
                    }
                }
            });
        }

    };

    /**************************************************
    /*  Blog Load More Function 
    **************************************************/
    rad.card_blog_load_more = function () {

        var self = this,
            $card_blog = $('.card-blog');

        if ($card_blog.length <= 0 || $card_blog.find('.card-blog-load-more').length <= 0 || $card_blog.data('maxpages') < 2)
            return;

        $card_blog.find('.card-blog-load-more a').click(function (e) {
            e.preventDefault();

            var $load_more = $(this),
                $blog = $load_more.parents('.card-blog'),
                blog_id = '#' + $blog.attr('id'),
                start_page_num = parseInt($blog.data('page')),
                next_page_num = start_page_num + 1,
                max = $blog.data('maxpages'),
                current_url = window.location.href,
                next_page = rad.updateQueryStringParameter(current_url.replace("#", ""), 'postpage', next_page_num ),
                is_loading = false;

            if (max < 2 || is_loading)
            {
                return;
            }

            //Activate loadmore button 
            if (next_page_num > max) {
                $load_more.addClass('no-more');
                return;
            }

            is_loading = true;
            $load_more.addClass('loading');
            
            var $pageContainer = $('<div class="posts-page-' + next_page_num + '"></div>');
            $pageContainer.load(next_page + ' ' + blog_id, function () {
                var $content = $($pageContainer.find('.rad-card-posts').eq(0).html());
                
                //$content.appendTo($blog.find('.rad-card-posts'));
                $blog.find('.rad-card-posts').isotope('insert', $content);
                setTimeout(function () {
                    // call isotope animation ( defualt and custom mode )
                    rad.isotopeAnimation($blog);
                    rad.lazy_on_load($blog);
                    rad.scatter_parallax_init();
                    rad.scroll_parallax_init();
                    rad.card_blog(true);//reload isotope and swiper for card blog
                }, 500);

                is_loading = false;
                $blog.attr('data-page', next_page_num);
                $load_more.removeClass('loading');

                if (next_page_num == max) {
                    $load_more.addClass('no-more');
                }

            });
        });
    };

    /***************************************************/
    /*  phone Navigation
    /***************************************************/
    rad.responsive_menu = function () {

        $('.toggle_submneu').on('click', function () {
            var $toggle = $(this);

            if ($toggle.hasClass('open')) {
                $toggle.closest('li').removeClass('submenu-open');
                $toggle.siblings('ul.sub-menu').slideUp('300', 'easeInOutCirc');
            }
            else {
                $toggle.closest('li').addClass('submenu-open');
                $toggle.siblings('ul.sub-menu').slideDown('300', 'easeInOutCirc');
            }

            $toggle.toggleClass('open');
        });
    };


    /***************************************************/
    /*  phone Navigation
    /***************************************************/
    rad.toggle_widgets_childs = function () {
        $('.widget ul.children, .widget ul.sub-menu').before('<span class="child-plus"></span>');
        $('.widget').on('click', '.child-plus', function () {
            var $toggle = $(this).parent('li');
            $toggle.toggleClass('submenu-open');
        });
    };

    /***************************************************/
    /*  Add To Cart - Open Toggle Sidebar When click On Add to cart Buttons 
    /***************************************************/
    rad.add_to_cart = function () {

        var self = this;

        $(document.body).on('adding_to_cart', function() {
            $(document).trigger('open-sidebar',[{type:'cart'}]);
        });

        // Open the Toggle Sidebar When Click On Add To Cart Buttons
        $(document).on('click', ".add_to_cart_button, .single_add_to_cart_button", function (e) {
            var $button = $(this),
                $productForm = $button.closest('form');

            if ( $button.hasClass('.affilate-product') || $button.hasClass('.product_type_variable') || $button.hasClass('disabled') || $productForm.length <= 0)
                return 0;

            e.preventDefault();

            if(! $button.hasClass('.ajax_add_to_cart') && ($button.hasClass('.single_add_to_cart_button') && !$('body').hasClass('.ajax-add-to-cart'
                ))){
                $productForm.submit();
                return;  
            }

            var data = {
                product_id: $productForm.find("input[name='add-to-cart'],button[name='add-to-cart']").val(),
                product_variation_group_data: $productForm.serialize()
            };

            // Trigger event
            $(document.body).trigger('adding_to_cart', [$button, data]);

            // Ajax action
            $.ajax({
                type: "POST",
                url: "?add-to-cart=" + data.product_id + "&rad-ajax-add-to-cart=1",
                data: data.product_variation_group_data,
                dataType: "html",
                cache: false,
                headers: { 'cache-control': 'no-cache' },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                },
                success: function (response) {

                    if (!response) {
                        return;
                    }

                    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 {

                        $(".widget_shopping_cart_content").html(response)
                        var $response = $(".widget_shopping_cart_content");

                        // Get replacement elements/values
                        var fragments = {
                            ".product_list_widget": $response.find('.product_list_widget'), // Cart items Detail
                        };

                        // Replace elements
                        $.each(fragments, function (selector, $element) {
                            if ($element.length) {
                                $(selector).each(function () {
                                    if ($(this).parents('.widget_shopping_cart_content').length) {
                                        $(this).replaceWith($element);
                                    }
                                });
                            }
                        });

                        // wait All Replace Elemets Complete then trigger added_to_cart
                        setTimeout(function () {
                            $(document.body).trigger("added_to_cart");
                            $button.removeClass('loading');
                            $button.removeClass('added');
                        }, 100);
                    }
                }
            });

            if ($('body').hasClass('disable-scroll')) { // is quick view window first wait 300ms then close it and then open sidebar cart.

                setTimeout(function () {
                    rad.modals_close();
                }, 300);

                setTimeout(function () {
                    $(document).trigger('open-sidebar',[{type:'cart'}]);

                }, 600);

            } else {
                $(document).trigger('open-sidebar',[{type:'cart'}]);

            }
        
        });
    };

    /***************************************************/
    /*  product variation adding to cart
    /***************************************************/
    rad.add_to_cart_events = function () {

        // Updating cart and show loading
        $(document.body).on('adding_to_cart', function (event, param1, data) {
            var $cart_list = $('.wc-cart-aside .cart_list');
            $('.wc-cart-aside .cart-aside-wrapper').addClass('updatingCart');
            if($cart_list.find('a[data-product_id='+ data.product_id+']').length <= 0 )
            {
                var $new_item = $('.wc-cart-aside li.mini_cart_item').eq(0).clone().addClass('removing');
                $cart_list.append($new_item);
                setTimeout(function(){
                    $new_item.removeClass('removing');
                },50)
            }
            
        });

        $(document.body).on('added_to_cart', function () {
            //$('.wc-cart-aside .cart-aside-wrapper').removeClass('updatingCart');
            $(document.body).trigger('wc_fragment_refresh');
        });
        $(document.body).on('removed_from_cart', function () {
            $('.wc-cart-aside .cart-aside-wrapper').removeClass('updatingCart');
        });
        $(document).on('wc_fragments_refreshed', function () {
            setTimeout(function(){
                $('.wc-cart-aside .cart-aside-wrapper').removeClass('updatingCart');
            },100);
        });
    };

    rad.custom_cursor = function () {
        var $elements = $('.custom-cursor:not(initiated)'),
            $body = $('body'),
            $cursor = $('.rad-cursor'),
            lastMousePosition = { x: 0, y: 0 };

        if($elements.length <= 0 || rad.is_mobile_or_tablet)
            return;

        $elements.addClass('initiated');

        function onMouseDown() {
            $cursor.addClass('is-mouse-down');
            requestAnimationFrame(update);
        }

        function onMouseUp() {
            $cursor.removeClass('is-mouse-down');
            requestAnimationFrame(update); 
        }

        function onMouseMove(evt) {
            lastMousePosition.x = evt.clientX;
            lastMousePosition.y = evt.clientY;
            requestAnimationFrame(update);
        }

        function update() {
            var $hovered_element = $(document.elementFromPoint(lastMousePosition.x, lastMousePosition.y));
            // Check if the element is on hover state
            $hovered_element = $hovered_element.hasClass('custom-cursor')? $hovered_element : $hovered_element.parents('.custom-cursor');
            if ($hovered_element.length) {
                var whichCursor = $hovered_element.attr('data-cursor');
                $body.addClass('is-cursor-active');
                $cursor = $(whichCursor);
                $cursor.addClass('is-active');
            } else {
                $body.removeClass('is-cursor-active');
                $cursor.removeClass('is-active');
            }

            // now move cursor to lastMousePosition
            $cursor.css({
                'transform': 'translate3d(' + lastMousePosition.x + 'px,' + lastMousePosition.y + 'px, 0)'
            });
        }


        document.addEventListener('mousemove', onMouseMove, false);
    }
    /***************************************************/
    /*  Toggle Sidebar container  + cart container
    /***************************************************/
    rad.wc_header_categories = function () {
        var $toggle = $('#cat-toggle'),
            $cats = $('#cat-disply'),
            centeredSlides = false;

        if($cats.length <= 0 )
            return;

        $toggle.on('click',function(e) {
            e.preventDefault();
            $toggle.toggleClass('open');
            $cats.toggleClass('open');
        });

        if(rad.is_mobile_or_vertical_tablet && rad.is_touch_device)
        {
            centeredSlides = true;
        }

        var $gallery_swiper = new Swiper($cats, {
            speed: 700,
            longSwipesMs: 700,
            touchAngle: 30,
            loop: false,
            centeredSlides : centeredSlides,
            slidesPerView: 'auto',
            followFinger: true,
            freeMode : true,
        });

        var slides_width = 0;
        $cats.find('li').each(function(index) {
            slides_width += $(this).outerWidth();
        });

        if(slides_width <= rad.w_width)
        {
            $cats.find('.swiper-wrapper').addClass('low-slide-num');
        }
    };

    /***************************************************/
    /*  WC categories in top of shop
    /***************************************************/
    rad.wc_top_categories = function () {
        var $cats = $('#rad-shop-cats');

        if($cats.length <= 0 )
            return;

        if(rad.is_mobile_or_vertical_tablet)
        {
            $cats.removeClass('simple').addClass('dropdown mobile-v');
            $cats.find('.cat-switch').on('click', function(){
                $(this).toggleClass("open");
            });
        }
        else
        {
            $cats.addClass('desktop-v');
        }
    };
    
    /***************************************************/
    /*  Toggle Sidebar container  + cart container
    /***************************************************/
    rad.toggle_aside = function () {
        var $header = $('#rad-menu'),
            $asides = $('.toggle-aside'),
            $hamburger_menu = $asides.filter('.hamburger-menu'),
            $wc_cart_aside = $asides.filter('.wc-cart-aside'),
            $collection_aside = $asides.filter('.collection-aside'),
            $resp_nav_aside = $asides.filter('.resp-nav-aside'),
            $search_container = $asides.filter('#search-form.search-aside'),
            $login_aside = $asides.filter('#login-form.login-aside'),
            $wishlist_aside = $asides.filter('.wishlist-aside'),
            $filter_container = $asides.filter('.shop-filter'),
            $size_chart_aside = $asides.filter('.size-chart-aside'),
            //Buttons
            $hamburger_menu_btn = $('.hamburger-menu-btn'),
            $cartToggleButton = $('.cart-btn'),
            $collectionToggleButton = $('.collection'),
            $filter_toggle_button = $('#shop-filter-toggle'),
            $search_button = $('.search-button'),
            $resp_nav_button = $('#rad-resp-nav-bt'),
            $wishlist_button = $header.find('.wishlist-btn'),
            $accounts_button = $('.header-account > a'),
            $size_chart_button = $('.size-chart-button');

        var close_aside = function (classTime, overlayTime, overlayClassTime ) {
            classTime = typeof classTime  === 'undefined' ? 400 : classTime;
            overlayTime = typeof overlayTime  === 'undefined' ? 400 : overlayTime;
            overlayClassTime = typeof overlayClassTime  === 'undefined' ? 1600 : overlayClassTime;

            $asides.removeClass('open');
            rad.start_scroll();
            $collection_aside.removeClass('scrollbar-active');
            $hamburger_menu_btn.add($collectionToggleButton).removeClass('active');
            $header.removeClass('aside-open');
            setTimeout(function(){
                $header.removeClass('cart-active collection-active search-active filter-active hamburger-active login-active resp-nav-active wishlist-active');
            },classTime);
            rad.hide_overlay(overlayTime,'high-zindex low-zindex',overlayClassTime);
            rad.set_menu_bg_height();
        }

        var close_other_asides = function(current_type)
        {
            var classes = 'aside-open cart-active collection-active search-active filter-active hamburger-active login-active resp-nav-active wishlist-active';
                classes = classes.replace(current_type +'-active', '');

            if (current_type == 'cart') {
                $asides.not('.wc-cart-aside').removeClass('open');
            }
            else if (current_type == 'collection') {
                $asides.not('.collection-aside').removeClass('open');
            }
            else if(current_type == 'search') {
                $asides.not('.search-aside').removeClass('open');
            }
            else if(current_type == 'filter') {
                $asides.not('.shop-filter').removeClass('open');
            }
            else if(current_type == 'login') {
                $asides.not('.login-aside').removeClass('open');
            }
            else if(current_type == 'wishlist') {
                $asides.not('.wishlist-aside').removeClass('open');
            }
            else if(current_type == 'resp-nav') {
                $asides.not('.resp-nav-aside').removeClass('open');
            }
            else if(current_type == 'size-chart') {
                $asides.not('.size-chart-aside').removeClass('open');
            }
            else {
                $asides.not('.hamburger-menu').removeClass('open');
            }

            $header.removeClass(classes);
        }

        var open_aside = function (type) {
            if(!$header.hasClass(type + '-active'))
            {
                close_other_asides(type);
            }
            
            setTimeout(function(){
                $header.addClass('aside-open');
            },450);
            
            rad.stop_scroll();

            if (type == 'cart') {
                $wc_cart_aside.addClass('open');
                rad.show_overlay(200,'high-zindex','low-zindex',0);
                $header.addClass('cart-active');
                $cartToggleButton.addClass('active');
            }
            else if (type == 'collection') {
                $collection_aside.addClass('open');
                setTimeout(function(){
                    $collection_aside.addClass('scrollbar-active');
                },1800);
                rad.show_overlay(0,'high-zindex','low-zindex',50);
                $header.addClass('collection-active');
            }
            else if(type == 'search') {
                $search_container.addClass('open');
                rad.show_overlay(0,'low-zindex','high-zindex',0);
                $header.addClass('search-active');
                rad.set_menu_bg_height($search_container.outerHeight());
            }
            else if(type == 'filter') {
                $filter_container.addClass('open');
                rad.show_overlay(0,'high-zindex','low-zindex',0);
                $header.addClass('filter-active');
            }
            else if(type == 'login') {
                $login_aside.addClass('open');
                rad.show_overlay(0,'high-zindex','low-zindex',0);
                $header.addClass('login-active');
            }
            else if(type == 'wishlist') {
                $wishlist_aside.addClass('open');
                rad.show_overlay(0,'high-zindex','low-zindex',0);
                $header.addClass('wishlist-active');
            }
            else if(type == 'resp-nav') {
                $resp_nav_aside.addClass('open');
                rad.show_overlay(0,'low-zindex','high-zindex',0);
                $header.addClass('resp-nav-active');
            }
            else if(type == 'size-chart') {
                $size_chart_aside.addClass('open');
                rad.show_overlay(200,'high-zindex','low-zindex',0);
                $size_chart_button.addClass('size-chart-active');
            }
            else {
                $hamburger_menu.addClass('open');
                rad.show_overlay(200,'high-zindex','low-zindex',0);
                $header.addClass('hamburger-active');
            }
        }

        $(document).on('click', '#overlay-layer, .aside-close',function(){
            if($header.hasClass('hamburger-active'))
            {
                close_aside(1200,1100,1600);
                return;
            }
            close_aside();
        });

        $(document).on('close_shop_filter',close_aside);

        $(document).on('open-sidebar', function(e, data){
            open_aside(data.type);
        });

        $cartToggleButton.on('click', function () {
            if ($('body').hasClass('woocommerce-cart'))
                return;
            open_aside('cart');
        });

        $hamburger_menu_btn.on('click', function () {
            open_aside('hamburger_menu');
            $(this).addClass('active');
        });

        $search_button.on('click', function () {
            open_aside('search');
            var $input = $("#search-form input[type=text]");
            if($input.length > 0)
            {
                setTimeout(function() {
                    $input[0].focus();
                },1000);
            }
        });

        $collectionToggleButton.on('click', function () {
            open_aside('collection');
            $(this).addClass('active');
        });

        $filter_toggle_button.on('click', function () {
            open_aside('filter');
            $(this).addClass('active');
        });

        $resp_nav_button.on('click', function () {
            open_aside('resp-nav');
            $(this).addClass('active');
        });

        $size_chart_button.on('click', function () {
            open_aside('size-chart');
            $(this).addClass('active');
        });

        $accounts_button.on('click', function (e) {
            e.preventDefault();
            open_aside('login');
            $(this).addClass('active');
        });

        $wishlist_button.on('click', function (e) {
            e.preventDefault();
            open_aside('wishlist');
            $(this).addClass('active');
        });
    };

    rad.toggle_aside_scrollbar = function () {
        rad.scrollbar('.toggle-aside:not(.search-aside) .sc,.toggle-aside .widget_shopping_cart_content');
        
        setTimeout(function(){
            rad.scrollbar('.wishlist-aside .shop_table');
        },100);

        //run scrollbar after updating contetn
        $('body').on( 'rad_search_ready_to_scroll', function(){
            rad.scrollbar('#search-form .sc', 'vertical');
        } );

        setTimeout(function(){
            rad.scrollbar('.shop-filter .filters', 'vertical', 50, false);
        },500);

        $('body').on( 'rad_filter_scroll', function(){
            rad.scrollbar('.shop-filter .filters', 'vertical', 50, false);
        } );

        $('body').on( 'wc_fragments_refreshed removed_from_cart', function(){
            rad.scrollbar('.toggle-aside .widget_shopping_cart_content');
        });

        $('body').on( 'added_to_wishlist removed_from_wishlist', function(){
            setTimeout(function(){
                rad.scrollbar('.wishlist-aside .shop_table');
            },50);
        });
        

    };

    /***************************************************/
    /*  Scrollbar
    /***************************************************/
    rad.scrollbar = function (element, direction , time, scrollbarHide) {
        direction = typeof direction  === 'undefined' ? 'vertical' : direction;
        time = typeof time  === 'undefined' ? 50 : time;
        scrollbarHide = typeof scrollbarHide  === 'undefined' ? true : scrollbarHide;
        var $element = $(element);

        if (!$element)
            return;
        
        setTimeout(function(){
            $element.each(function () {
                var $this = $(this),
                    $scrollContainer = $this.find('.swiper-container');

                if ($scrollContainer.length > 0) {
                    if ($scrollContainer[0].swiper != undefined) {
                        $scrollContainer[0].swiper.updateSize();
                        return;
                    }
                }

                $this.wrapInner('<div class="swiper-container sw-scrollbar"><div class="swiper-wrapper"><div class="swiper-slide"></div></div><div class="swiper-scrollbar"></div></div>');
                $scrollContainer = $this.find('.swiper-container');
                var swiper = new Swiper($scrollContainer, {
                    direction: direction,
                    slidesPerView: 'auto',                    
                    freeMode: true,
                    scrollbar : {
                        el : $scrollContainer.find('.swiper-scrollbar'),
                        hiide: scrollbarHide,
                        snapOnRelease : true,
                        draggable: true,
                    },
                    mousewheel : {
                        sensitivity: 0.6,
                        releaseOnEdges : false,
                    }
                });
            });
        },time);
    };

    /**************************************************
    /* slideshow
    **************************************************/
    rad.slideshow_block = function () {
        var $slideshow_blocks = $('.slideshow-block');

        if ($slideshow_blocks.length <= 0)
            return;

        $slideshow_blocks.find('.sl-items li').on('mouseover click',function(){
            var $this = $(this),
                id = $this.data('id');

            $this.siblings('li').removeClass('active');
            $this.addClass('active');
            $('#'+id).siblings('.slideshow-item').removeClass('active').addClass('go-out');
            $('#'+id).removeClass('go-out').addClass('active');
        });

        $slideshow_blocks.each(function(){
            var $slideshow = $(this);
            $slideshow.find('.sl-items  li').eq(0).trigger('mouseover')
        });

    };

    /**************************************************
    /* Reveal slideshow
    **************************************************/
    rad.reveal_slideshow_block = function () {
        var $slideshow = $('.reveal-slideshow-block');

        if ($slideshow.length <= 0)
            return;

        $slideshow.on('click',function(){
            var $this = $(this),
                $sl_items = $this.find('.rsl-images'),
                $current = $sl_items.find('.slideshow-item.active'),
                $next     = $current.next('.slideshow-item'),
                num = 1;

            if($this.hasClass('in-transition'))
            {
                return;
            }
            else
            {
                $this.addClass('in-transition');
                setTimeout(function(){
                    $this.removeClass('in-transition');
                },1300);
            }

            if($next.length <= 0)
            {
                $next = $sl_items.find('.slideshow-item').eq(0);
            }
            num = $next.attr('data-item');
            $next.siblings('.slideshow-item').removeClass('active').addClass('go-out');
            $next.removeClass('go-out').addClass('active');
            $this.find('.current').html(num);
        });

        rad.$window.on('scroll', function(){
            $slideshow.find('.rad-rsls-cursor').removeClass('is-active');
        });
        

    };

    /**************************************************
    /*  parallax  
    **************************************************/
    rad.scatter_parallax_init = function () {

        if ( $('.parallax').length <= 0 || rad.msie > 0 || !!rad.msie11 || rad.w_width <= 1140 || rad.is_touch_device)
            return;

        $('.product.parallax').each(function (index) {
            var $el = $(this);

            if(index == 1 || index == 2 || (index%4) == 1 || (index%4) == 2)
            {
                $el.attr('data-speed',".4");
            }
            else
            {
                $el.attr('data-speed',".1");
            }
        });
    };

    /**************************************************
    /*  parallax  
    **************************************************/
    rad.scroll_parallax_init = function () {

        if ( $('.parallax').length <= 0 || rad.msie > 0 || !!rad.msie11 || rad.is_mobile_or_tablet || rad.is_touch_device)
            return;

        var $parallaxContainers = $('.parallax'),
            scrollPosition = 0,
            tick = false,
            parallax_handler = function () {
            $parallaxContainers.each(function () {
                var $el = $(this),
                    speed = $el.attr('data-speed') ? parseFloat($el.attr('data-speed')) : 27,
                    is_img_parallax = $el.attr('data-img-parllax') ? ($el.attr('data-img-parllax') == 'true') : false,
                    elementHeight = $el.outerHeight(),
                    elementTop = $el.offset().top,
                    elementBottom = elementTop + elementHeight,
                    factorMult = 100;

                    //When element is out of viewport
                    if (elementTop > (scrollPosition + rad.w_height) || elementBottom < scrollPosition)
                        return;

                if(is_img_parallax)
                {

                    factorMult = ((scrollPosition - elementTop) / rad.w_height) * speed;
                    $el.find(".prlx-target").css({
                        'transform': 'scale(1.4) translate3d(0,' + factorMult + '%,0)'
                    });
                }
                else
                {

                    var hiddenBefore = elementBottom - scrollPosition,
                        factorMult = 0;

                    if (hiddenBefore > 0) {
                        factorMult = (hiddenBefore * 100) / rad.w_height;
                    }

                    factorMult = factorMult * speed;
                    
                    $el.find(".prlx-target").css({
                        'transform': 'translate3d(0,' + factorMult + '%,0)'
                    });
                }

            });
            tick = false;
        }

        var requestTick  = function () {
            if (!tick) {
                window.requestAnimationFrame(parallax_handler);
                tick = true;
            }
        }

        var onScroll = function () {
            scrollPosition = window.scrollY;
            requestTick();
        }
        onScroll();
        rad.$window.on('scroll', onScroll).on('resize', onScroll);
    };

    /**************************************************
    /* Mouse parallax
    **************************************************/
    rad.mouse_parallax_init = function () {
        if ($('.mouse-parallax').length <= 0)
            return;

        rad.mouse_parallax($('.mouse-parallax .section-container'), { sensitivity: 100, duration: 8000, zoom: false, initialZoom : true });
    };

    //Parallax by mouse position
    rad.mouse_parallax = function ($elements, options) {

        if (rad.w_width <= 1140 || rad.is_touch_device)
            return;

        var transform = function ($target, x, y, scaleRatio) {
                $target.css('transform', 'matrix(1, 0, 0,1,' + x + ',' + y + ') scale(' + scaleRatio +',' + scaleRatio +')');
        }

        var transformLeave = function ($target, x, y, scaleRatio) {
            $target.css('transform', 'matrix(1, 0, 0,1,' + x + ',' + y + ') scale(' + scaleRatio + ',' + scaleRatio + ')');
        }

        return $elements.each(function () {

            var settings = $.extend({
                target: '> .mouse-parallax-img img',
                sensitivity: 20,
                duration: 1400,//ms
                zoom: true,
                initialZoom : false,
            }, options);

            var el = $(this);
            //Prevent from multiple running
            if (el.find(settings.target).length === 0 || el.hasClass('mouse-parallax-active')) {
                return true;
            }

            var target = el.find(settings.target),
                h, w, width, cx, x, y, scaleRatio = 1;

            //set different transition duration for element
            if (settings.duration != 1400) {
                target.css('transition-duration', settings.duration + 'ms');
            }

            el.addClass('mouse-parallax-active');
            el.on('mouseenter mouse_parallax_init', function (e) {
                if (w !== el.width()) {
                    w = el.width();
                    h = el.height();
                    cx = settings.sensitivity / w;

                    if(settings.zoom || settings.initialZoom)
                    {
                        scaleRatio = (w + settings.sensitivity) / w;
                    }

                    //set initial scale
                    if (settings.initialZoom) {
                        target.css('transform', 'scale(' + scaleRatio + ',' + scaleRatio + ')');
                    }
                }
            }).on('mousemove', function (e) {
                x = (-cx * (e.pageX - (target.offset().left + w / 2)));
                y = (-cx * (e.pageY - (target.offset().top + h / 2)));
                transform(target, x, y, scaleRatio);
            }).on('mouseleave', function (e) {
                if(settings.initialZoom)
                {
                    transformLeave(target, 0, 0,scaleRatio);
                }
                else
                {
                    transformLeave(target, 0, 0,1);
                }
                
            });

            if (settings.initialZoom) {
                el.trigger('mouse_parallax_init');
            }
        });
    };

    /**************************************************
    /*  Comment Respond
    **************************************************/

    rad.comment_respond = function () {

        var $respond = $('#respond'), $respondWrap = $('#respond-wrap'),
            $cancelCommentReply = $respond.find('#cancel-comment-reply-link'),
            $commentParent = $respond.find('input[name="comment_parent"]');

        $('.comment-reply-link').each(function () {
            var $this = $(this),
                $parent = $this.parents().eq(2);

            $this.click(function () {
                var commId = $this.parents('.comment').attr('data-id');

                $commentParent.val(commId);
                $respond.insertAfter($parent);
                $cancelCommentReply.show();

                return false;
            });
        });

        $cancelCommentReply.click(function (e) {
            e.preventDefault();

            $cancelCommentReply.hide();

            $respond.appendTo($respondWrap);
            $commentParent.val(0);
        });
    };

    /**************************************************
    /*  Scrolling function 
    **************************************************/
    rad.scroll_to = function (location, time, offset) {
        time = typeof time  === 'undefined' ? 500 : time;
        offset = typeof offset  === 'undefined' ? 0 : offset;

        var top_distance = 0,
            $location = $(location);

        if ($location.length <= 0)
            return;

        top_distance = $location.offset().top - offset;
        top_distance = (top_distance > 0 ) ? top_distance : 0;

        time = ((typeof time !== 'undefined') ? time : parseInt(rad.data.scroling_speed));

        $("html, body").animate(
            {
                scrollTop: top_distance
            },
            {
                duration: time,
                easing: 'easeInOutCirc',
                queue: false
            }
        );
    };

    /**************************************************
    /*  fitvid 
    **************************************************/

    rad.fit_videos = function () {
        $("#rad-wrapper").fitVids();
    }

    /**************************************************
    /*  Grid Animation 
    **************************************************/
    rad.animationDelay = function (counter) {
        var base_delay = 0.15;
        return base_delay * counter;
    };
    /* cart blog */
    rad.isotopeAnimation = function ($container) {
        var self = this,
            $this = $container,
            counter = 0,
            $selector;

        if((rad.is_mobile || rad.is_tablet) && $container.hasClass('no-resp-anim'))
            return;

        $container.find('.isotope-item').not('.isotope-hidden').find('.rad-post-wrap').not('.animated').waypoint({
            handler : function () {
                var $this = $(this.element);
                $this.each(function () {
                    var $item = $(this);
                    setTimeout(function () {
                        //Ask self.animationDelay() for the amount of delay per each item
                        var delay = rad.animationDelay(counter);

                        $item.css({ 'transition-delay': delay + 's' });
                        $item.addClass('animated');
                        
                        counter += 1;//Reset counter per each iteration.

                    }, 50);
                    counter = 0;
                });
                this.destroy();
            },
            offset: '90%'
        });
    };

    // products and Carousel ( image carousel , Products carousel )
    rad.showAnimation = function ($container, type) {
        
        if(!$container.hasClass('elem-grid-anim') && !$container.hasClass('img-anim'))
            return;

        if((rad.is_mobile || rad.is_tablet) && $container.hasClass('no-resp-anim'))
        {
            return;
        }

        var self = this,
            counter = 0,
            $carouselItem,
            $duplicateSlider;

        $container.find('.product-wrap , .swiper-slide').addClass('target-anim');
        $container.find('.swiper-slide-duplicate.target-anim').css({ 'transition-delay': '0s' }).addClass('animated');

        var showAnimationBase = function (that) {

            var $that = $(that);

            $that.each(function () {
                setTimeout(function () {
                    var delay = counter * 0.2;

                    $that.css({ 'transition-delay': delay + 's' });
                    $that.addClass('animated');

                    counter = counter + 1;

                }, 50);

                counter = 0;//Reset counter after each iteration

            });
        }


        if (type == 'carousel') { //this code For carousel

            $carouselItem = $container.find('li.product');

            if (!$carouselItem.hasClass('swiper-slide-visible')) {
                return 0;
            }

            $container.find('.swiper-slide-visible .product-wrap:not(.animated)').waypoint({
                handler : function () {
                    var $item = $(this.element);
                    $container = $item.parents('.woocommerce.wc-shortcode');

                    showAnimationBase($item);
                    this.destroy();
                },
                offset: '95%'
            });

        } else if (type == 'image-carousel') { // For Image Carousel 

            $carouselItem = $container.find('div.swiper-slide');

            if (!$carouselItem.hasClass('swiper-slide-visible')) {
                return 0;
            }

            $container.find('.swiper-slide-visible:not(.animated)').waypoint({
                handler : function () {
                    var $item = $(this.element);
                    $container = $item.parents('.carousel');

                    //load animation on slide and its duplicate slide
                    showAnimationBase($item);
                    this.destroy();
                },
                offset: '95%'
            });

        } else if (type == 'grid') {

            $container.find('.product-wrap:not(.animated)').waypoint({
                handler : function () {
                    var $item = $(this.element);
                    showAnimationBase($item);
                    this.destroy();
                },
                offset: '95%'
            });
        }
    };

    /**************************************************
    /*  Lazy loading images 
    **************************************************/
    rad.lazy_on_load = function (that) {

        var $lazyLoadCntainers = $(that).find('.lazy-load-on-load');

        if ($lazyLoadCntainers.length > 0) {
            $lazyLoadCntainers.each(function () {
                var $this = $(this);

                if (!$this.hasClass('lazy-loaded') && !$this.hasClass('fetching')) {
                    $this.addClass('fetching');
                    var $img, src;

                    if ($this.hasClass('bg-lazy-load')) {
                        src = $this.data('src');

                    }
                    else {
                        $img = $this.find('img');
                        src = $img.data('src');
                    }

                    var img = new Image();

                    img.onload = function () {
                        if ($this.hasClass('bg-lazy-load'))
                            $this.css('background-image', 'url(' + src + ')').removeAttr('data-src');
                        else
                            $img.attr('src', src).removeAttr('data-src');

                        setTimeout(function () {
                            $this.addClass('lazy-loaded');
                        }, 100);
                    }

                    img.src = src;
                }
            })

        }
    };

    rad.lazy_load_on_hover = function () {

        if (rad.is_touch_device)
            return;

        var $items = $('.lazy-load-hover-container');

        $items.on('mouseenter', function () {
            var $this = $(this).find('.lazy-load-hover');
            if ($this.length > 0) {
                if (!$this.hasClass('lazy-loaded') && !$this.hasClass('fetching')) {
                    $this.addClass('fetching');
                    $this.closest('.lazy-load-hover-container').addClass('fetching');

                    var $img,
                        src,
                        img = new Image();

                    if ($this.hasClass('bg-lazy-load')) {
                        src = $this.data('src');
                    }
                    else {
                        $img = $this.find('img');
                        src = $img.data('src');
                    }

                    img.onload = function () {
                        if ($this.hasClass('bg-lazy-load'))
                            $this.css('background', 'url(' + src + ')').removeAttr('data-src', '');
                        else
                            $img.attr('src', src).removeAttr('data-src', '');

                        $this.closest('.lazy-load-hover-container').removeClass('fetching');

                        setTimeout(function () {
                            $this.addClass('lazy-loaded');
                        }, 100);
                    }

                    img.src = src;
                }
            }
        })
    };

    rad.abortImageLoading = function() {
        $('.lazy-load.fetching:not(.lazy-loaded) img').attr('src','');
    };
    /**************************************************
    /*  products isotope  
    **************************************************/

    rad.shop_grid_animation = function ($mainContainer) {

        if ($mainContainer === undefined)
            $mainContainer = $('body');

        $mainContainer.find('.products.shop-grid').each(function () {
            rad.showAnimation($(this),'grid');
        });
    };

    rad.products_layout = function() {
        $('.products.shop-grid').each(function () {
            var $grid = $(this),
            is_sticky = false;

            if($grid.hasClass('masonry-g'))
            {
                return true;
            }

            if($grid.hasClass('sticky-layout') && !rad.is_mobile_or_tablet)
            {
                is_sticky = true;
            }
            setTimeout(function(){
                var maxHeight = Math.max.apply(null, $grid.find("li.product").map(function (index)
                {
                    $(this).css('min-height', '');
                    if(is_sticky && index == 0)
                    {
                        return 1;//a minimum value
                    }
                    return $(this).outerHeight();
                }));

                $grid.find("li.product").css('min-height',maxHeight + 'px');
            },100);
        });
    }

    rad.sticky_products_layout = function() {

        if($('.shop-grid.sticky-layout').length <= 0 || rad.is_mobile)
            return;

        $('.shop-grid.sticky-layout').each(function(){
            var $grid = $(this),
                $target = $grid.find('.product').eq(0),
                target_height = $target.outerHeight();
                $grid.css('min-height',target_height);

            var scrolling_element_height = $grid.outerHeight(),
                scrolling_top_distance = $grid.offset().top,
                target_pos = {
                    'fxd_left' :$target.offset().left,
                },

                fixed_range = {
                    'start' : scrolling_top_distance,
                    'end' : scrolling_top_distance + scrolling_element_height - Math.max(rad.w_height,target_height)
                };
            

            if($target.length <= 0 || scrolling_element_height <= rad.w_height)
                return;

            $target.css('width',$target.outerWidth());
            
            var left_value = 0;
            if($grid.hasClass('two-unit-gutter'))
            {
                left_value = -10;
            }

            rad.$window.on('scroll',function(){
                var scrolltop = rad.$window.scrollTop();
                if (scrolltop <= fixed_range['start'])
                {
                    $target.css({
                        position: 'absolute',
                        top: 0,
                        left: left_value,
                    });
                }
                else if ( scrolltop > fixed_range['start'] && scrolltop < fixed_range['end']) {
                    $target.css({
                        position: 'fixed',
                        top: 0,
                        left:target_pos['fxd_left']
                    });  
                } else {
                    $target.css({
                        position: 'absolute',
                        top: scrolling_element_height - target_height,
                        left:left_value
                    });
                }
            });
        });
    }

    /**************************************************
    /*  special blocks
    **************************************************/
    rad.blocks = function (tab_container) {
        tab_container = typeof tab_container  === 'undefined' ? false : tab_container;

        rad.chart();
        rad.countdown();
        rad.counter_block();

        rad.toggle();
        rad.progressbar();
        rad.custom_heading_block();

        if (tab_container == false) { // prevent to running multiple times in tab/tour/accordian
            rad.tabs_tour_accordion();
            rad.pagable_container();
        }

    };

    /**************************************************
    /*  mediaelementplayer ( Html Video )
    **************************************************/
    rad.video_bg = function () {


        if (typeof $.fn.mediaelementplayer == 'function') {
            $('.video').mediaelementplayer({
                enableKeyboard: false,
                iPadUseNativeControls: false,
                pauseOtherPlayers: false,
                iPhoneUseNativeControls: false,
                AndroidUseNativeControls: false,
                features: ['playpause', 'progress', 'current', 'duration', 'tracks', 'volume', 'fullscreen'],
                success : function (mediaElement, domObject) {
                    // fade in play buttons and poster image In Video Html 5 inline 
                    $('.mejs-poster').addClass('fadeIn');
                    var attr = $(domObject).attr('autoplay');
                    if (typeof attr !== typeof undefined && attr !== false) {
                        $(domObject).parents('.mejs-inner').find('.mejs-playpause-button button').trigger('click');
                    }
                },
            });

            //mobile check
            if (navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)) {
                rad.video_bg_size();
                $('.videoHomePreload').show();
                $('.videoWrap').remove();
            }

            // append play button In poster image wrap ( for inline Video ) - we need set this div In this Position For hidding Play buttons when click On video
            var $play_button = $('.inline_video.video_embed_container .play-button');
            $('.inline_video.video_embed_container .play-button').remove();

            var $mejs_poster = $('.mejs-poster');
            $play_button.appendTo($mejs_poster);
        }
    };
    
    /**************************************************
    /*  light galley for video
    **************************************************/
    rad.embed_video = function () {

        $('.video_embed_container').each(function (i) {

            var $this = $(this);

            var $video_embed_id = $this.attr('id');
            if (typeof $.fn.lightGallery == 'function') {
                $this.not('.inline_video').lightGallery({
                    counter: false,
                    addClass: 'videoPopUp',
                    galleryId: $video_embed_id,
                    backdropDuration : 900
                });
            }
        });
    };

    /**************************************************
    /*  light galley Carousel
    **************************************************/
    rad.carousel_gallery = function () {

        if (typeof $.fn.lightGallery !== 'function' || $('.carousel_gallery').length <= 0)
            return;

        var $carousel_gallery = $('.carousel_gallery');
        $carousel_gallery.lightGallery({
            thumbnail: true,
            selector: '.galleryCarouselLink',
        });

    };

    /**************************************************
    /*  Video background size
    **************************************************/
    rad.video_bg_size = function () {

        if(rad.is_mobile_or_tablet)
            return;

        $('.videoWrap').each(function (i) {

            var $sectionWidth = $(this).closest('.videoHome ').outerWidth();
            var $vcVideoWrap = $(this).parents('.vc_videowrap');

            if ($vcVideoWrap.length) {

                var $sectionHeight = $vcVideoWrap.find('.vc_videocontent').outerHeight();

                $(this).width($sectionWidth);
                $vcVideoWrap.height($sectionHeight);

            } else {

                var $sectionHeight = $(this).closest('.videoHome').outerHeight();
                $(this).width($sectionWidth);
                $(this).height($sectionHeight);

            }

            // calculate scale ratio
            var videoWidthOriginal = 1280,  // original video dimensions
            videoHeightOriginal = 720,
            vidRatio = 1280 / 720,
            scale_h = $sectionWidth / videoWidthOriginal,
            scale_v = ($sectionHeight) / videoHeightOriginal,
            scale = scale_h > scale_v ? scale_h : scale_v;

            // limit minimum width
            var minVideoWidth = vidRatio * ($sectionHeight + 20);

            if (scale * videoWidthOriginal < minVideoWidth) { scale = minVideoWidth / videoWidthOriginal; }

            $(this).find('video').width(Math.ceil(scale * videoWidthOriginal + 2));
            $(this).find('video').height(Math.ceil(scale * videoHeightOriginal + 2));

            $(this).scrollLeft(($(this).find('video').width() - $sectionWidth) / 2);
            $(this).find('.mejs-overlay, .mejs-poster').scrollTop(($(this).find('video').height() - ($sectionHeight)) / 2);
            $(this).scrollTop(($(this).find('video').height() - ($sectionHeight)) / 2);

        });

    };

    /**************************************************
    /*  social share's pop up 
    **************************************************/
    rad.responsive_product_social_share = function () {
        if(!rad.is_mobile_or_vertical_tablet || !$('body').hasClass('single-product'))
            return;

        $(".product #social-share").removeClass('vertical').insertAfter('.summary');
    };

    /**************************************************
    /*  social share's pop up 
    **************************************************/
    rad.social_share_pop_up = function () {

        $(".social-icons.share a").click(function (e) {
            e.preventDefault();

            var url = $(this).attr('href'),
                title = $(this).attr('title'),
                new_window = window.open(url, title, 'height=300,width=600');

            if (window.focus) {
                new_window.focus();
            }
            return false;
        });
    };

    /**************************************************
    /*   Custom title
    **************************************************/
    rad.custom_heading_block = function () {

        if ($('.custom-heading-block').length <= 0 || rad.msie > 0 || !!rad.msie11 || rad.w_width <= 1140 || rad.is_touch_device)
            return;

        var $titles = $('.custom-heading-block'),
            scrollPosition = 0;

        var parallax_handler  = function () {
            $titles.each(function () {
                var $el = $(this),
                    elementTop = $el.data('offsetTop'),
                    factorMult = 0,
                    offsetDiff = elementTop - scrollPosition;

                factorMult = 1 - ((((rad.w_height / 3) - offsetDiff) / (rad.w_height / 3)) * 1.1);

                if (offsetDiff < (rad.w_height / 3) && factorMult >= 0 && factorMult <= 1) {
                    $el.css({ 'opacity': factorMult });
                }
            });
        }

        var parallax_init  = function () {
            $titles.each(function () {
                var $el = $(this);
                if ($el.find('.title').length) {
                    $el.data('offsetTop', $el.find('.title').offset().top);
                }
            });
        }

        var requestTick  = function () {
            parallax_init();
            scrollPosition = rad.$window.scrollTop();
            window.requestAnimationFrame(parallax_handler);
        }

        var resizeHandler  = function () {
            parallax_init();
        }

        parallax_init();
        parallax_handler();

        rad.$window.on('scroll', requestTick).resize(resizeHandler);

    };

    /**************************************************
    /*   Workaround for double tap issue on IOS
    **************************************************/
    rad.ios_double_tap = function () {
        if (!navigator.platform.match(/(iPhone|iPod|iPad)/i))
            return;

        var $elements = $('.buttons,.rad-carousel-prev,.rad-carousel-next');
        $elements = $elements.add('#rad-resp-nav-bt,.cart-btn,.hamburger-menu-btn,.aside-close,#overlay-layer, .rad-post-inner .play-button');
        $elements = $elements.add('.readmore .loadMore, .woocommerce ul.products li.product .product-buttons > span a');
        $elements.on('touchstart mouseenter focus', function (e) {
            if (e.type == 'touchstart') {
                e.stopImmediatePropagation();
            }
        });
    };

    /**************************************************
    /*   preloader
    **************************************************/
    rad.preloader_hide = function () {
        if($("#preloader").length <= 0)
        {
            $('body').addClass('content-loaded');
            return;
        }

        setTimeout(function () {
            $('body').addClass('content-loaded');
        }, 500);

        $("#preloader").addClass('hide');

        setTimeout(function () {
            $("#preloader").css({ 'display': 'none' });
        }, 1000);

    };

    /**************************************************
    /*   Close button for WC notices
    **************************************************/
    rad.wc_notice_close = function () {

        $('.woocommerce-notices-wrapper .close').on('click',function(){
            $(this).siblings('.woocommerce-info, .woocommerce-message, .woocommerce-error').addClass('wc-notice-hide');
        });
    };

    /**************************************************
    /*   Ajax Search form
    **************************************************/
    rad.ajax_search_form = function () {
        var xhr = null,
            $search_form = $('#search-form'),
            $input = $search_form.find('.search-input');

        $('.go-to-search').on('click', function() {
            $search_form.find('form').submit();
        });

        $('.reset-search').on('click', function() {
            $input.val('').trigger('keyup');
            setTimeout(function(){
                rad.set_menu_bg_height($('#search-form').height());
            },250);
        });

        $search_form.find('ul li').on('click', function() {
            var $this = $(this);
            $search_form.find('input[name="cat"]').val($this.data('slug'));
            $this.siblings('li').removeClass('selected');
            $this.addClass('selected');

        });

        $input.on('keyup', function () {
            if (xhr) {
                xhr.abort();
            }

            var value = $(this).val(),
                cat = $(this).siblings('input[name="cat"]').val(),
                $searchResults = $('.searchResults');

            if (value.length <= 2) {
                if (xhr) {
                    xhr.abort();
                }
                $search_form.removeClass('fetching show-results no-result');
                return;
            }

            rad.stop_scroll();

            $search_form.addClass('fetching').removeClass('show-results no-result');


        
            var ajaxurl = '',
                send_data = {
                    s: value,
                    cat: cat
                };

            // Use new WooCommerce endpoint URL if available
            if (typeof wc_add_to_cart_params !== 'undefined') {
                ajaxurl = wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'rad_ajax_search_action'); // WooCommerce Ajax endpoint URL (available since 2.4)
            } else {
                ajaxurl = rad.data.ajax_url;
                send_data['action'] = 'rad_ajax_search_action';
            }

            xhr = $.ajax({
                url: ajaxurl,
                type: 'GET',
                dataType: 'html',
                data: send_data
            }).done(function (response) {
                var $response = $(response),
                    count = $response.filter('.search-item').length;
                if(count >= 0 )
                {
                    $search_form.find('.result-count span').html(count);
                }

                $('.results').html('').append($response);
                $search_form.addClass('show-results').removeClass('fetching');
                if($response.hasClass('no-result'))
                {
                    $search_form.addClass('show-no-results');
                }
                
                setTimeout(function(){
                    rad.set_menu_bg_height($('#search-form').height());
                    $(document.body).trigger('rad_search_ready_to_scroll');
                },150);
                
            })
            .fail(function (response) {
                console.log("error");
                console.log(response);
            });
        });
    };

    /**************************************************
    /*  Menu states
    **************************************************/
    rad.mobile_menu_states = function () {
        
        if (!rad.is_mobile || !$('body').hasClass('logged-in') || !$('body').hasClass('admin-bar') || $("#rad-menu").length <= 0)
            return;

        var $menu = $("#rad-menu"),
            $asides = $('.toggle-aside'),
            lastScrollY = 0,
            tick        = false;

        var update_menu_state  = function () {
            if (46 >= lastScrollY) {
                $menu.css('margin-top','-'+lastScrollY+'px');
                $asides.css('margin-top', (46 - lastScrollY)+'px');
            }
            else {
                $menu.css('margin-top','-46px');
                $asides.css('margin-top','0px');
            }

            tick = false;
        }

        var requestTick  = function () {
            if (!tick) {
                window.requestAnimationFrame(update_menu_state);
                tick = true;
            }
        }

        var onScroll = function () {
            lastScrollY = window.scrollY;
            requestTick();
        }

        rad.$window.on('scroll', onScroll);
        onScroll();

    };
    /**************************************************
    /*  Menu states
    **************************************************/
    rad.menu_states = function () {

        var $menu = $("#rad-menu"),
            is_single_state = $menu.hasClass("single-state");

        if (rad.is_mobile_or_tablet || is_single_state)
        {
            if (rad.is_mobile_or_tablet)
            {
                $menu.addClass('state2');
            }
            
            return;            
        }

        var latestKnownScrollPosition = 0,
            tick = false,
            changeStateThreshold = 100,
            menuHeight = $menu.outerHeight();

        if($('#header').length > 0)
        {
            changeStateThreshold = $('#header').outerHeight() - menuHeight;
        }

        var update_menu_state  = function () {

            if (changeStateThreshold > latestKnownScrollPosition) {
                $menu.removeClass('state2');
            }
            else {
                $menu.addClass('state2');
            }

            tick = false;
        }

        var requestTick  = function () {
            if (tick == false) {
                window.requestAnimationFrame(update_menu_state);
                latestKnownScrollPosition = window.scrollY;
            }
            tick = true;
        }

        rad.$window.on('scroll', requestTick);
        requestTick();

    };

    /**************************************************
    /*  Update woocommerce content by ajax
    **************************************************/
    rad.woocommerce_filter = function () {

        var $filters = $('.shop-filter'),
            filter_width = 0,
            filter_height = 0;

        if(rad.is_mobile_or_tablet)
        {
            $filters.find('.filters').prepend($('#woocommerce-sidebar .sidebar'));
            if(rad.is_tablet)
            {
                setTimeout(function(){
                    $filters.find('.sidebar').each(function(index) {
                        filter_width += parseInt($(this).width(), 10);
                    });
                    filter_width += 52;
                    $filters.css({'width': filter_width + 'px'});         
                },300);

            }

            setTimeout(function(){
                filter_height = $filters.find('.filters').outerHeight(true);
                $filters.css({'max-height' : filter_height + 'px'});
            },600);
            setTimeout(function(){
                $('body').trigger('rad_filter_scroll');
            },700);
        }
        else
        {

            $filters.find('.sidebar').each(function(index) {
                filter_width += parseInt($(this).width(), 10);
            });

            filter_width += 52;

            $filters.css({'width': filter_width + 'px'});
            setTimeout(function(){
                filter_height = $filters.find('.filters').outerHeight(true);
                $filters.css({'max-height' : filter_height + 'px'});
                if(filter_height > (rad.w_height - 40))
                {
                    $filters.find('.filters').addClass('overflowed');
                }
            },600);

            if($('#shop-sticky-filter').length > 0)
            {
                var $sticky_filter = $('#shop-sticky-filter'),
                latestKnownScrollPosition = 0,
                tick = false,
                element_treshold = $('.wc-ajax-wrapper').offset().top,
                element_width = $('.wc-ajax-wrapper').outerWidth(),
                right_dis = (rad.w_width - element_width)/2;
                rad.shop_height = $('.wc-ajax-wrapper').height();

                if(right_dis <= 0)
                {
                    right_dis = 50;
                    $sticky_filter.addClass("go-above")
                }

                
                $sticky_filter.css("right",right_dis);

                $sticky_filter.on("click",function(){
                    $('#shop-filter-toggle').trigger("click");
                });

                $(document).on("update_shop_height",function(){
                    rad.shop_height = $('.wc-ajax-wrapper').height();
                });

                var update_sticky_filter_position  = function () {
                    if (latestKnownScrollPosition > element_treshold && latestKnownScrollPosition < (element_treshold + rad.shop_height - (rad.w_height/1.5))  ) {
                        $sticky_filter.addClass('show');
                    }
                    else {
                        $sticky_filter.removeClass("show");
                    }
                    tick = false;
                }

                update_sticky_filter_position();

                var requestTick  = function () {
                    if (tick == false) {
                        window.requestAnimationFrame(update_sticky_filter_position);
                    }
                    tick = true;
                }

                var onScroll  = function () {
                    latestKnownScrollPosition = rad.$window.scrollTop();
                    requestTick();
                }
                rad.$window.on('scroll', onScroll);
            }
            
        }
    };

    rad.go_to_top_shop = function () {
       var self = this;
       setTimeout(function () {
           rad.scroll_to('.shop_top_padding', 400, 250);
       }, 500)

    };

    /**************************************************
    /*  Woocommerce column view switcher
    **************************************************/
    //Activate tag on page refresh
    rad.woocommerce_column_switcher = function () {
        if(!rad.active_wc)
            return;
            
        $('.column-switcher a').on('click',function(e){
            e.preventDefault();

            var $this = $(this),
                column = $this.data('column'),
                $product_grid = $('.woocommerce ul.products');

            if($this.hasClass('current'))
                return false;

            $this.siblings().removeClass('current');
            $this.addClass('current');
            rad.show_wrapper_loading();

            setTimeout(function(){
                $product_grid.removeClass('shop-2column shop-3column shop-4column shop-5column shop-6column').addClass('shop-' + column +'column');  
                rad.shop_grid_animation();
                rad.hide_wrapper_loading();
                rad.products_layout();
            },600);
        });
    };

    rad.apply_wc_column_switch = function($content) {
        if($('.column-switcher').length <= 0)
            return $content;

        var column = $('.column-switcher a.current').data('column');
        $content.find('ul.products').removeClass('shop-2column shop-3column shop-4column shop-5column shop-6column').addClass('shop-' + column +'column');  
        return $content;
    }
    /**************************************************
    /*  reinit price filter on price slider widget  - it's a copy of WC init_price_filter() function
    **************************************************/
    rad.reinit_price_filter = function() {
        $( 'input#min_price, input#max_price' ).hide();
        $( '.price_slider, .price_label' ).show();

        var min_price         = $( '.price_slider_amount #min_price' ).data( 'min' ),
            max_price         = $( '.price_slider_amount #max_price' ).data( 'max' ),
            step              = $( '.price_slider_amount' ).data( 'step' ) || 1,
            current_min_price = $( '.price_slider_amount #min_price' ).val(),
            current_max_price = $( '.price_slider_amount #max_price' ).val();

        if ( typeof $.fn.slider === 'undefined' || !$.isFunction($.fn.slider) )
            return;

        $( '.price_slider:not(.ui-slider)' ).slider({
            range: true,
            animate: true,
            min: min_price,
            max: max_price,
            step: step,
            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] ] );
            }
        });
    }


    /**************************************************
    /*  Update woocommerce content by ajax
    **************************************************/
    //Activate WC tags on page refresh
    rad.woocommerce_active_tag = function () {
        var url = window.location.href;
        $('.widget.woocommerce.widget_product_tag_cloud a[href="' + url + '"]').addClass('current-cat');

    };

    rad.hide_wrapper_loading  = function () {
        $('.wc-ajax-content').css('opacity', 1);
        $('.wc-ajax-wrapper > .wc-loading').addClass('hide');
        setTimeout(function(){
            $('.shop-filter').removeClass('loading');
            $('.shop-filter .wc-loading').addClass('hide');
        },300);
    }

    rad.show_wrapper_loading  = function () {
        $('.wc-ajax-content').css('opacity', 0);
        $('.wc-ajax-wrapper > .wc-loading').removeClass('hide');
        $('.shop-filter').addClass('loading');
        $('.shop-filter .wc-loading').removeClass('hide');
    }

    rad.woocommerce_ajax_wrapper = function () {

        if (!rad.active_wc || $('body').hasClass('single-product'))
            return;

        var is_active_ajax_request  = function () {
            if (xhr && xhr.readyState != 4)
                return true;

            return false;
        }

        var update_widgets = function ($response) {

            //Update search form
            var form = $response.find('form.woocommerce-product-search');
            $('form.woocommerce-product-search').attr('data-type', form.attr('data-type')).attr('action', form.attr('action'));
            
            var $shop_filter = $response.find('.shop-filter'),
                $result_count = $response.find('p.woocommerce-result-count'),
                $res_ordering = $response.find('.woocommerce-ordering select'),
                $res_shop_filters = $shop_filter.find('.filters'),
                $res_shop_cats = $response.find('#rad-shop-cats ul'),
                $res_shop_sidebar = $response.find('#woocommerce-sidebar');
            
            //Wait .2s to complete animations
            setTimeout(function () {                
                if($res_shop_cats.length > 0 )
                {
                    $('#rad-shop-cats ul').html($res_shop_cats.html());
                }
                
                $('.shop-filter .filters').html($res_shop_filters.html());

                $('#woocommerce-sidebar').html($res_shop_sidebar.html());

                $('.woocommerce-result-count').html($result_count.html());

                $('.woocommerce-ordering select').html($res_ordering.html());

                rad.woocommerce_filter();

                setTimeout(function () {
                    rad.reinit_price_filter();
                    
                    rad.init_niceselect('update');
                    rad.layer_nav_ajax_dropdown();
                    rad.cat_widget();
                }, 100 );
            }, 200);

        }

        var update_content = function ($response, categoryChanged) {
            var $new_block = $response.find('.wc-ajax-content'),
                $new_category_header = $response.filter('#header'),
                $current_category_header = $('#header'),
                $new_top_space_classes = $response.find('#rad-wrapper').attr("class"); // get new top space classes 

            if ($new_block.length > 0) {
                $('.wc-ajax-content').html($new_block.html());
            }
            else {
                $new_block = $response.find('.woocommerce-info').addClass('no-match');
                $('.wc-ajax-content').html($new_block);
            }
            

            //update category header and top space classes
            if(categoryChanged) {
                if ($new_category_header.length > 0) {
                    if ( $current_category_header.length > 0 ) {
                        
                        $current_category_header.after($new_category_header.addClass('hide hide-cat'));
                        //wait a bit to add content to DOM completely

                        setTimeout(function () {
                            $new_category_header.removeClass('hide');
                        }, 100);
                        //wait a bit to animate completely
                        setTimeout(function () {
                            $current_category_header.remove();
                        }, 400);

                        setTimeout(function () {
                            rad.wc_header_categories();
                            $new_category_header.removeClass('hide-cat');
                        }, 500);
                        
                    }
                    else {
                        if($('#slider').length <= 0)
                        {
                            $('#rad-wrapper').prepend($new_category_header.addClass('hideCompletly'));
                            //wait a bit to add content to DOM completely
                            setTimeout(function () {
                                $new_category_header.removeClass('hideCompletly');
                            }, 200);
                        }
                    }

                }
            }

            //wait a bit to add content to DOM completely
            setTimeout(function () {
                rad.shop_grid_animation();
                rad.lazy_on_load('#rad-wrapper');
                rad.lazy_load_on_hover();
                rad.product_hover();
                rad.product_quickview();
                rad.products_pagination();
                rad.products_layout();
                rad.sticky_products_layout();
                rad.scatter_parallax_init();
                rad.scroll_parallax_init();
            }, 50)

        }

        //Helper function to get content by url
        var get_woocommerce_content = function (pageUrl, categoryChanged) {

            //Prevent from multiple ajax requests
            if (is_active_ajax_request()) {
                xhr.abort();
            }

            rad.abortImageLoading();

            if (pageUrl) {

                $('body').trigger('wc-content-updating');

                if(rad.w_width <= 1140){
                    rad.go_to_top_shop();
                }
                
                rad.show_wrapper_loading();

                // Make sure the URL has a trailing-slash before query args (fix 301 redirect)
                pageUrl = pageUrl.replace(/\/?(\?|#|$)/, '/$1');

                //Update history of browser ( for browser next/prev button)
                window.history.pushState({ 'url': pageUrl, 'title': '' }, '', pageUrl);

                xhr = $.ajax({
                    url: pageUrl,
                    dataType: 'html',
                    data: { ajax_shop_req: true },
                    cache: false,
                    headers: { 'cache-control': 'no-cache' },
                    method: 'POST',

                    error : function (XMLHttpRequest, textStatus, error) {
                        console.log('AJAX error - ' + error);
                    },
                    success : function (response) {
                        // Update shop content
                        var $response = $(response);
                        $response = rad.apply_wc_column_switch($response);
                        update_content($response, categoryChanged);
                        update_widgets($response);

                    },
                    complete : function () {
                        rad.hide_wrapper_loading();
                    }
                });

            }
        }

        rad.woocommerce_active_tag();

        var xhr,//xmlHttpRequest
            pagination_type = $(".wc-ajax-content").data('pagination');

        if(pagination_type == 'ajax_pagination')
        {
            //Woocommerce pagination + woocommerce back-to-shop link
            $(document).on('click', '.wc-ajax-content nav.woocommerce-pagination li a, .back-to-shop', function (e) {
                if (e.handled !== true) // This will prevent event triggering more then once
                {
                    e.handled = true;
                    e.preventDefault();
                    rad.go_to_top_shop();
                    get_woocommerce_content($(this).attr('href'),false);
                }
            });
        }

        $(document).on('click', '#rad-shop-cats a', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {
                e.handled = true;
                e.preventDefault();
                get_woocommerce_content($(this).attr('href'),true);
            }

        });


        //Woocommerce Layered nav + Layered nav filter (filter by and active filters widgets) + on sale filter + in stock filter + sorting filter
        $(document).on('click', '.widget_layered_nav li a, .widget_layered_nav_filters li a,.on-sale-filter a,.in-stock-filter a', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {
                e.handled = true;
                e.preventDefault();

                if (!is_active_ajax_request()) {
                    $(this).closest('li').addClass('pending');
                }
                else {
                    $(this).closest('ul').find('.pending').removeClass('pending').toggleClass('chosen');
                }

                $(this).closest('li').toggleClass('chosen');
                get_woocommerce_content($(this).attr('href'),true);
            }
        });

        //Woocommerce rating filter
        $(document).on('click', '.reset-filter', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {

                e.handled = true;
                e.preventDefault();
                get_woocommerce_content($(this).attr('href'),false);
            }

        });

        //Woocommerce rating filter
        $(document).on('click', '.widget_rating_filter li a', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {

                e.handled = true;
                e.preventDefault();
                if ($(this).closest('ul').find('li.chosen').is($(this).closest('li'))) {
                    $(this).closest('li').toggleClass('chosen');
                }
                else {
                    $(this).closest('li').toggleClass('chosen');
                }

                get_woocommerce_content($(this).attr('href'),false);
            }

        });

        //Woocommerce ranged price filter, sorting widget
        $(document).on('click', '.widget_ranged_price_filter li a,.widget_order_by_filter li a', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {

                e.handled = true;
                e.preventDefault();
                $(this).closest('ul').find('li.current').removeClass('current');
                $(this).closest('li').toggleClass('current');
                get_woocommerce_content($(this).attr('href'),false);
            }

        });

        //Woocommerce tag cloud widget
        $(document).on('click', '.widget.woocommerce.widget_product_tag_cloud a', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {

                e.handled = true;
                e.preventDefault();
                $(this).closest('.tagcloud').find('.current-tag').removeClass('current-tag');
                $(this).addClass('current-tag');
                get_woocommerce_content($(this).attr('href'), false);
            }

        });

        //Woocommerce categories              
        $(document).on('click', '.widget_product_categories li a', function (e) {

            if ($(this).parents('.shop_is_categories_style').length) { // When shop page is set to show just categories or subcategories - filter ajax not work
                return;
            }

            if (e.handled !== true) // This will prevent event triggering more then once
            {

                e.handled = true;
                e.preventDefault();
                $(this).closest('.widget_product_categories').find('.current-cat').removeClass('current-cat');
                $(this).closest('li').addClass('current-cat');
                get_woocommerce_content($(this).attr('href'), true);
            }

        });

        //Woocommerce categories
        $(document).on('select2-open', '.widget_product_categories .dropdown_product_cat:not(.change_event_removed)', function (e) {
            $(this).addClass('change_event_removed');
            $('.dropdown_product_cat').unbind('change');
        });
        $(document).on('change', '.widget_product_categories select', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {

                e.handled = true;
                var selected = $(this).find('option:selected').val(),
                    url,
                    home_url = rad.data.home_url;

                if (home_url.indexOf('?') > 0) {
                    url = home_url + '&product_cat=' + selected;
                } else {
                    url = home_url + '?product_cat=' + selected;
                }

                get_woocommerce_content(url, true);
            }

        });

        //Woocommerce price filter
        $(document).on('click', '.widget_price_filter button.button', function (e) {
            if (e.handled !== true) // This will prevent event triggering more then once
            {

                e.handled = true;
                e.preventDefault();

                var url = window.location.href,
                    min_price = $(this).siblings('#min_price').val(),
                    max_price = $(this).siblings('#max_price').val();

                //Update/add min_price and max_price
                url = rad.updateQueryStringParameter(url, 'min_price', min_price);
                url = rad.updateQueryStringParameter(url, 'max_price', max_price);

                get_woocommerce_content(url,false);
            }

        });

        //Woocommerce sort
        //Unbind previous function and bind new function to orderby select
        $('.woocommerce-ordering').off('change', 'select.orderby');
        $('.woocommerce-ordering').on('change', 'select.orderby', function () {

            var selected = $(this).find('option:selected').val();
            var url = window.location.href;

            //Update/add orderby
            url = rad.updateQueryStringParameter(url, 'orderby', selected);

            get_woocommerce_content(url,false);

        });

        //Woocommerce search
        $(document).find("form.woocommerce-product-search").each(function () {
            var $this = $(this);
            $this.submit(function (e) {
                e.preventDefault();
                var keyword = $this.find('input.search-field').val();
                if (keyword != '') {
                    $this.find('input.search-field').blur();//Hide virtual keyboard in mobiles

                    var url = $this.attr('action');
                    //Update/add orderby
                    url = rad.updateQueryStringParameter(url, 's', keyword);
                    //Do not add post_type to URL if this form is in category page
                    if ($this.attr('data-type') != 'category') {
                        url = rad.updateQueryStringParameter(url, 'post_type', 'product');
                    }
                    get_woocommerce_content(url);
                }
            });
        });
    },

    //a helper function to add/update querystrings of URL
    rad.updateQueryStringParameter = function (uri, key, value) {
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        }
        else {
            return uri + separator + key + "=" + value;
        }
    };

    /**************************************************
    /*  Show cart in cart page
    **************************************************/
    rad.update_widget_cart_on_cart_page = function () {
        if(!rad.active_wc)
            return;

        //Use ajaxSend event to detect when it's needed to update cart
        var ajaxStartHandlerForCartPage = function (event, xhr, settings) {
            var main_form_action = $('form.woocommerce-cart-form').attr('action');
            if (settings.url.indexOf('get_cart_totals') > 0) {
                $(document.body).trigger('wc_fragment_refresh');
            }
        }

        if ($('body').hasClass('woocommerce-cart')) // just do it in cart page
        {
            $(document).ajaxSend(ajaxStartHandlerForCartPage);
        }
    };

    /**************************************************
    /*  top Button
    **************************************************/
    rad.go_up = function () {

        var $go_up = $(".go-up");

        if ($go_up.length <= 0 || rad.w_width <= 1140)
            return;

        var latestKnownScrollPosition = 0,
            tick = false,
            visibilityThreshold = rad.w_height * 1.7;

        //use unbind to prevent from multiple times clikc event
        $go_up.on('click',function (e) {
            e.preventDefault();
            rad.scroll_to("body");  //scroll to top of page 
        });

        var update_button_visibility  = function () {

            if (visibilityThreshold > latestKnownScrollPosition) {
                $go_up.removeClass('show');
            }
            else {
                $go_up.addClass('show');
            }

            tick = false;
        }

        update_button_visibility();

        var requestTick  = function () {
            if (tick == false) {
                window.requestAnimationFrame(update_button_visibility);
            }
            tick = true;
        }

        var onScroll  = function () {
            latestKnownScrollPosition = window.scrollY;
            requestTick();
        }

        rad.$window.on('scroll', onScroll);
    };

    /**************************************************
    /*  Masonry Blog
    **************************************************/
    rad.card_blog = function (isLoadMore) {

        $('.card-blog .isotope').each(function () {

            var $container = $(this),
                layout    = $(this).data('layout');

            if (isLoadMore != true) {
                $container.isotope({
                    itemSelector: '.isotope-item',
                    layoutMode: layout,
                });
            }

            // call isotope animation
            rad.isotopeAnimation($container);

            var blog_resize_handler = function ()
            {
                setTimeout(function () {
                    $container.isotope('reLayout');
                }, 500);
            }
            rad.$window.on('resize', blog_resize_handler);

            $container.find('.swiper-container').each(function () {

                var $this = $(this);
                if ($this.find('.swiper-slide').length > 1) {
                    var $next_button = $this.find('.rad-carousel-next'),
                        $prev_button = $this.find('.rad-carousel-prev'),
                        autoplayDuration = 3000 + Math.floor(Math.random() * 4000);


                    //Prevent from running swiper multiple times on initiated items
                    if ($this[0].swiper != undefined)
                        return true;

                    // Gallery Post format 
                    var $card_blog_slider = new Swiper($this, {
                        speed: 600,
                        longSwipesMs: 700,
                        touchAngle: 30,
                        loop: true,
                        autoplay: {
                            delay: autoplayDuration,
                            disableOnInteraction: false,
                        },
                        followFinger: false,
                        navigation: {
                            nextEl: $next_button,
                            prevEl: $prev_button,
                        }
                    });
                }
            });
        });
    };

    /**************************************************
    /*  Scrollbar width
    **************************************************/
    rad.detect_scroll_bar_width = function () {
        return;
        
        var inner = document.createElement('p'),
            outer = document.createElement('div');
        inner.style.cssText = 'width: 100%; height: 200px;';
        outer.style.cssText = 'width: 200px; height: 150px; position:absolute; visibility:hidden; left:0px; top:0px; overflow:hidden;';
        outer.appendChild(inner);

        document.body.appendChild(outer);
        var w1 = inner.offsetWidth;
        outer.style.overflow = 'scroll';
        var w2 = inner.offsetWidth;
        if (w1 == w2) w2 = outer.clientWidth;
        document.body.removeChild(outer);

        if ((w1 - w2) > 0) { // Detect scrollbar width
            if ($('body').height() > rad.w_height) { // Detect if a page has a vertical scrollbar?
                $('body').addClass('has-scrollbar');

                if ((w1 - w2) == 15) { // ios device 
                    $('body').addClass('scrollbarSize15');
                } else if ((w1 - w2) == 17) { // chorme and firefox in windows 
                    $('body').addClass('scrollbarSize17');
                } else if ((w1 - w2) == 12) { // edge in windows 
                    $('body').addClass('scrollbarSize12');
                }
            }
        }
    };

    rad.cat_widget_update = function() { //add toggle button to category widget + show current category/subcategory
        var $widget = $('.widget_product_categories'),
        $list = $widget.find('.product-categories');
        
        $list.find('.cat-parent').each(function()
        {
            var $this = $(this);
            if( $this.find('ul').length <= 0 )
                return true;
            
            if( $this.hasClass('current-cat-parent'))
                $this.append( '<div class="cats-toggle toggle-active"></div>' );
            else
                $this.append( '<div class="cats-toggle"></div>' );
        });
        
        
        if( $list.find('li.current-cat').length > 0 )
        {
            $list.find('li.current-cat').parents('ul').css("display","block");
            $list.find('li.current-cat ul.children').css("display","block");
            $list.find('.current-cat.cat-parent .cats-toggle').addClass('toggle-active');
        }
    };
    
    rad.cat_widget = function(){
        var $widget = $('.widget_product_categories'),
        $list = $widget.find('.product-categories'),
        time = 500;
        
        $list.on('click', '.cats-toggle', function()
        {
            var $btn = $(this),
            $subList = $btn.prev();
            if( $subList.hasClass('list-shown') ) 
            {
                $btn.removeClass('toggle-active');
                $subList.stop().slideUp(time).removeClass('list-shown');
            }
            else 
            {
                $subList.parent().parent().find('> li > .list-shown').slideUp().removeClass('list-shown');
                $subList.parent().parent().find('> li > .toggle-active').removeClass('toggle-active');
                $btn.addClass('toggle-active');
                $subList.stop().slideDown(time).addClass('list-shown');
            }
        });
    };
    

    rad.cookies_notice = function () {

        if(rad.data.cookie_notice == 0)
            return;
        
        var cookie_enabled = navigator.cookieEnabled,
            name = 'rad-'+ rad.data.cookie_notice_id +'-notice';
        if (!cookie_enabled){ 
            document.cookie = "testcookie";
            cookie_enabled = document.cookie.indexOf("testcookie")!=-1;
            document.cookie = "cookiename=testcookie;expires = Thu, 01 Jan 1970 00:00:00 GMT"
        }

        if (cookie_enabled == false ) {
            return false;
        }

        Cookies.set() == 'accepted'

        if( Cookies.set(name) == 'accepted') 
            return;

        var $cookies_notice = $( '#rad-cookies-wrap');

        setTimeout(function() {
            $cookies_notice.addClass('show').find('.rad-accept').on('click', function (e) {
                e.preventDefault();
                $cookies_notice.removeClass('show');
                Cookies.set(name, 'accepted', { expires: 60, path: '/'} );
            })
        }, 2000);
    };


    // popup
    rad.popup = function() {

        var $newsletter_modal = $("#rad-popup-newsletter"),
            name = 'rad-'+ rad.data.cookie_popup_id +'-popup-nl';

        if ($newsletter_modal.length <= 0 || ($newsletter_modal.hasClass('hidden-phone') && rad.is_mobile)) {
            return;
        }
            
        if ( Cookies.set(name) != 'dismiss' ) {
            setTimeout(function () {
                rad.modals_open('newsletter','rad-newsletter');
                rad.modals_show($newsletter_modal);
            }, 1000);

        }

        $(document).on('newsletter-modal-close',function (e) {
            Cookies.set(name, 'dismiss', { expires: 60, path: '/'});
        });
    };
     
    /**************************************************
    /*  products pagination
    **************************************************/
    rad.products_pagination = function() {
        
        var self = this,
            xhr,
            $shop = $(".wc-ajax-content"),
            $next = $shop.find('.woocommerce-pagination li a.next'),
            type  = $shop.data('pagination'),
            $waypoint;

        if(type == 'pagination' || type == 'ajax_pagination' || $next.length <= 0) {
            return;
        }
        else if(type == 'load_more')
        {   
            $('body').on('click','.woocommerce-pagination li a.next',function(e){
                e.preventDefault();
                $(this).addClass('loading');
                load_more_products($(this).attr('href'))
            })
        }
        else
        {
            $waypoint = new Waypoint({
                element : $shop.find('.woocommerce-pagination li a.next'),
                handler : function () {
                    load_more_products($(this.element).attr('href'))
                },
                offset: '90%'
            });
        }

        var load_more_products = function (pageUrl) {

            if (!pageUrl)
                return;

            if (typeof $waypoint !== 'undefined') {
                $waypoint.disable();
            }

            //Prevent from multiple ajax requests
            if (xhr && xhr.readyState != 4) {
                xhr.abort();
            }

            rad.abortImageLoading();

            $('body').trigger('wc-content-updating');
            
            // Make sure the URL has a trailing-slash before query args (fix 301 redirect)
            pageUrl = pageUrl.replace(/\/?(\?|#|$)/, '/$1');

            xhr = $.ajax({
                url: pageUrl,
                dataType: 'html',
                data: { ajax_shop_req: true },
                cache: false,
                headers: { 'cache-control': 'no-cache' },
                method: 'POST',

                error : function (XMLHttpRequest, textStatus, error) {
                    console.log('AJAX error - ' + error);
                },
                success : function (response) {
                    // Update shop content
                    var $response = $(response),
                        $new_items = $response.find('.wc-ajax-content ul.products'),
                        $next = $response.find('.woocommerce-pagination a.next');

                    if ($new_items.length > 0) {
                        $('.wc-ajax-content .products').append($new_items.html());
                    }

                    if($next.length > 0 && $('.woocommerce-pagination a.next').attr('href') != $next.attr('href')) {
                        $('.woocommerce-pagination a.next').attr('href',$next.attr('href'));
                    }
                    else
                    {
                        $('.woocommerce-pagination a.next').remove();
                    }

                    //wait a bit to add content to DOM completely
                    setTimeout(function () {
                        rad.shop_grid_animation();
                        rad.lazy_on_load('#rad-wrapper');
                        rad.lazy_load_on_hover();
                        rad.product_hover();
                        rad.product_quickview();
                        Waypoint.refreshAll();
                        
                    }, 50);

                    setTimeout(function () {
                        if (typeof $waypoint !== 'undefined') {
                            $waypoint.enable();//wait a bit after adding elements to DOM
                        }
                        $(document).trigger("update_shop_height");
                    }, 400);

                },
                complete : function () {
                    $('.woocommerce-pagination li a.next').removeClass('loading')
                }
            });
        }
    };

    /**************************************************
    /*  Show More tag
    **************************************************/
    /* optimization : depend on spec and design */
    rad.show_more_tag = function () {

        if ($('.widget_product_tag_cloud .tagcloud').length <= 0)
            return;

        var $product_tag_height = $('.widget_product_tag_cloud .tagcloud').height();
        if ($product_tag_height > 80 ) {
            $('.widget_product_tag_cloud').addClass("collapse");
            /* DOIT : "Show More" would be translatable */
            $('.widget_product_tag_cloud .tagcloud').after(`<span class='show_more_tags'>${rad.data.loadmore}</span>`);
        }

        $('.widget_product_tag_cloud .show_more_tags').on('click', function (e) {
            e.preventDefault();
            $('.widget_product_tag_cloud').removeClass("collapse");
        });

    };

    /**************************************************
    /*  Size chart pop-up
    **************************************************/
    rad.size_chart = function () {
        var chart_container = $('.size-chart-aside .size-chart-wrapper');

        $('.size-chart-button').on('click', function (e) {
            e.preventDefault();
            var chart_id = $( this ).data( "chart-id" );
            var data = $(`#tab-yith-wcpsc-tab-${chart_id} .yith-wcpsc-product-table-wrapper`).clone();
            chart_container.html(data);
        });
        
        rad.scrollbar('.size-chart-aside');
    }



    /**************************************************
     *    Fire when document ready
     **************************************************/
    $( function() {
        rad.init();
    } );
})( jQuery );