jQuery(document).ready(function ($) {
    "use strict";

    var $body = $('body'),
        has_rtl = $body.hasClass('rtl');

    function draly_dropshipping_starter_vertical_menu($elem) {
        var _blockTitle = $elem.find('.block-title');
         _blockTitle.on('click', function (e) {
            e.preventDefault();
            $(this).toggleClass('active');
            $(this).parent().toggleClass('has-open');
        });
    }
    if ($('.block-nav-category').length) {
        draly_dropshipping_starter_vertical_menu($('.block-nav-category'));
    }
    
    $('.header .menu-item > a, .vertical-wrapper.block-nav-category .block-title').on('focus', function () {
        var $anchor = $(this);

        $('.focus').each(function () {
            var $el = $(this);
            if (!$el.has($anchor).length) {
                $el.removeClass('focus');
            }
        });

        $anchor.parent().addClass('focus');
    });

    $(document).on('keydown', '.header-mobile-menu, .block-user .sub-menu, .block-minicart .widget_shopping_cart, .header-search.draly-dropdown .block-search', function (e) {
        const $menu = $(this),
              $dropdown = $(this).closest('.draly-dropdown');
        if (e.key === 'Escape') {
            $menu.removeClass('open');
            if($dropdown.length) {
                $dropdown.removeClass('open');
            }
        }
        if (e.key === 'Tab') {
            const $focusable = $menu.find('a, input, button').filter(':visible');
            const first = $focusable.first()[0];
            const last = $focusable.last()[0];
            const active = document.activeElement;

            if (e.shiftKey) {
                if (active === first) {
                    e.preventDefault();
                    $(last).focus();
                }
            }
            else {
                if (active === last) {
                    e.preventDefault();
                    $(first).focus();
                }
            }
        }
    });

    $(document).on("click", ".mobile-menu-toggle", function(e) {
        e.preventDefault();
        $('.header-mobile-menu').toggleClass('open');
    });

    function draly_dropshipping_starter_menu_caret() {
        $('.draly-nav').each(function () {
            var _main = $(this);
            _main.children('.menu-item.menu-item-has-children').each(function () {
                var curent = $(this).find('.sub-menu');
                curent.before('<a href="#" class="caret"></a>');
            });
        });
    }

    if ($('.draly-nav').length) {
        draly_dropshipping_starter_menu_caret();
    }

    $(document).on("click", ".main-menu-tab", function (e) {
        e.preventDefault();
        $(this).addClass('active');
        $('#main-menu-tab').addClass('active');
        $('.vertical-menu-tab, #vertical-menu-tab').removeClass('active');
    });

    $(document).on("click", ".vertical-menu-tab", function () {
        $(this).addClass('active');
        $('#vertical-menu-tab').addClass('active');
        $('.main-menu-tab, #main-menu-tab').removeClass('active');
    });

    $(document).on("click", ".mobile-menu-clone .caret", function () {
        let $this = $(this);
        let titleText = $this.siblings("a").text();
        let $menuItem = $this.closest(".menu-item");
        let $subMenu = $this.closest(".sub-menu");
        let $mobileMenuTitle = $this.closest(".mobile-menu-inner").siblings(".mobile-menu-title");
        $menuItem.toggleClass("show-sub-menu");
        $mobileMenuTitle.addClass('active');
        if($this.hasClass("active")) {
            if($subMenu.length) {
                titleText = $subMenu.siblings("a").text();
            } else {
                $mobileMenuTitle.removeClass('active');
            }
        }
        $mobileMenuTitle.text(titleText);
        $this.toggleClass("active");
    });

    function draly_dropshipping_starter_clone_menu(sourceSelector, targetSelector) {
        let $menu = $(sourceSelector).first();
        if ($menu.length && !$(targetSelector + ' .mobile-menu-clone').length) {
            let $clone = $menu.clone(false);
            $clone.removeAttr('id');
            $clone.find('.menu-item[id]').removeAttr('id');

            $(targetSelector).append(
                $('<div class="mobile-menu-clone"></div>').append($clone)
            );
        }
    }
    draly_dropshipping_starter_clone_menu('.draly-nav.main-menu', '#main-mobile-menu');
    draly_dropshipping_starter_clone_menu('.draly-nav.vertical-menu', '#vertical-mobile-menu');

    function draly_dropshipping_starter_animation_tabs($elem, _tab_animated) {
        _tab_animated = (_tab_animated == undefined || _tab_animated == "") ? '' : _tab_animated;
        if (_tab_animated == "") {
            return;
        }
        $elem.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);
            });
        });
    }

    function draly_dropshipping_starter_init_carousel($elem) {
        $elem.not('.slick-initialized').each(function () {
            var _this = $(this),
                _responsive = _this.data('responsive'),
                _config = [];

            if (has_rtl) {
                _config.rtl = true;
            }
            if (_this.hasClass('slick-vertical')) {
                _config.prevArrow = '<span class="fa fa-angle-up prev"></span>';
                _config.nextArrow = '<span class="fa fa-angle-down next"></span>';
            } else {
                _config.prevArrow = '<span class="prev"><svg width="10" height="20" viewBox="0 0 10 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9 1L1.59055 9.33564C1.25376 9.71452 1.25376 10.2855 1.59055 10.6644L9 19" stroke="currentColor" stroke-linecap="round"/></svg></span>';
                _config.nextArrow = '<span class="next"><svg width="10" height="20" viewBox="0 0 10 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L8.40945 9.33564C8.74624 9.71452 8.74624 10.2855 8.40945 10.6644L1 19" stroke="currentColor" stroke-linecap="round"/></svg></span>';
            }
            _config.responsive = _responsive;

            _this.slick(_config);
        });
    }
    function draly_dropshipping_starter_product_thumb($elem) {
        $elem.on('draly_dropshipping_starter_product_thumb', function () {
            $elem.not('.slick-initialized').each(function () {
                var _this = $(this),
                    _responsive = JSON.parse(draly_dropshipping_starter_global_frontend.data_responsive),
                    _config = JSON.parse(draly_dropshipping_starter_global_frontend.data_slick);
                if ($('.vertical_thumbnail').length > 0) {
                    _config.vertical = true;
                }
                if (has_rtl) {
                    _config.rtl = true;
                }
                _config.infinite = false;
                _config.prevArrow = '<span class="fa fa-angle-left prev"></span>';
                _config.nextArrow = '<span class="fa fa-angle-right next"></span>';
                _config.responsive = _responsive;

                _this.slick(_config);
            });
        }).trigger('draly_dropshipping_starter_product_thumb');
    }

    function draly_dropshipping_starter_countdown($elem) {
        $elem.on('draly_dropshipping_starter_countdown', function () {
            $elem.each(function () {
                var _this = $(this);
                _this.countdown(_this.data('datetime'), function (event) {
                    var _text_countdown = event.strftime(
                        '<span class="days"><span class="number">%D</span><span class="text">' + draly_dropshipping_starter_global_frontend.countdown_day + '</span></span>' +
                        '<span class="hour"><span class="number">%H</span><span class="text">' + draly_dropshipping_starter_global_frontend.countdown_hrs + '</span></span>' +
                        '<span class="mins"><span class="number">%M</span><span class="text">' + draly_dropshipping_starter_global_frontend.countdown_mins + '</span></span>' +
                        '<span class="secs"><span class="number">%S</span><span class="text">' + draly_dropshipping_starter_global_frontend.countdown_secs + '</span></span>'
                    );
                    _this.html(_text_countdown);
                });
            });
        }).trigger('draly_dropshipping_starter_countdown');
    }
    if($('.contain-left.sticky_detail .entry-summary').length > 0) {
        $('.contain-left.sticky_detail .entry-summary').theiaStickySidebar({
            additionalMarginTop: 50
        });
    }
    function draly_dropshipping_starter_update_wishlist_count() {
        jQuery.ajax({
            url: yith_wcwl_l10n.ajax_url,
            data: {
                action: 'draly_dropshipping_starter_update_wishlist_count'
            },
            dataType: 'json',
            success: function(response) {
                if (response.count !== undefined) {
                    jQuery('.block-wishlist .count').text(response.count);
                }
            }
        });
    }

    $(document).on('added_to_wishlist removed_from_wishlist', function() {
        draly_dropshipping_starter_update_wishlist_count();
    });

    // draly_dropshipping_starter_dropdown
    $(document).on('click', function (event) {
        var _target = $(event.target).closest('.draly-dropdown'),
            _parent = $('.draly-dropdown');

        if (_target.length > 0) {
            _parent.not(_target).removeClass('open');
            if (
                $(event.target).is('[data-draly="draly-dropdown"]') ||
                $(event.target).closest('[data-draly="draly-dropdown"]').length > 0
            ) {
                _target.toggleClass('open');
                event.preventDefault();
            }
        } else {
            $('.draly-dropdown').removeClass('open');
        }
    });

    // category product
    function draly_dropshipping_starter_category_product($elem) {
        $elem.each(function () {
            var _main = $(this);
            _main.find('.cat-parent').each(function () {
                if ($(this).hasClass('current-cat-parent')) {
                    $(this).addClass('show-sub');
                    $(this).children('.children').stop().slideDown(300);
                }
                $(this).children('.children').before('<span class="carets"></span>');
            });
            _main.children('.cat-parent').each(function () {
                var curent = $(this).find('.children');
                $(this).children('.carets').on('click', function () {
                    $(this).parent().toggleClass('show-sub');
                    $(this).parent().children('.children').stop().slideToggle(300);
                    _main.find('.children').not(curent).stop().slideUp(300);
                    _main.find('.cat-parent').not($(this).parent()).removeClass('show-sub');
                });
                var next_curent = $(this).find('.children');
                next_curent.children('.cat-parent').each(function () {
                    var child_curent = $(this).find('.children');
                    $(this).children('.carets').on('click', function () {
                        $(this).parent().toggleClass('show-sub');
                        $(this).parent().parent().find('.cat-parent').not($(this).parent()).removeClass('show-sub');
                        $(this).parent().parent().find('.children').not(child_curent).stop().slideUp(300);
                        $(this).parent().children('.children').stop().slideToggle(300);
                    })
                });
            });
        });
    }

    // Draly Ajax Tabs
    $(document).on('click', '.draly-tabs .tab-link a', function (e) {
        e.preventDefault();
        var _this = $(this),
            _tabID = _this.attr('href'),
            _data_section = _this.data('section'),
            _tab_link = _this.closest('.tab-link'),
            _ajax_tabs = _tab_link.data('ajax'),
            _data_general = _tab_link.data('general'),
            _data_slick = JSON.stringify(_tab_link.data('slick')),
            _data_responsive = JSON.stringify(_tab_link.data('responsive')),
            _tab_animated = _tab_link.data('animate'),
            _draly_dropshipping_starter_tabs = _this.closest('.draly-tabs');
        if (_ajax_tabs == 'yes' && !_this.hasClass('loaded') && !_draly_dropshipping_starter_tabs.hasClass('loading')) {
            _draly_dropshipping_starter_tabs.addClass('loading');
            _this.parent().addClass('active').siblings().removeClass('active');
            $.ajax({
                type: 'POST',
                url: draly_dropshipping_starter_ajax_frontend.ajaxurl,
                data: {
                    action: 'draly_dropshipping_starter_ajax_tabs',
                    security: draly_dropshipping_starter_ajax_frontend.security,
                    data_general: _data_general,
                    data_slick: _data_slick,
                    data_responsive: _data_responsive,
                    data_section: _data_section,
                },
                success: function (response) {
                    if (response['success'] == 'ok') {
                        $(_tabID).html(response['html']);
                        if (window.wp && window.wp.hooks) {
                           window.wp.hooks.doAction('yith_wcwl_init_add_to_wishlist_components');
                        }
                        draly_dropshipping_starter_init_carousel($(_tabID).find('.owl-slick'));
                        _this.addClass('loaded');
                    } else {
                        $(_tabID).html('<strong>Error: Can not Load Data ...</strong>');
                    }
                },
                complete: function () {
                    $(_tabID).addClass('active').siblings().removeClass('active');
                    _draly_dropshipping_starter_tabs.removeClass('loading');
                    setTimeout(function (args) {
                        draly_dropshipping_starter_animation_tabs($(_tabID), _tab_animated);
                    }, 10);
                }
            });
        } else {
            _this.parent().addClass('active').siblings().removeClass('active');
            $(_tabID).addClass('active').siblings().removeClass('active');
            draly_dropshipping_starter_animation_tabs($(_tabID), _tab_animated);
        }
    });

    $(document).on('click', '#backtotop', function (e) {
        $('html, body').animate({scrollTop: 0}, 800);
        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('change', '.mini-cart-qty-form .input-qty', function() {
        $('.widget_shopping_cart').addClass('loading');
        let qty = $(this).val();
        let cartItemKey = $(this).closest('.mini-cart-qty-form').data('cart-item-key');
        $.ajax({
            url: draly_dropshipping_starter_ajax_frontend.ajaxurl,
            type: 'POST',
            data: {
                action: 'draly_dropshipping_starter_update_mini_cart_qty',
                cart_item_key: cartItemKey,
                quantity: qty
            },
            success: function(response) {
                $(document.body).trigger('wc_fragment_refresh');
            },
            complete: function() {
                 $('.widget_shopping_cart').removeClass('loading');
            }
        });
    });

    $(document.body).on('added_to_cart', function (evt, fragments, cart_hash, btn) {
        let img_product = btn.closest('.product-item').find('.product-thumb img'),
            cart_icon = $('.draly-sidebar-cart-icon-wrap');
            img_product = $(img_product);
        if ($(img_product).length && cart_icon.length) {
            let img_product_wrap, img_top, img_left, img_width, img_height,
                cart_icon_top = cart_icon.offset().top,
                cart_icon_left = cart_icon.offset().left;
            img_top = img_product.offset().top;
            img_left = img_product.offset().left;
            img_width = img_product.width();
            img_height = img_product.height();
            $('.draly-img-flying').remove();
            $('body').append('<div class="draly-img-flying"></div>');
            let img_flying = $('div.draly-img-flying');
            img_product.clone().appendTo(img_flying);
            img_flying.css({
                'top': img_top + 'px',
                'left': img_left + 'px',
                'width': img_width + 'px',
                'height': img_height + 'px'
            }).fadeIn("slow");
            img_flying.animate({
                'width': (img_width * 0.6) + 'px',
                'height': (img_height * 0.6) + 'px',
                top: '+=' + (img_height * 0.2) + 'px',
                left: '+=' + (img_width * 0.2) + 'px'
            }, 400, 'swing', function () {
                img_flying.animate({
                    top: cart_icon_top + 'px',
                    left: cart_icon_left + 'px',
                    height: '18px',
                    width: '25px'
                }, 800, "swing", function () {
                    $('div.draly-img-flying').fadeIn('fast', function () {
                        $('div.draly-img-flying').remove();
                    });
                });
            });
        }
    });

    function draly_dropshipping_starter_product_gallery($elem) {
        $elem.each(function () {
            var _items = $(this).closest('.product-inner').data('items'),
                _main_slide = $(this).find('.product-gallery-slick'),
                _dot_slide = $(this).find('.gallery-dots');

            _main_slide.not('.slick-initialized').each(function () {
                var _this = $(this),
                    _config = [];

                if ($('body').hasClass('rtl')) {
                    _config.rtl = true;
                }
                _config.prevArrow = '<span class="fa fa-angle-left prev"></span>';
                _config.nextArrow = '<span class="fa fa-angle-right next"></span>';
                _config.cssEase = 'linear';
                _config.infinite = false;
                _config.fade = true;
                _config.slidesMargin = 0;
                _config.arrows = false;
                _config.asNavFor = _dot_slide;
                _this.slick(_config);
            });
            _dot_slide.not('.slick-initialized').each(function () {
                var _config = [];
                if ($('body').hasClass('rtl')) {
                    _config.rtl = true;
                }
                _config.slidesToShow = _items;
                _config.infinite = false;
                _config.focusOnSelect = true;
                _config.vertical = true;
                _config.slidesMargin = 8;
                _config.prevArrow = '<span class="fa fa-angle-up prev"></span>';
                _config.nextArrow = '<span class="fa fa-angle-down next"></span>';
                _config.asNavFor = _main_slide;
                _config.responsive = [
                    {
                        breakpoint: 992,
                        settings: {
                            vertical: false,
                            slidesMargin: 8,
                            prevArrow: '<span class="fa fa-angle-left prev"></span>',
                            nextArrow: '<span class="fa fa-angle-right next"></span>',
                        }
                    }
                ];
                $(this).slick(_config);
            })
        })
    }

    if ($('.vertical-wrapper .vertical-menu').length > 0) {
        $('.vertical-wrapper .vertical-menu').scrollbar();
    }
    if ($('.product-list-scroll').length > 0) {
        $('.product-list-scroll').scrollbar();
    }

    setTimeout(function () {
        if ($('.owl-slick').length) {
            $('.owl-slick').each(function () {
                draly_dropshipping_starter_init_carousel($(this));
            });
         }
        if ($('.product-gallery').length) {
            draly_dropshipping_starter_product_gallery($('.product-gallery'));
        }
        if ($('.flex-control-thumbs').length) {
            draly_dropshipping_starter_product_thumb($('.flex-control-thumbs'));
        }
        if ($('.block-minicart .cart_list').length > 0) {
            $('.block-minicart .cart_list').scrollbar();
        }
    }, 10);

     if (window.elementorFrontend) {
        window.elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope){
            if ($('.owl-slick').length) {
                draly_dropshipping_starter_init_carousel($scope.find('.owl-slick'));
            }
            if ($('.product-gallery').length) {
                draly_dropshipping_starter_product_gallery($scope.find('.product-gallery'));
            }
        });
    }

    if ($('.draly-countdown').length) {
        draly_dropshipping_starter_countdown($('.draly-countdown'));
    }
    if ($('.category-search-option').length) {
        $('.category-search-option').chosen();
    }

    // Window load
    $(window).load(function () {
        if ($('.widget_product_categories .product-categories').length) {
            draly_dropshipping_starter_category_product($('.widget_product_categories .product-categories'));
        }
    });
    // AJAX completed
    $(document).ajaxComplete(function (event, xhr, settings) {
        if ($('.block-minicart .cart_list').length > 0 && $.fn.scrollbar) {
            $('.block-minicart .cart_list').scrollbar();
        }
    });
});

jQuery(window).on('load', function() {
  jQuery('body').addClass('loaded');
});