(function ($) {
    'use strict';

    var isTouch  = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0) || (navigator.maxTouchPoints)),
        isMobile = navigator.userAgent.match(
            /(iPhone|iPod|iPad|Android|playbook|silk|BlackBerry|BB10|Windows Phone|Tizen|Bada|webOS|IEMobile|Opera Mini)/
        ),
        get_url  = function (endpoint) {
            return ocolus_main_params.ocolus_ajax_url.toString().replace(
                '%%endpoint%%',
                endpoint
            );
        };

    var Mobile_Detect = {
        Mobile: function () {
            return navigator.userAgent.match(
                /(iPhone|iPod|Android|Phone|DROID|ZuneWP7|silk|BlackBerry|BB10|Windows Phone|Tizen|Bada|webOS|IEMobile|Opera Mini)/
            );
        },
        Tablet: function () {
            return navigator.userAgent.match(
                /(Tablet|iPad|Kindle|Playbook|Nexus|Xoom|SM-N900T|GT-N7100|SAMSUNG-SGH-I717|SM-T330NU)/
            );
        },
        any   : function () {
            return (Mobile_Detect.Mobile() || Mobile_Detect.Tablet());
        }
    };

    $.fn.ocolus_vertical_menu = function () {
        /* SHOW ALL ITEM */
        var _countLi      = 0,
            _verticalMenu = $(this).find('.vertical-menu'),
            _blockNav     = $(this).closest('.block-nav-category'),
            _blockTitle   = $(this).find('.block-title');

        $(this).each(function () {
            var _dataItem = $(this).data('items') - 1;
            _countLi      = $(this).find('.vertical-menu>li').length;

            if (_countLi > (_dataItem + 1)) {
                $(this).addClass('show-button-all');
            }
            $(this).find('.vertical-menu>li').each(function (i) {
                _countLi = _countLi + 1;
                if (i > _dataItem) {
                    $(this).addClass('link-other');
                }
            });
        });
        /* VERTICAL MENU ITEM */
        if (_verticalMenu.length > 0) {
            $(document).on('click', '.open-cate', function (e) {
                _blockNav.find('li.link-other').each(function () {
                    $(this).slideDown();
                });
                $(this).addClass('close-cate')
                       .removeClass('open-cate')
                       .find('.text').html($(this).data('closetext'));
                e.preventDefault();
            });
            $(document).on('click', '.close-cate', function (e) {
                _blockNav.find('li.link-other').each(function () {
                    $(this).slideUp();
                });
                $(this).addClass('open-cate')
                       .removeClass('close-cate')
                       .find('.text').html($(this).data('alltext'));
                e.preventDefault();
            });

            _blockTitle.on('click', function () {
                $(this).toggleClass('active');
                $(this).parent().toggleClass('has-open');
                $('body').toggleClass('category-open');
            });
        }
    };
    /* ANIMATE */
    $.fn.ocolus_animation_tabs     = function ($tab_animated) {
        $tab_animated = ($tab_animated === undefined || $tab_animated === '') ? '' : $tab_animated;
        if ($tab_animated !== '') {
            $(this).find('.owl-slick .slick-active, .product-list-grid .product-item').each(function (i) {
                var _this  = $(this),
                    _style = _this.attr('style'),
                    _delay = i * 200;

                _style = (_style === undefined) ? '' : _style;
                _this.attr('style', _style +
                                    ';-webkit-animation-delay:' + _delay + 'ms;' +
                                    '-moz-animation-delay:' + _delay + 'ms;' +
                                    '-o-animation-delay:' + _delay + 'ms;' +
                                    'animation-delay:' + _delay + 'ms;'
                ).addClass($tab_animated + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                    _this.removeClass($tab_animated + ' animated');
                    _this.attr('style', _style);
                });
            });
        }
        if ($(this).find('.wpb_animate_when_almost_visible').length) {
            $(this).find('.wpb_animate_when_almost_visible').removeClass('wpb_animate_when_almost_visible');
        }
    };
    $.fn.ocolus_init_carousel      = function () {
        $(this).not('.slick-initialized').each(function () {
            var _this   = $(this),
                _config = _this.data('slick') !== undefined ? _this.data('slick') : [];

            if (_this.hasClass('flex-control-thumbs')) {
                _config = _this.closest('.woocommerce-product-gallery').data('attr_slick');
            }
            if (_config.vertical == true) {
                _config.prevArrow = '<span class="icomoon-Up-arrow prev"><span class="text">' + ocolus_main_params.nav_prev + '</span></span>';
                _config.nextArrow = '<span class="icomoon-Up-arrow next"><span class="text">' + ocolus_main_params.nav_next + '</span></span>';
            } else {
                _config.prevArrow = '<span class="icomoon-Back prev"><span class="text">' + ocolus_main_params.nav_prev + '</span></span>';
                _config.nextArrow = '<span class="icomoon-Next next"><span class="text">' + ocolus_main_params.nav_next + '</span></span>';
            }
            if ($('body').hasClass('rtl')) {
                _config.rtl = true;
            }
            _this.on('init', function (event, slick) {
                $(event.target).trigger('ocolus_trigger_init_slide', slick);
            });
            _this.slick(_config);
            _this.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
                $(slick.$list).trigger('ocolus_trigger_before_change_slide', slick, currentSlide, nextSlide);
            });
            _this.on('afterChange', function (event, slick, currentSlide, nextSlide) {
                $(slick.$list).find('.lazy').ocolus_init_lazy_load();
                $(slick.$list).trigger('ocolus_trigger_after_change_slide', slick, currentSlide, nextSlide);
            });
            _this.on('setPosition', function (event) {
                $(event.target).trigger('ocolus_trigger_setPosition_slide');
                if ($(event.target).find('.product-item.style-01').length) {
                    $(event.target).find('.product-item.style-01').ocolus_hover_product();
                }
            });
        });
    };
    $.fn.ocolus_init_lazy_load     = function () {
        $(this).each(function () {
            var _this   = $(this),
                _config = [];

            _config.beforeLoad     = function (element) {
                if (element.is('div') === true) {
                    element.addClass('loading-lazy');
                } else {
                    element.parent().addClass('loading-lazy');
                }
            };
            _config.afterLoad      = function (element) {
                if (element.is('div') === true) {
                    element.removeClass('loading-lazy');
                } else {
                    element.parent().removeClass('loading-lazy');
                }
            };
            _config.onFinishedAll  = function () {
                if (!this.config('autoDestroy'))
                    this.destroy();
            }
            _config.effect         = "fadeIn";
            _config.enableThrottle = true;
            _config.throttle       = 250;
            _config.effectTime     = 600;
            if (_this.closest('.canvas-sidebar').length) {
                _config.appendScroll = _this.closest('.canvas-sidebar > .widget-area');
            }
            if (_this.closest('.filter-content').length) {
                _config.appendScroll = _this.closest('.filter-content > .widget-area');
            }
            if (_this.closest('.ovic-menu-clone-wrap').find('.ovic-menu-panel').length) {
                _config.appendScroll = _this.closest('.ovic-menu-clone-wrap').find('.ovic-menu-panel');
            }
            _this.lazy(_config);
        });
    };
    $.fn.ocolus_better_equal_elems = function () {
        if (!Mobile_Detect.Mobile()) {
            var _this = $(this);
            _this.on('ocolus_better_equal_elems', function () {
                setTimeout(function () {
                    _this.each(function () {
                        if ($(this).find('.equal-elem').length) {
                            $(this).find('.equal-elem').css({
                                'height': 'auto'
                            });
                            var _height = 0;
                            $(this).find('.equal-elem').each(function () {
                                if (_height < $(this).height()) {
                                    _height = $(this).height();
                                }
                            });
                            $(this).find('.equal-elem').height(_height);
                        }
                    });
                }, 100);
            }).trigger('ocolus_better_equal_elems');
            $(window).on('resize', function () {
                _this.trigger('ocolus_better_equal_elems');
            });
        }
    };
    $.fn.ocolus_sticky_header      = function () {
        $(this).each(function () {
            var _this          = $(this),
                _lastScrollTop = 0,
                _header_height = $('.header').height();

            $(window).scroll(function (event) {
                var st = $(this).scrollTop();
                if (st > _header_height + 60) {
                    _this.addClass('is-sticky');
                } else {
                    _this.removeClass('is-sticky');
                    _this.find('.ocolus-dropdown').removeClass('open');
                }
            });
        });
    };
    $.fn.ocolus_scroll_percent     = function () {
        var $this = $(this);
        $this.on('ocolus_scroll_percent', function () {
            $this.each(function () {
                var scrollTop            = $(window).scrollTop(),
                    docHeight            = $(document).height(),
                    winHeight            = $(window).height(),
                    scrollPercent        = (scrollTop) / (docHeight - winHeight),
                    scrollPercentRounded = Math.round(scrollPercent * 100) + '%';

                if ($('#header').outerHeight() + 100 < scrollTop) {
                    $(this).closest('.scroll-percent').addClass('sticky');
                } else {
                    $(this).closest('.scroll-percent').removeClass('sticky');
                }
                $(this).css('width', scrollPercentRounded);
            });
        }).trigger('ocolus_scroll_percent');
        $(window).scroll(function () {
            $this.trigger('ocolus_scroll_percent');
        });
    };
    $.fn.ocolus_goto_comment       = function () {
        $(this).each(function () {
            $(this).on('click', function (e) {

                if ($('#commentform').length) {
                    $('html, body').animate({
                        scrollTop: $('#commentform').offset().top - $('#commentform').height()
                    }, 'slow');
                }

                e.preventDefault();
            });
        });
    };
    /* AJAX TABS */
    $(document).on('click', '.ovic-tabs .tabs .tab-link, .ovic-accordion .panel-heading a', function (e) {
        e.preventDefault();
        var $this       = $(this),
            $data       = $this.data(),
            $tabID      = $this.attr('href'),
            $tabItem    = $this.closest('.tab-item'),
            $tabContent = $($tabID).closest('.tabs-container,.ovic-accordion'),
            $data_atts  = window['ovic_vc_tta_section_' + $data.section],
            $loaded     = $this.closest('.tabs,.ovic-accordion').find('a.loaded').attr('href');

        if ($data.ajax == 1 && !$this.hasClass('loaded')) {
            $tabContent.addClass('loading');
            $tabItem.addClass('active').closest('.tabs').find('.tab-item').not($tabItem).removeClass('active');
            $.ajax({
                type     : 'POST',
                url      : get_url('content_ajax_tabs'),
                data     : {
                    security: ocolus_main_params.security,
                    section : $data_atts.content,
                },
                success  : function (response) {
                    $('[href="' + $loaded + '"]').removeClass('loaded');
                    if (response) {
                        $($tabID).html(response);
                        if ($($tabID).find('.lazy').length) {
                            $($tabID).find('.lazy').lazy({delay: 0});
                        }
                        if ($($tabID).find('.equal-container.better-height').length) {
                            $($tabID).find('.equal-container.better-height').ocolus_better_equal_elems();
                        }
                        if ($($tabID).find('.ocolus-countdown').length && $.fn.ocolus_countdown) {
                            $($tabID).find('.ocolus-countdown').ocolus_countdown();
                        }
                        if ($($tabID).find('.ovic-products').length && $.fn.ocolus_load_infinite) {
                            $($tabID).find('.ovic-products').ocolus_load_infinite();
                        }
                        if ($($tabID).find('.product-item').length) {
                            $($tabID).find('.product-item').ocolus_hover_zoom_product();
                        }
                        if ($($tabID).find('.variations_form').length && $.fn.wc_variation_form) {
                            $($tabID).find('.variations_form').each(function () {
                                $(this).wc_variation_form();
                            });
                        }
                        if ($($tabID).find('.owl-slick').length) {
                            $($tabID).find('.owl-slick').ocolus_init_carousel();
                        }
                        if ($($tabID).find('.yith-wcqv-button,.compare-button a.compare,.yith-wcwl-add-to-wishlist a').length) {
                            $($tabID).find('.yith-wcqv-button,.compare-button a.compare,.yith-wcwl-add-to-wishlist a').ocolus_bootstrap_tooltip();
                        }
                    } else {
                        $($tabID).html('<div class="alert alert-warning"><strong>Warning!</strong> No content found.</div>');
                    }
                    /* for accordion */
                    $this.closest('.panel-default').addClass('active').siblings().removeClass('active');
                    $this.closest('.ovic-accordion').find($tabID).slideDown(400);
                    $this.closest('.ovic-accordion').find('.panel-collapse').not($tabID).slideUp(400);
                },
                complete : function () {
                    setTimeout(function ($tabID, $tab_animated, $loaded) {
                        $($tabID).addClass('active').siblings().removeClass('active');
                        $($tabID).ocolus_animation_tabs($tab_animated);
                        $($loaded).html('');
                    }, 10, $tabID, $data.animate, $loaded);
                    $this.addClass('loaded');
                    $tabContent.removeClass('loading');
                    /* trigger ajax complete */
                    $($tabID).trigger('ocolus_ajax_tabs_complete');
                },
                ajaxError: function () {
                    $tabContent.removeClass('loading');
                    $($tabID).html('<div class="alert alert-danger"><strong>Danger!</strong> Can not Load Data.</div>');
                }
            });
        } else {
            $tabItem.addClass('active').closest('.tabs').find('.tab-item').not($tabItem).removeClass('active');
            $($tabID).addClass('active').siblings().removeClass('active');
            /* for accordion */
            $this.closest('.panel-default').addClass('active').siblings().removeClass('active');
            $this.closest('.ovic-accordion').find($tabID).slideDown(400);
            $this.closest('.ovic-accordion').find('.panel-collapse').not($tabID).slideUp(400);
            /* for animate */
            $($tabID).ocolus_animation_tabs($data.animate);
            if ($($tabID).find('.lazy').length) {
                $($tabID).find('.lazy').ocolus_init_lazy_load();
            }
        }
    });
    /* LOAD MORE POST */
    $.fn.ocolus_load_post = function () {
        var is_busy        = false,
            previousScroll = 0,
            is_load        = function ($url, $response, $pagination) {
                var $max_page = $pagination.find('.button-loadmore').data('total');
                $pagination.addClass('loading');
                $.ajax({
                    url     : $url,
                    data    : {
                        ocolus_raw_content: 1,
                    },
                    success : function (response) {
                        if (!response) {
                            return;
                        }
                        var $html       = $.parseHTML(response, document, true),
                            $nav        = $('.pagination-nav', $html).length ? $('.pagination-nav', $html)[0].innerHTML : '',
                            $content    = $('.response-content', $html).length ? $('.response-content', $html)[0] : '',
                            $current    = $('.pagination-nav', $html).find('.button-loadmore').data('current'),
                            $post_items = $($content).children();

                        if ($content !== '') {
                            if ($response.hasClass('ocolus-isotope') && $.fn.ocolus_isotope_grid) {
                                $response.append($content.innerHTML);
                                $response
                                    .isotope('appended', $content, true)
                                    .isotope('reloadItems')
                                    .ocolus_isotope_grid();
                            } else if ($response.hasClass('owl-slick')) {
                                var $lastSlide = $response.find('.last-slick').data('slick-index');

                                $response.slick('slickAdd', $post_items);
                                $response.slick('slickGoTo', $lastSlide);
                            } else {
                                $post_items.each(function (i) {
                                    var $product = $(this),
                                        $style   = $product.attr('style'),
                                        $delay   = i * 100;

                                    $style = ($style === undefined) ? '' : $style;
                                    $product.attr('style', $style +
                                                           ';-webkit-animation-delay:' + $delay + 'ms;' +
                                                           '-moz-animation-delay:' + $delay + 'ms;' +
                                                           '-o-animation-delay:' + $delay + 'ms;' +
                                                           'animation-delay:' + $delay + 'ms;'
                                    ).addClass('fadeInUp' + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                                        $product.removeClass('fadeInUp' + ' animated');
                                        $product.attr('style', $style);
                                    });
                                    $response.append($product);
                                });
                            }
                            is_busy = false;
                            $response.trigger('ocolus_load_more_post');
                        } else {
                            is_busy = true;
                        }
                        if ($current >= $max_page) {
                            $pagination.closest('.pagination-nav').remove();
                        } else {
                            $pagination.html($nav);
                            $pagination.removeClass('loading');
                        }
                    },
                    complete: function () {
                        if ($response.find('.lazy').length) {
                            $response.find('.lazy').lazy({delay: 0});
                        }
                        if ($response.find('.variations_form').length && $.fn.wc_variation_form) {
                            $response.find('.variations_form').each(function () {
                                $(this).wc_variation_form();
                            });
                        }
                        if ($response.closest('.site-main').find('.equal-container.better-height').length) {
                            $response.closest('.site-main').find('.equal-container.better-height').ocolus_better_equal_elems();
                        }
                        if ($response.find('.yith-wcqv-button,.compare-button a.compare,.yith-wcwl-add-to-wishlist a').length) {
                            $response.find('.yith-wcqv-button,.compare-button a.compare,.yith-wcwl-add-to-wishlist a').ocolus_bootstrap_tooltip();
                        }
                    }
                });
            };

        $(document).on('click', '.pagination-nav.type-load_more .button-loadmore', function (e) {
            e.preventDefault();
            var $this       = $(this),
                $url        = $this.data('url'),
                $contain    = $this.closest('.site-main'),
                $response   = $contain.find('.response-content'),
                $pagination = $this.closest('.pagination-nav');

            is_load($url, $response, $pagination);
        });

        if ($('.pagination-nav.type-infinite .button-loadmore').length) {

            if ($(this).closest('.site-main').find('.response-content').hasClass('owl-slick')) {
                $(this).closest('.site-main').find('.response-content').on('afterChange', function (event, slick) {

                    var $this       = $('.pagination-nav.type-infinite .button-loadmore'),
                        $url        = $this.data('url'),
                        $contain    = $this.closest('.site-main'),
                        $response   = $contain.find('.response-content'),
                        $pagination = $this.closest('.pagination-nav'),
                        $lastSlide  = $(event.target).find('.last-slick').data('slick-index');

                    if ($lastSlide === slick.slideCount - 1 && is_busy === false) {
                        is_load($url, $response, $pagination);
                    }
                });
            } else {
                $(document).on('scroll', function () {

                    var $this       = $('.pagination-nav.type-infinite .button-loadmore'),
                        $url        = $this.data('url'),
                        $contain    = $this.closest('.site-main'),
                        $response   = $contain.find('.response-content'),
                        $pagination = $this.closest('.pagination-nav');

                    var currentScroll = $(this).scrollTop();

                    if (currentScroll > previousScroll) {

                        if ($pagination.length && $(window).scrollTop() + $(window).height() >= $pagination.offset().top) {

                            if (is_busy === false) {
                                is_load($url, $response, $pagination);
                            }
                            is_busy = true;
                        }
                    }

                    previousScroll = currentScroll;

                });
            }

        }
    };
    $(document).on('click', '.action-backtotop', function (e) {
        $('html, body').animate({scrollTop: 0}, 800);
        e.preventDefault();
    });
    $(document).on('click', function (event) {
        var _target = $(event.target).closest('.ocolus-dropdown'),
            _parent = $('.ocolus-dropdown');

        if (_target.length) {
            _parent.not(_target).removeClass('open');
            if ($(event.target).is('[data-ocolus="ocolus-dropdown"]') ||
                $(event.target).closest('[data-ocolus="ocolus-dropdown"]').length) {
                if (_target.hasClass('overlay')) {
                    if (_target.hasClass('open')) {
                        $('body').removeClass('active-overlay');
                    } else {
                        $('body').addClass('active-overlay');
                    }
                }
                _target.toggleClass('open');
                event.preventDefault();
            }
        } else {
            $('.ocolus-dropdown').removeClass('open');
            if (_target.hasClass('overlay') || !_target.length) {
                $('body').removeClass('active-overlay');
            }
        }
    });
    $(document).on('click', '.product-item .product-gallery li a', function (event) {
        var _this     = $(this),
            _img      = _this.attr('href'),
            _parent   = _this.closest('.product-item'),
            _main_img = _parent.find('.wp-post-image');

        if (_main_img) {
            //_main_img.parent().addClass('loading-lazy');
            _main_img.attr('src', _img).attr('srcset', _img);
            _main_img.css({
                '-webkit-transform' : 'scale(0.5)',
                '-moz-transform'    : 'scale(0.5)',
                '-ms-transform'     : 'scale(0.5)',
                '-o-transform'      : 'scale(0.5)',
                'transform'         : 'scale(0.5)',
                'opacity'           : '0',
                '-webkit-transition': 'all 0.3s ease',
                '-moz-transition'   : 'all 0.3s ease',
                '-ms-transition'    : 'all 0.3s ease',
                '-o-transition'     : 'all 0.3s ease',
                'transition'        : 'all 0.3s ease',
            }).load(function () {
                var image = $(this);
                setTimeout(function () {
                    image.css({
                        '-webkit-transform' : 'scale(1)',
                        '-moz-transform'    : 'scale(1)',
                        '-ms-transform'     : 'scale(1)',
                        '-o-transform'      : 'scale(1)',
                        'transform'         : 'scale(1)',
                        'opacity'           : '1',
                        '-webkit-transition': 'all 0.3s ease',
                        '-moz-transition'   : 'all 0.3s ease',
                        '-ms-transition'    : 'all 0.3s ease',
                        '-o-transition'     : 'all 0.3s ease',
                        'transition'        : 'all 0.3s ease',
                    });
                    //image.parent().removeClass('loading-lazy');
                }, 300);
            });
            $(this).parent().addClass('active').siblings().removeClass('active');
        }

        event.preventDefault();
    });
    /* ADD TO CART SINGLE PRODUCT */
    var serializeObject = function (form) {
        var o = {};
        var a = form.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
    $(document).on('click', '.product:not(.product-type-external) .single_add_to_cart_button', function (e) {

        var $thisbutton = $(this);

        if (!$thisbutton.hasClass('disabled') && ocolus_main_params.ajax_add_to_cart) {
            console.log(ocolus_main_params.ajax_add_to_cart);

            var form = $thisbutton.closest('form'),
                data = serializeObject(form);

            if ($thisbutton.val()) {
                data.product_id = $thisbutton.val();
            }

            $thisbutton.addClass('loading');

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

            // Ajax action.
            $.post(get_url('add_to_cart_single'), data, function (response) {

                $thisbutton.removeClass('loading');

                if (!response) {
                    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;
                }

                // Trigger event so themes can refresh other areas.
                $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);

            });
            e.preventDefault();

        }
    });
    /* QUANTITY */
    if (!String.prototype.getDecimals) {
        String.prototype.getDecimals = function () {
            var num   = this,
                match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
            if (!match) {
                return 0;
            }
            return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
        };
    }
    $(document).on('click', '.quantity-plus, .quantity-minus', function (e) {
        e.preventDefault();
        // Get values
        var $qty       = $(this).closest('.quantity').find('.qty'),
            currentVal = parseFloat($qty.val()),
            max        = parseFloat($qty.attr('max')),
            min        = parseFloat($qty.attr('min')),
            step       = $qty.attr('step');

        if (!$qty.is(':disabled')) {
            // Format values
            if (!currentVal || currentVal === '' || currentVal === 'NaN') currentVal = 0;
            if (max === '' || max === 'NaN') max = '';
            if (min === '' || min === 'NaN') min = 0;
            if (step === 'any' || step === '' || step === undefined || parseFloat(step) === 'NaN') step = '1';

            // Change the value
            if ($(this).is('.quantity-plus')) {
                if (max && (currentVal >= max)) {
                    $qty.val(max);
                } else {
                    $qty.val((currentVal + parseFloat(step)).toFixed(step.getDecimals()));
                }
            } else {
                if (min && (currentVal <= min)) {
                    $qty.val(min);
                } else if (currentVal > 0) {
                    $qty.val((currentVal - parseFloat(step)).toFixed(step.getDecimals()));
                }
            }

            // Trigger change event
            $qty.trigger('change');
        }
    });

    $(document).on('added_to_wishlist removed_from_wishlist', function () {
        $.get(get_url('update_wishlist_count'), function (count) {
            if (!count) {
                count = 0;
            }
            $('.block-wishlist .count').text(count);
        });
    });

    /* NOIFICATIONS */
    $.fn.ocolus_add_notify = function ($text_content) {
        var config    = [],
            $img_html = '',
            $this     = $(this),
            $img      = $this.closest('.product-item').find('img.wp-post-image'),
            pName     = $this.attr('aria-label');

        config.duration = ocolus_main_params.growl_notice.growl_duration;
        config.title    = ocolus_main_params.growl_notice.growl_notice_text;

        $this.removeClass('loading');

        // if from wishlist
        if (!$img.length) {
            $img = $this.closest('tr')
                        .find('.product-thumbnail img');
        }
        // if from single product page
        if (!$img.length) {
            $img = $this.closest('.product').find('.woocommerce-product-gallery__wrapper img.wp-post-image');
        }
        if (typeof pName === 'undefined' || pName === '') {
            pName = $this.closest('.product').find('.summary .product_title').text();
        }
        // if from mini cart
        if ($this.closest('.mini_cart_item').length) {
            $img  = $this.closest('.mini_cart_item').find('a > img');
            pName = $this.closest('.mini_cart_item').find('a:not(.remove)').clone().children().remove().end().text();
        }

        // reset state after 5 sec
        setTimeout(function () {
            $this.removeClass('added').removeClass('recent-added');
            $this.next('.added_to_cart').remove();
        }, 3000, $this);

        if (typeof pName === 'undefined' || pName === '') {
            pName = $this.closest('.product-item').find('.product-title a').text().trim();
        }

        if (typeof pName !== 'undefined' && pName !== '') {
            var string_start = pName.indexOf("“") + 1,
                string_end   = pName.indexOf("”"),
                pName        = string_start > 1 ? pName.slice(string_start, string_end) : pName;

            pName = '<span>' + pName + '</span>';
        } else {
            pName = '';
        }

        if ($img.length) {
            $img_html = '<figure><img src="' + $img.attr('src') + '"' + ' alt="' + pName + '" class="growl-thumb" /></figure>';
        }

        config.message = $img_html + '<p class="growl-content">' + pName + '' + $text_content + '</p>';

        $.growl.notice(config);
    };

    $(document).on('removed_from_cart', function (event, fragments, cart_hash, $thisbutton) {

        $thisbutton.ocolus_add_notify(
            ocolus_main_params.growl_notice.removed_cart_text
        );

    });

    $(document).on('added_to_cart', function (event, fragments, cart_hash, $thisbutton) {

        $thisbutton.ocolus_add_notify(
            ocolus_main_params.growl_notice.added_to_cart_text + '</br>' +
            '<a href="' + wc_add_to_cart_params.cart_url + '">' +
            wc_add_to_cart_params.i18n_view_cart + '</a>'
        );

    });

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

    $(document).on('added_to_wishlist', function (event, $thisbutton) {

        $thisbutton.ocolus_add_notify(
            ocolus_main_params.growl_notice.added_to_wishlist_text + '</br>' +
            '<a href="' + ocolus_main_params.growl_notice.wishlist_url + '">' +
            ocolus_main_params.growl_notice.browse_wishlist_text + '</a>'
        );

        $thisbutton.removeClass('loading');

    });

    $(document).on('click', function (event) {
        var _target = $(event.target).closest('#growls-default'),
            _parent = $('#growls-default');

        if (!_target.length) {
            $('.growl-close').trigger('click');
        }
    });

    // HOVER PRODUCT
    $.fn.ocolus_hover_product      = function () {
        if ($(window).width() > 1200 && $(this).closest('.owl-slick').length && !$('body').hasClass('ocolus_is_mobile')) {
            $(this).each(function () {
                var _this = $(this),
                    _list = _this.closest('.slick-list');

                if (_this.hasClass('style-01')) {
                    _this.hover(
                        function (e) {
                            if (_this.hasClass('has-gallery') && _this.closest('.slick-slide').hasClass('first-slick')) {
                                _list.css({
                                    'padding': '15px 15px 70px 90px',
                                    'margin' : '-15px -15px -70px -90px',
                                });
                            } else {
                                _list.css({
                                    'padding': '15px 15px 70px',
                                    'margin' : '-15px -15px -70px',
                                });
                            }
                        }, function () {
                            _list.css({
                                'padding': '0',
                                'margin' : '0',
                            });
                        }
                    );
                }
                if (_this.hasClass('style-23') || _this.hasClass('style-24')) {
                    _this.hover(
                        function (e) {
                            _list.css({
                                'padding': '15px 15px 60px 16px',
                                'margin' : '-15px -15px -60px',
                            });
                        }, function () {
                            _list.css({
                                'padding': '0 0 0 1px',
                                'margin' : '0',
                            });
                        }
                    );
                }
                if (_this.hasClass('style-29')) {
                    _this.hover(
                        function (e) {
                            _list.css({
                                'padding-bottom': '120px',
                                'margin-bottom' : '-120px',
                            });
                        }, function () {
                            _list.css({
                                'padding-bottom': '0',
                                'margin-bottom' : '0',
                            });
                        }
                    );
                }
            });
        }
    };
    // HOVER PRODUCT
    $.fn.ocolus_hover_slide        = function () {
        if ($(window).width() > 1200 && $(this).closest('.owl-slick').length && !$('body').hasClass('ocolus_is_mobile')) {
            $(this).each(function () {
                var _this = $(this),
                    _list = _this.closest('.slick-list');

                _this.hover(
                    function (e) {
                        _list.css({
                            'padding': '30px',
                            'margin' : '-30px',
                        });
                    }, function () {
                        _list.css({
                            'padding': '0',
                            'margin' : '0',
                        });
                    }
                );
            });
        }
    };
    $.fn.ocolus_hover_zoom_product = function () {
        if (ocolus_main_params.products_hover === 'zoom' && $.fn.zoom) {
            $(this).each(function () {
                var zoomTarget = $(this).find('.primary-thumb'),
                    zoomImg    = zoomTarget.data('image');

                zoomTarget.zoom({url: zoomImg});
            });
        }
    }
    $.fn.ocolus_zoom_product       = function () {
        if ($(this).find('.woocommerce-product-gallery.has-gallery').hasClass('has-gallery') && $.fn.zoom) {
            $(this).find('.woocommerce-product-gallery.has-gallery .woocommerce-product-gallery__image').each(function () {
                var zoomTarget = $(this),
                    zoomImg    = zoomTarget.find('a').attr('href');

                if (zoomTarget.hasClass('flex-active-slide')) {
                    zoomTarget.trigger('zoom.destroy');
                }
                zoomTarget.zoom({url: zoomImg});
            });
        }
    }
    $.fn.ocolus_bootstrap_tooltip  = function () {
        $(this).each(function () {
            var _this      = $(this),
                _placement = 'top',
                _product   = _this.closest('.product-item'),
                _text      = _this.text();

            if (
                _product.hasClass('style-11') ||
                _product.hasClass('style-12')
            ) {
                return false;
            }
            if (!_this.closest('.add-to-cart').length && _product.length) {
                if (
                    _product.hasClass('style-01') ||
                    _product.hasClass('style-06') ||
                    _product.hasClass('style-04') ||
                    _product.hasClass('style-22')
                ) {
                    _placement = 'left';
                }
            }
            _this.tooltip({
                trigger  : 'hover',
                placement: _placement,
                container: 'body',
                title    : _text,
            })
        });
    }
    // accordion
    $(document).on('click', function (event) {
        var _target = $(event.target).closest('.accordion-toggle'),
            _parent = $('.accordion-toggle');

        if (_target.length) {
            _parent.not(_target).children('.accordion-content').slideUp('500');
            if ($(event.target).is('[data-accordion="accordion-toggle"]') ||
                $(event.target).closest('[data-accordion="accordion-toggle"]').length) {
                _target.children('.accordion-content').slideToggle('500');
                event.preventDefault();
            }
        } else {
            $('.ocolus-dropdown').children('.accordion-content').slideUp('500');
        }
    });

    $(document).on('qv_loader_stop', function (event) {
        var _modal = $('#yith-quick-view-modal');
        if (_modal.find('.flex-control-thumbs').length > 0) {
            _modal.find('.flex-control-thumbs').ocolus_init_carousel();
        }
    });
    $(document).on('updated_wc_div', function (event) {
        if ($(event.target).find('.cross-sells .owl-slick').length > 0) {
            $(event.target).find('.cross-sells .owl-slick').ocolus_init_carousel();
        }
    });
    $(document).on('wc_fragments_refreshed wc_fragments_loaded', function () {
        if ($('.woocommerce-mini-cart').length && isMobile === null && $.fn.scrollbar) {
            $('.woocommerce-mini-cart').scrollbar();
        }
    });
    $(window).on('scroll', function () {
        if ($(window).scrollTop() > 400) {
            $('.backtotop').addClass('show');
        } else {
            $('.backtotop').removeClass('show');
        }
    });
    $(window).on('resize', function () {
        if ($('.product-item.style-01').length) {
            $('.product-item.style-01').ocolus_hover_product();
        }
        if ($('.product-item.style-23').length) {
            $('.product-item.style-23').ocolus_hover_product();
        }
        if ($('.product-item.style-24').length) {
            $('.product-item.style-24').ocolus_hover_product();
        }
        if ($('.product-item.style-29').length) {
            $('.product-item.style-29').ocolus_hover_product();
        }
        if ($('.product-item.style-07').length) {
            $('.product-item.style-07').ocolus_hover_slide();
        }
        if ($('.product-item.style-16').length) {
            $('.product-item.style-16').ocolus_hover_slide();
        }
        if ($('.blog-item.style-08').length) {
            $('.blog-item.style-08').ocolus_hover_slide();
        }
    });
    $(document).on('change click', '.coupon-options', function () {
        var _this = $(this),
            _wrap = _this.closest('.coupon-code');

        _this.find('option').each(function () {
            var _val = $(this).data('excerpt');

            if ($(this).is(':selected')) {
                if (_wrap.find('.coupon-excerpt').length) {
                    _wrap.find('.coupon-excerpt').html(_val);
                } else {
                    _wrap.append('<p class="coupon-excerpt">' + _val + '</p>');
                }
            }
        });
    });
    $(document).on('click', '.site-content.desc_03 .woocommerce-tabs .tabs-desc', function (e) {
        $(this).closest('li')
               .toggleClass('active')
               .find('.woocommerce-Tabs-panel').slideToggle();
        e.preventDefault();
    });
    $(document).on('click', '.canvas-close, .overlay-body', function (e) {
        $('.header').removeClass('open');
        $('body').removeClass('active-overlay');
        e.preventDefault();
    });
    $(document).on('click', '.filter-close, .overlay-body', function (e) {
        $('.product-filter').removeClass('open');
        $('body').removeClass('active-overlay');
        e.preventDefault();
    });
    $(document).on('click', '.menu-item .caret', function (e) {
        e.preventDefault();
        $(this).closest('.menu-item')
               .toggleClass('show-sub')
               .children('.sub-menu')
               .slideToggle('slow');
    });
    $(document).on('found_variation', function (event, variation) {
        if ($(variation.price_html).length) {
            $(event.target).closest('.product-item').find('.price').replaceWith(variation.price_html);
        }
        if ($(event.target).closest('.product-item').find('.thumb-link.zoom').length) {
            $(event.target).closest('.product-item').find('img.zoomImg').attr('src', variation.image.full_src);
        }
    });
    $(document).on('click', '.ocolus-head-account .form-tab-account', function (e) {
        var _this    = $(this),
            _content = _this.closest('.woocommerce');

        _this.addClass('active').siblings().removeClass('active');
        if (_this.hasClass('register')) {
            _content.find('.u-column2').fadeIn(400).siblings().fadeOut(400);
        } else {
            _content.find('.u-column1').fadeIn(400).siblings().fadeOut(400);
        }
        e.preventDefault();
    });
    $(document).on('click', '.tagcloud .view-all', function (e) {
        $(this).closest('.tagcloud').find('a').css('display', 'inline-block');
        $(this).remove();
        e.preventDefault();
    });
    $(document).on('click', '.button-size-chart', function (e) {
        $('#chart-button').trigger('click');
        e.preventDefault();
    });
    $(document).ajaxComplete(function (event, xhr) {
        if (xhr.status == 200 && xhr.responseText) {
            if ($(event.target).find('.lazy').length) {
                $(event.target).find('.lazy').ocolus_init_lazy_load();
            }
        }
    });

    $(document).on('wc-product-gallery-after-init', function (event, gallery, params) {
        if ($(this).find('.flex-control-thumbs').length) {
            $(this).find('.flex-control-thumbs').ocolus_init_carousel();
        }
    });

    $('.block-search .category select').chosen();

    window.addEventListener("load", function load() {
        /**
         * remove listener, no longer needed
         * */
        window.removeEventListener("load", load, false);
        /**
         * start functions
         * */
        if ($('.owl-slick').length) {
            $('.owl-slick').ocolus_init_carousel();
        }
        if ($('.equal-container.better-height').length) {
            $('.equal-container.better-height').ocolus_better_equal_elems();
        }
        if ($('.pagination-nav .button-loadmore').length) {
            $('.pagination-nav .button-loadmore').ocolus_load_post();
        }
        if ($('.scroll-percent span.percent').length) {
            $('.scroll-percent span.percent').ocolus_scroll_percent();
        }
        if ($('.ocolus-message-to-comment').length) {
            $('.ocolus-message-to-comment').ocolus_goto_comment();
        }
        if ($('.block-nav-category').length) {
            $('.block-nav-category').ocolus_vertical_menu();
        }
        if ($('.lazy').length) {
            $('.lazy').ocolus_init_lazy_load();
        }
        if ($('.product-item').length) {
            $('.product-item').ocolus_hover_zoom_product();
        }
        if ($('.gallery_grid,.sticky_info').length) {
            $('.gallery_grid ,.sticky_info').ocolus_zoom_product();
        }
        /**
         * check not mobile
         * */
        if (isMobile === null) {
            if ($('.header-sticky').length && $(window).width() > 1024) {
                $('.header-sticky').ocolus_sticky_header();
            }
            if ($('.product-item.style-01').length) {
                $('.product-item.style-01').ocolus_hover_product();
            }
            if ($('.product-item.style-23').length) {
                $('.product-item.style-23').ocolus_hover_product();
            }
            if ($('.product-item.style-24').length) {
                $('.product-item.style-24').ocolus_hover_product();
            }
            if ($('.product-item.style-29').length) {
                $('.product-item.style-29').ocolus_hover_product();
            }
            if ($('.product-item.style-07').length) {
                $('.product-item.style-07').ocolus_hover_slide();
            }
            if ($('.product-item.style-16').length) {
                $('.product-item.style-16').ocolus_hover_slide();
            }
            if ($('.blog-item.style-08').length) {
                $('.blog-item.style-08').ocolus_hover_slide();
            }
            if ($('.yith-wcqv-button,.compare-button a.compare,.yith-wcwl-add-to-wishlist a').length) {
                $('.yith-wcqv-button,.compare-button a.compare,.yith-wcwl-add-to-wishlist a').ocolus_bootstrap_tooltip();
            }
            /* SCROLLBAR */
            if ($.fn.scrollbar) {
                if ($('.widget_product_categories > ul').length) {
                    $('.widget_product_categories > ul').scrollbar();
                }
                if ($('.widget_layered_nav > ul').length) {
                    $('.widget_layered_nav > ul').scrollbar();
                }
                if ($('.woocommerce-mini-cart').length) {
                    $('.woocommerce-mini-cart').scrollbar();
                }
                if ($('.widget_categories > ul').length) {
                    $('.widget_categories > ul').scrollbar();
                }
                if ($('.shop-before-control .filter-content > .widget-area').length) {
                    $('.shop-before-control .filter-content > .widget-area').scrollbar();
                }
                if ($('.header-canvas > .widget-area').length) {
                    $('.header-canvas > .widget-area').scrollbar();
                }
                if ($('.instant-search-box .chosen-results').length) {
                    $('.instant-search-box .chosen-results').scrollbar();
                }
            }
        }
    }, false);

})(window.jQuery);