jQuery(function ($) {
	'use strict'  
	// if( $('#main_slider').length ){	
	$('#main_slider').owlCarousel({
        loop: true,
        margin: 0,
        nav: true,
        dots: false,
		items: 1,
        autoplayHoverPause:true,
        autoplay: true,
		autoplayTimeout: 10000,
        navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"]
    });
	
	$("[data-delay]").each(function () {
		var anim_del = $(this).data('delay');
		$(this).css('animation-delay', anim_del);
	});
	$("[data-duration]").each(function () {
		var anim_dur = $(this).data('duration');
		$(this).css('animation-duration', anim_dur);
	});
// }
    
	var product = $('.categories-inner').owlCarousel({
		loop: true,
		margin: 30,
		dots: false,
		nav: false,
		autoplay: true,
		autoplaySpeed: 9000,
		slideTransition: "linear",
		autoplayTimeout: 9000,
		responsive: {
			0: {
				items: 1
			},
			600: {
				items: 2
			},
			768: {
				items: 3
			},
			992: {
				items: 4
			},
			1200: {
				items: 5
			}

		}
	});

    $('#testimonials2').owlCarousel({
        loop: true,
        margin: 0,
        nav: true,
        dots: true,
        autoplayHoverPause: true,
        autoplay: true,
        navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 1
            },
            1000: {
                items: 1
            }
        }
    });

    $('#testimonial4').owlCarousel({
        loop: true,
        margin: 0,
        nav: true,
        dots: false,
        autoplayHoverPause: true,
        autoplay: true,
        navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 1
            },
            1000: {
                items: 1
            }
        }
    });


    $('#singleproduct').owlCarousel({
        loop: true,
        margin: 0,
        nav: true,
        dots: false,
        autoplayHoverPause: true,
        autoplay: true,
        navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
        responsive: {
            0: {
                items: 4
            },
            600: {
                items: 3
            },
            1000: {
                items: 4
            }
        }
    });



    // sidebar testimonial
    $('.testimonial_wrap,.sale_wrap').owlCarousel({
        loop: true,
        margin: 0,
        nav: false,
        dots: true,
        autoplayHoverPause: true,
        autoplay: true,
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 1
            },
            1000: {
                items: 1
            }
        }
    });


    $('#besttmonial').owlCarousel({
        loop: true,
        margin: 10,
        nav: false,
        dots: true,
        autoplayHoverPause: true,
        autoplay: true,
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 1
            },
            1000: {
                items: 1
            }
        }
    });


    $('.newsflash').owlCarousel({
        loop: true,
        margin: 10,
        nav: false,
        dots: false,
        touchDrag: false,
        mouseDrag: false,
        autoplayHoverPause: true,
        autoplay: true,
        animateOut: 'slideOutDown',
        animateIn: 'slideInDown',
        autoplayTimeout: 2000,
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 1
            },
            1000: {
                items: 1
            }
        }
    });

    // mobilemenu-switcher tab
    $(".switcher-tab > button").click(function (e) {
        if (!$(this).hasClass("active-bg")) {
            $(".product-categories,.main-mobile-wrapper .main-menu.menu-wrap").toggleClass("d-none");
            $(this).parent().children().toggleClass("active-bg");
        }
    });

    // mobile-menu switcher
    $('.main-mobile-build, .widget_nav_menu').find('a').on('focus blur', function () {
        $(this).parents('ul, li').toggleClass('focus');
    });

    // mobile-menu trap
    $(".menu-collapse-wrap").on("click", function () {
        // $("body").addClass("header-menu-active");
        // startTrap($('.main-mobile-wrapper'));
    });
    

    $(".header-above-collapse").click(function () {
        $(".header-above-bar").css({
            "top": "92px"
        }).slideToggle();
    });


    // mobile menu toggle 
    $(".menu-collapse-wrap").click(function () {
        $(".main-mobile-wrapper").css({
            "transform": "translateX(0%)",
            "visibility": "visible"
        });
        startTrap($('.main-mobile-wrapper'));
    });

    // mobile footer menu
    $("#footer-bottom-category").click(function () {
        $(".main-mobile-wrapper").css({
            "transform": "translateX(0%)",
            "visibility": "visible"
        });
    });

function mobile_menu_close() {
    if ($(window).width() <= 991) {
        $(".header-close-menu").click(function() {
		// alert('whooo');
          $(".main-mobile-wrapper").css({
            "transform": "translateX(-150%)",
            "visibility": "hidden"
          });
        });
      }
}	  
	  mobile_menu_close();
	  $(window).resize(function(){ mobile_menu_close(); });

    // mobile footer search style
    $("#bottom-search-area").click(function () {
        $(".navigation-middle-row").css({
            "transform": "translateX(0%)",
            "visibility": "visible"
        });
    });

    // mobile footer search close style
        $(".header-search-form .close-style").click(function () {
            $(".navigation-middle-row").css({
                "transform": "translateX(150%)",
                "visibility": "hidden"
            });
        });


    // Search TRAP
    var searchTrap = function (elem) {
        let tabbable = elem.find('select, input, textarea, button, a,button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])').filter(':visible');
        let firstTabbable = tabbable.first();
        let lastTabbable = tabbable.last();
        // /set focus on first input/
        console.log(lastTabbable)
        firstTabbable.focus();
        //redirect last tab to first input/
        lastTabbable.on('keydown', function (e) {
            if ((e.which === 9 && !e.shiftKey)) {
                e.preventDefault();
                firstTabbable.focus();
            }
        });
        //redirect first shift+tab to last input/
        firstTabbable.on('keydown', function (e) {
            if ((e.which === 9 && e.shiftKey)) {
                e.preventDefault();
                lastTabbable.focus();
            }
        });
    };

    // header search
    $(document).on('click', '.search-magnifier .search-btn, #bottom-search-area', function (e) {
        $("body").addClass('header-search-active');
        $("body").addClass("overlay-enabled");
        searchTrap($('.header-search-popup'));
    });
    // header search
    $(".menu-right-list .search-btn, #bottom-search-area").on("click", function () {
        $("body").addClass("header-search-active");
    });
    // header search close
    $(".header-search-close").click(function () {
        $("body").removeClass("header-search-active");
        $(".menu-right-list .search-btn, #bottom-search-area");
    });



    $('.cat-menu-bt').click(function (e) {
        e.preventDefault();
        startTrap($('.main-mobile-build'));
    });



    // Mobile Menu Browse Category
    var startTrap = function (elem) {
        var tabbable = elem.find('select, input, textarea, button, a, [href],[tabindex]:not([tabindex="-1"])').filter(':visible');

        var firstTabbable = tabbable.first();
        var lastTabbable = tabbable.last();

        $('.product-categories-list li:first-of-type a').focus();

        lastTabbable.on('keydown', function (e) {
            if ((e.which === 9 && !e.shiftKey)) {
                e.preventDefault();
                firstTabbable.focus();
            }
        });

        firstTabbable.on('keydown', function (e) {
            if ((e.which === 9 && e.shiftKey)) {
                e.preventDefault();
                lastTabbable.focus();
            }
        });

        elem.on('keyup', function (e) {
            if (e.keyCode === 27) {
                $(".header-close-menu").click();
            };
        });
    };

    $(window).on('load', function () {
        $('.preloader').fadeOut('3000');
    });




    // Sticky Header
    if ($(".is-sticky-on").length > 0) {
        $(window).on('scroll', function () {
            if ($(window).scrollTop() >= 250) {
                $('.is-sticky-on').addClass('is-sticky-menu');
            }
            else {
                $('.is-sticky-on').removeClass('is-sticky-menu');
            }
        });
    }

    $('.cat-menu-bt').click(function (e) {
        e.preventDefault();
        startTrap($('.main-mobile-build'));
    });


    $(".switcher-tab > button").click(function (e) {
        if (!$(this).hasClass("active-bg")) {
            $(".product-categories,#menu-primary-menu").toggleClass("d-none");
            $(this).parent().children().toggleClass("active-bg");
        }
    });

    $(".menu-item-has-children .mobile-collapsed > button").click(function (e) {
        $(this).parent().next().toggle();
        $(this).toggleClass("active-arrow");
    });


    $(".signin-close").click(function () {
        $(".signin-overlay ").hide();
    });

    $(".quickview-close").click(function () {
        $(".quickview-overlay").hide();
    });


    $(".quickview-trigger").click(function () {
        $(".quickview-overlay").show();
    });

    // water ripple animation
    $(".breadcrumb-area").ripples({
        resolution: 512,
        dropRadius: 20,
        // interactive: true,
        perturbance: 0.04,
    }); 

    // counter up
    $('.counter').counterUp({
        delay: 10,
        time: 1000,
    });

    // filter tab
    $(window).on('load', function () {
        var postFilter = $('.dt-filter-init');
        $.each(postFilter, function (index, value) {
            var el = $(this);
            var parentClass = $(this).parent().attr('class');
            var $selector = $('#' + el.attr('id'));
            $($selector).imagesLoaded(function () {
                var festivarMasonry = $($selector).isotope({
                    itemSelector: '.dt-filter-item',
                    percentPosition: true,
                    masonry: {
                        columnWidth: 0,
                        gutter: 0
                    }
                });
                $('.collapse').on('shown.bs.collapse hidden.bs.collapse', function () {
                    festivarMasonry.isotope('layout');
                });
                $(document).on('click', '.' + parentClass + ' .dt-tab-filter a', function () {
                    var filterValue = $(this).attr('data-filter');
                    festivarMasonry.isotope({
                        filter: filterValue,
                        animationOptions: {
                            duration: 450,
                            easing: "linear",
                            queue: false,
                        }
                    });
                    return false;
                });
            });
        });

        $(document).on('click', '.dt-tab-filter a', function () {
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
        });
        // debounce so filtering doesn't happen every millisecond

    });


    var btn = $('#scrollup');
    $(window).scroll(function () {
        if ($(window).scrollTop() > 300) {
            btn.addClass('show');
        } else {
            btn.removeClass('show');
        }
    });

    btn.on('click', function (e) {
        e.preventDefault();
        $('html, body').animate({ scrollTop: 0 }, '300');
    });


    // cooming soon Timer
   function initializeClock(id, endtime) {
        const clock = document.getElementById(id);
        const daysSpan = clock.querySelector('.days');
        const hoursSpan = clock.querySelector('.hours');
        const minutesSpan = clock.querySelector('.minutes');
        const secondsSpan = clock.querySelector('.seconds');

        function updateClock() {
            const t = getTimeRemaining(endtime);

            daysSpan.innerHTML = t.days;
            hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
            minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
            secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

            if (t.total <= 0) {
                clearInterval(timeinterval);
            }
        }

        updateClock();
        const timeinterval = setInterval(updateClock, 1000);
    }

	
	const deadline = jQuery('#clockdiv').attr("data-timer");
    if (deadline) {
        initializeClock('clockdiv', deadline);
    }

    
	// required elements
	var imgPopup = $('.img-popup');
	var imgCont = $('.gallery');
	var popupImage = $('.img-popup img');
	var closeBtn = $('.close-btn');

	// handle events
	imgCont.on('click', function () {
		var img_src = $(this).children('img').attr('src');
		imgPopup.children('img').attr('src', img_src);
		imgPopup.addClass('opened');
	});

	$(imgPopup, closeBtn).on('click', function () {
		imgPopup.removeClass('opened');
		imgPopup.children('img').attr('src', '');
	});

	popupImage.on('click', function (e) {
		e.stopPropagation();
	});

	$('.btn-on')
		.on('mouseenter', function (e) {
			var parentOffset = $(this).offset(),
				relX = e.pageX - parentOffset.left,
				relY = e.pageY - parentOffset.top;
			$(this).find('span').css({ top: relY, left: relX })
		})
		.on('mouseout', function (e) {
			var parentOffset = $(this).offset(),
				relX = e.pageX - parentOffset.left,
				relY = e.pageY - parentOffset.top;
			$(this).find('span').css({ top: relY, left: relX })
		});
    

    $('.cart-trigger').on('click', function (e) {
        e.preventDefault();
        if (!$('.cart-modal').hasClass("cart-active")) {
            // $(".main-header").css({"z-index":"1"});
            $('.cart-modal').addClass('cart-active');
            $('.cart-close').focus();
            var e, t, i, n = document.querySelector(".cart-modal");
            let a = document.querySelector(".cart-close"),
                s = n.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),
                o = s[s.length - 1];
            if (!n) return !1;
            for (t = 0, i = (e = n.getElementsByTagName("a")).length; t < i; t++) e[t].addEventListener("focus", c, !0), e[t].addEventListener("blur", c, !0);
            function c() {
                for (var e = this; - 1 === e.className.indexOf("cart-container");) "li" === e.tagName.toLowerCase() && (-1 !== e.className.indexOf("focus") ? e.className = e.className.replace(" focus", "") : e.className += " focus"), e = e.parentElement
            }
            document.addEventListener("keydown", function (e) {
                ("Tab" === e.key || 9 === e.keyCode) && (e.shiftKey ? document.activeElement === a && (o.focus(), e.preventDefault()) : document.activeElement === o && (a.focus(), e.preventDefault()))
            })
        }
        else {
            $('.cart-trigger').focus();
            $('.cart-modal').removeClass('cart-active');
            // $(".main-header").css({"z-index":"2"});
        }
    });

    $('.cart-close, .cart-overlay').on('click', function (e) {
        e.preventDefault();
        $('.cart-trigger').focus();
        $('.cart-modal').removeClass('cart-active');
        $(".main-header").css({ "z-index": "2" });
    });

    $('.signin-close').on('click', function (e) {
        e.preventDefault();
        $('.signin-close').focus();
        $('.signin-overlay').removeClass('active');
    });
    $('.cart-close, .cart-overlay').on('click', function (e) {
        e.preventDefault();
        $('.cart-trigger').focus();
        $('.cart-modal').removeClass('cart-active');
    });


    $(".wc-tabs li").click(function (e) {
        e.preventDefault();
        $(this).parent().siblings().hide();
        var get_id = $(this).attr("id");
        $(this).parent().siblings().filter(`[aria-labelledby*=${get_id}]`).show();
    });


    $(".product-category-btn").click(function () {
        $(".product-category-menus-list").slideToggle();
    });




    // footer menu bottom function
    $(".footer-mobile-menu a").each(function () {

        // Get current page URL
        var url = window.location.href;
        // remove # from URL
        url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
        // remove parameters from URL
        url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
        // select file name
        url = url.substr(url.lastIndexOf("/") + 1);
        // If file name not avilable
        if (url == '') {
            url = 'index.html';
        }

        // select href
        var href = $(this).attr('href');
        // console.log(href)
        // Check filename
        if (url == href) {

            $(this).addClass('hover-color');
            if ($(this).parent().attr("id") == "fix-3") {
                $(this).children().css("color", "#ffffff");
            } else {
                $(this).children().addClass('hover-color');

            }
        }
    });
	
	$(window).resize(function(){
	if ($(window).width() < 992) {
		$(".product-category-browse").removeClass("active modal-opened");
		$(".product-category-menus-list").slideUp();
		}	
	});
	
	$(window).on('scroll', function(){
		var stk_head = $(".main-navigation-area.is-sticky-on.is-sticky-menu").outerHeight();
		$(".container.is-sticky-on.is-sticky-menu").css("top",stk_head +'px');
	});


    // var category_limit		= MyAjax.category_limit;

    // if( $('.product-category-menus-list ul.main-menu').children().length >= category_limit ) {
    if ($('.product-category-menus-list ul.main-menu').children().length >= 6) {
        $(".product-category-menus-list").addClass("active");
        $(".product-category-menus-list ul.main-menu").append('<li class="menu-item more-item"><button type="button" class="browse-more"><i class="fa fa-plus"></i> <span>More Category</span></button></li>');
        // $(".product-category-menus-list > ul.main-menu > li:not(.more-item)").slice(0, category_limit).show();
        $(".product-category-menus-list > ul.main-menu > li:not(.more-item)").slice(0, 6).show();
        $(".browse-more").on('click', function (e) {
            if (!$(".browse-more").hasClass("active")) {
                $(".browse-more").addClass("active");
                $('.browse-more i').removeClass('fa-plus').addClass("fa-minus");
                $(".browse-more").animate({ display: "block" }, 500,
                    function () {
                        $(".product-category-menus-list > ul.main-menu > li:not(.more-item):hidden").addClass('actived').slideDown(200);
                        if ($(".product-category-menus-list > ul.main-menu > li:not(.more-item):hidden").length === 0) {
                            $(".browse-more").html('<i class="fa fa-minus"></i> <span>No More</span>');
                        }
                    }
                );
            } else {
                $(".browse-more").removeClass("active");
                $(".browse-more").animate({ display: "none" }, 500,
                    function () {
                        if ($(".product-category-menus-list > ul.main-menu > li:not(.more-item)").hasClass('actived')) {
                            // $(".product-category-menus-list > ul.main-menu > li:not(.more-item).actived").slice(0, category_limit).slideUp(200);
                            $(".product-category-menus-list > ul.main-menu > li:not(.more-item).actived").slice(0, 6).slideUp(200);
                            $(".browse-more").html('<i class="fa fa-plus"></i> <span>More Category</span>');
                        }
                    }
                );
            }
        });
    }


    // PRODUCT CATEGORIE FILTERS
    // filter tab
    $(window).on('load', function () {
        var postFilter = $('.product-filter-init');
        $.each(postFilter, function (index, value) {
            var el = $(this);
            var parentClass = $(this).parent().attr('class');
            // console.log(parentClass)
            var $selector = $('#' + el.attr('id'));
            $($selector).imagesLoaded(function () {
                var festivarMasonry = $($selector).isotope({
                    itemSelector: '.product-filter-item',
                    percentPosition: true,
                    masonry: {
                        columnWidth: 0,
                        gutter: 0
                    }
                });
                $('.collapse').on('shown.bs.collapse hidden.bs.collapse', function () {
                    festivarMasonry.isotope('layout');
                });
                $(document).on('click', '.' + parentClass + ' .product-tab-filter a', function () {
                    var filterValue = $(this).attr('product-filter');
                    festivarMasonry.isotope({
                        filter: filterValue,
                        animationOptions: {
                            duration: 450,
                            easing: "linear",
                            queue: false,
                        }
                    });
                    return false;
                });
            });
        });

        $(document).on('click', '.product-tab-filter a', function () {
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
        });
        // debounce so filtering doesn't happen every millisecond

    });  
	
	/* Product List + Grid */
	$(document).on('click', '.gridlist-toggle a', function () {
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
			var viewType = $(this).attr('id');
			
			// Get the <ul> element that holds the products
			var productsList = $('.products');
			
			// Update the class of the <ul> based on the clicked button
			if (viewType === 'grid') {
				productsList.removeClass('list').addClass('grid'); // Switch to grid view
			} else if (viewType === 'list') {
				productsList.removeClass('grid').addClass('list'); // Switch to list view
			}
        });

    // footer style update
        function footerContent() {
            let plus_icon = $("<span class='collaps'></span>").html("<i class='fa fa-plus-circle'></i>");
            let minus_icon = $("<span class='collapsd'></span>").html("<i class='fa fa-minus-circle'></i>");
            $(".footer_content_wrap").append(plus_icon, minus_icon);
            $(".footer_content_wrap > span").click(function(){
                if(!$(this).parents('.footer_content_wrap').hasClass('active')){
                    $(this).parents('.footer_content_wrap').addClass('active');
                    // $(this).parent().children('div,ul,form,img').slideDown();
                    $(this).parent().find('.widget-title').next().slideDown();
                    $(this).parent().find('.mejs-audio').slideDown();
                    $(this).parent().children(".widget-contact").slideDown();
                } else {
                    $(this).parents('.footer_content_wrap').removeClass('active');		
                    // $(this).parent().children('div,ul,form,img').slideUp();
                    $(this).parent().find('.widget-title').next().slideUp();
                    $(this).parent().find('.mejs-audio').slideUp();
                    $(this).parent().children(".widget-contact").slideUp();
                }
            });
            
            $(window).resize(function(){
            if($(this).width() > 767){
                $(".footer_content_wrap > span").parent().find('.widget-title').next().slideDown();
                $(".footer_content_wrap > span").parent().find('.mejs-audio').slideDown();
                $(".footer_content_wrap > span").parent().children(".widget-contact").slideDown();
                $(".footer_content_wrap > span").css("visibility","hidden");
                }else {
                $(".footer_content_wrap > span").parent().find('.widget-title').next().slideUp();
                $(".footer_content_wrap > span").parent().find('.mejs-audio').slideUp();
                $(".footer_content_wrap > span").parent().children(".widget-contact").slideUp();
                $(".footer_content_wrap > span").css("visibility","visible");
                $('.footer_content_wrap').removeClass('active');
                }
            });
        }
        footerContent();
});