var appStart = function ($) {

    var screenWidth = $(window).width();
	function videoPlayer() {
		const players = Plyr.setup('.js-player', 
		{
		youtube: {
		  noCookie: true,
		  rel: 0,
		  modestbranding: 1
		}});
	}
    // handle Preloader OnClick
    function handlePreloaderOnClick() {
        
    }

    // RTL to LTR ------------
    var initRtlToggle = function () {
        const btn = document.getElementById('rtlToggleBtn');
        const link = document.getElementById('mainStylesheet');
        const body = document.body;

        if (!btn || !link) return;
        
        btn.addEventListener('click', () => {
            body.classList.toggle('rtl');
            if (body.classList.contains('rtl')) {
                btn.classList.add('active');
                link.href = 'assets/css/main-rtl.css'
            } else {
                btn.classList.remove('active');
                link.href = 'assets/css/main.css'
            }
        });
    }

    // ====== Dark / Light Theme Switcher ====>
    function Theme_dark_light() {
        const switchers = $('.dark-mode-switch');
        const dhtml = $("html");

        const storedDarkMode = localStorage.getItem('dark-mode') === 'true';
        if (storedDarkMode) {
            dhtml.addClass('dark-mode');
            switchers.find('i').removeClass('fa-moon-o').addClass('fa-sun-o');
        }

        switchers.on('click', function () {
            const isDarkMode = dhtml.toggleClass('dark-mode').hasClass('dark-mode');
            localStorage.setItem('dark-mode', isDarkMode);

            // Update all buttons' icons
            switchers.find('i').each(function () {
                if (isDarkMode) {
                    // $(":root").css("--sp-primary", "#005db8");
                    $(":root").css("--dark-1", "#000000");
                    $(":root").css("--dark-2", "#222222");
                    $(this).removeClass('fa-moon-o').addClass('fa-sun-o');
                } else {
                    // $(":root").css("--sp-primary", "#003366");
                    $(":root").css("--dark-1", "#ffffff");
                    $(":root").css("--dark-2", "#F5F5F5");
                    $(this).removeClass('fa-sun-o').addClass('fa-moon-o');
                }
            });
        });
    }

    // Handle Search Toggle ============ 
    var handleSearchToggle = function () {
        const toggleButton = document.querySelector('.header-search-toggle');
        const searchBox = document.querySelector('.header-search-popup');
        const closeButton = document.querySelector('.header-search-close');
        const body = document.querySelector('body');

        if (toggleButton && searchBox) {
            toggleButton.addEventListener('click', function () {
                searchBox.classList.add('header-search-active');
                body.classList.add('fixed');
            });
            document.addEventListener('click', function (e) {
                if (!searchBox.contains(e.target) && !toggleButton.contains(e.target)) {
                    searchBox.classList.remove('header-search-active');
                    body.classList.remove('fixed');
                }
            });
            if (closeButton) {
                closeButton.addEventListener('click', function () {
                    searchBox.classList.remove('header-search-active');
                    body.classList.remove('fixed');
                });
            }
        } else {
            console.log('Search toggle elements are missing!');
        }
    };

    // Handle Toggler Mobile Menu ============
    var handleTogglerMobileMenu = function () {
        const menuToggler = document.querySelector('.menu-toggle');

        if (menuToggler) {
            const body = document.querySelector('body');
            const menuClose = document.querySelector('.menu-close');
            const target = menuToggler.getAttribute('data-target');
            const targetElement = document.querySelector(target);

            const toggleMenu = () => {
                if (window.innerWidth <= 991) {
                    menuToggler.addEventListener('click', openMenu);
                    menuClose.addEventListener('click', closeMenu);
                } else {
                    menuToggler.removeEventListener('click', openMenu);
                    menuClose.removeEventListener('click', closeMenu);
                    menuToggler.classList.remove('open');
                    body.classList.remove('fixed');
                    targetElement.classList.remove('show');
                }
            };
            const openMenu = () => {
                menuToggler.classList.add('open');
                body.classList.add('fixed');
                targetElement.classList.add('show');
            };
            const closeMenu = () => {
                menuToggler.classList.remove('open');
                body.classList.remove('fixed');
                targetElement.classList.remove('show');
            };
            toggleMenu();
            window.addEventListener('resize', toggleMenu);
        }
    }

    // handleStickyHeader  =============
    var handleStickyHeader = function () {
        if ($(".sticky-nav").length > 0) {
            var navbar = $(".sticky-nav");
            var navbarOffset = navbar.offset().top;
            $(window).on("scroll", function () {
                var scrollTop = $(window).scrollTop();
                if (scrollTop > navbarOffset) {
                    navbar.addClass("sticky-menu");
                } else {
                    navbar.removeClass("sticky-menu");
                }
            });
        }
    }

    // handle Header Menu ============
    var handleHeaderMenu = function () {
        if ($(window).width() <= 991) {
            jQuery('.menu-wrap li > a, .dropdown-menu li > a')
                .off("click keypress")
                .on("click keypress", function (e) {
                    if (e.type === "keypress" && e.key !== "Enter") return;
                    // handleMenus(e, jQuery(this));
                });
            jQuery('.tabindex').attr("tabindex", "0");

            jQuery('.mobile-toggler button')
                .off('click')
                .on('click', function (e) {
                    e.preventDefault();
                    console.log(11);
                    let parentLi = jQuery(this).closest('li');
                    let dropdown = parentLi.find('.dropdown-menu').first();
                    if (parentLi.hasClass('open')) {
                        dropdown.slideUp('slow', function () {
                            jQuery(this).css('display', 'none');
                        });
                        parentLi.removeClass('open');
                    } else {
                        parentLi.siblings('li').removeClass('open')
                            .children('.dropdown-menu, .mega-menu').slideUp('slow').css('display', 'none');
                        dropdown.css('display', 'block').slideDown();
                        parentLi.addClass('open');
                    }
                });
        } else {
            jQuery('.tabindex').removeAttr("tabindex");
            jQuery('.dropdown-menu, .mega-menu').removeAttr('style');
            jQuery('.menu-wrap li').removeClass('open');
        }
    };

    // handle Breaking News  ============
    var handleBreakingNewsSlider = function () {
        jQuery(document).ready(function ($) {
            $(".breaking-news-slider").each(function () {
                var $slider = $(this);
                $slider.owlCarousel({
                    autoWidth: true,
                    loop: true,
                    margin: 10,
                    autoplay: true,
                    autoplayTimeout: 5000,
                    autoplaySpeed: 5000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
                    slideTransition: 'linear',
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        575: {
                            nav: true
                        },
                        991: {
                            margin: 15
                        }
                    }
                });
                setInterval(function () {
                    if ($(window).width() >= 575) {
                        $slider.find(".owl-nav").removeClass("disabled");
                    }
                }, 0);
            });
        });
    };

    // handle Latest News ============
    var handleLatestNewsSlider = function () {
        if (jQuery('.news-slider').length > 0) {
            jQuery(document).ready(function ($) {
                entertainmentNews= $(".news-slider").owlCarousel({
                    center: true,
                    items: 1,
                    loop: true,
                    margin: 5,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: true,
                    dots: false,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                });
            });
        }
    }
	
	// handle sport News ============
    var handleSportNewsSlider = function () {
        if (jQuery('.sport-news-slider').length > 0) {
            jQuery(document).ready(function ($) {
                sportNews= $(".sport-news-slider").owlCarousel({
                    center: true,
                    items: 1,
                    loop: true,
                    margin: 5,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: true,
                    dots: false,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                });
            });
        }
    }
	
// handle fashion News ============
    var handleFashionNewsSlider = function () {
        if (jQuery('.fashion-news-slider').length > 0) {
            jQuery(document).ready(function ($) {
                fashionNews= $(".fashion-news-slider").owlCarousel({
                    center: true,
                    items: 1,
                    loop: true,
                    margin: 5,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: true,
                    dots: false,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                });
            });
        }
    }

    // handle Filter Slider ============
    var handleFilterSlider = function () {
        jQuery(document).ready(function ($) {
            $(".tab-filter-slider").each(function () {
                var $slider = $(this);
                $slider.owlCarousel({
                    loop: false,
                    margin: 30,
                    autoplay: false,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: true,
                    dots: false,
					autoWidth:true,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"]                    
                });

                setInterval(function () {
                    $slider.find(".owl-nav").removeClass("disabled");
                }, 0);
            });
        });
    };

    // handle Zodiac Filter ============
    
	var handleSetupZodiacFilter = function () {
    const zodiacItems = document.querySelectorAll('.zodiac-item');
    const posts = document.querySelectorAll('.post-astrology');

    zodiacItems.forEach(item => {
        item.addEventListener('click', () => {
            zodiacItems.forEach(i => i.classList.remove('active'));
            item.classList.add('active');
            const selectedSign = item.querySelector('.zodiac-label').textContent.trim();
            posts.forEach(post => {
                post.classList.remove('show');
                post.style.display = 'none';
            });
            posts.forEach(post => {
                const postSign = post.getAttribute('data-sign');
                if (postSign === selectedSign) {
                    post.style.display = 'block';
                    requestAnimationFrame(() => {
                        post.classList.add('show');
                    });
                }
            });
        });
    });

    // Default trigger on first zodiac item if no active one is set
    const activeItem = document.querySelector('.zodiac-item.active');
    if (activeItem) {
        activeItem.click();
    } else if (zodiacItems.length > 0) {
        zodiacItems[0].classList.add('active');
        zodiacItems[0].click();
    }
};


    // handle toggle Tabs ============
    var handleToggleTabs = function () {
        const buttons = document.querySelectorAll('.news-top-btn button');
        const tabs = [document.getElementById('popular-1'), document.getElementById('popular-2')];

        buttons.forEach((button, index) => {
            button.addEventListener('click', () => {
                buttons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                tabs.forEach(tab => tab.classList.add('d-none'));
                tabs[index].classList.remove('d-none');
            });
        });
    }

    // handle Post Slider ============
    var handlePostSlider = function () {
        if (jQuery('.post-slider').length > 0) {
            jQuery(document).ready(function ($) {
                var owl = $(".post-slider").owlCarousel({
                    items: 4,
                    loop: true,
                    margin: 25,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        0: {
                            items: 1
                        },
                        450: {
                            items: 2
                        },
                        768: {
                            items: 3
                        },
                        991: {
                            items: 4
                        }
                    }
                });
            });
        }
    }

    // handle Web Store Slider ============
    var handleWebStoreSlider = function () {
        if (jQuery('.web-store-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $('.web-store-slider').each(function () {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        items: 1,
                        loop: true,
                        margin: 12,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {
                            0: {
                                items: 1
                            },
							768: {
                                items: 2
                            }
                        }
                    });

                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };
    // handle Web Store Slider ============
    var handleEditorSlider = function () {
        if (jQuery('.editorz-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $('.editorz-slider').each(function () {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        // items: 2,
                        loop: true,
                        margin: 12,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {                            
                            0: {
                                items: 1
                            },
							768: {
                                items: 2
                            }
                        }
                    });

                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };

    // handle Team Slider ============
    var handleTeamSlider = function () {
        if (jQuery('.team-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $('.team-slider').each(function () {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        items: 1,
                        loop: true,
                        margin: 30,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {
                            575: {
                                items: 2
                            },
                            768: {
                                items: 3
                            },
                            991: {
                                items: 4
                            }
                        }
                    });
                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };

    // handle Awarads Slider ============
    var handleAwaradsSlider = function () {
        if (jQuery('.awards-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $('.awards-slider').each(function () {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        items: 1,
                        loop: false,
                        margin: 25,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {
                            575: {
                                items: 2
                            },
                            768: {
                                items: 3
                            },
                            991: {
                                items: 4
                            }
                        }
                    });
                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };

    // handle Timeline Slider ============
    var handleTimelineSlider = function () {
        if (jQuery('.timeline-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $('.timeline-slider').each(function () {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        items: 1,
                        loop: true,
                        margin: 50,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {
                            575: {
                                items: 1,
                                margin: 10,
                            },
                            991: {
                                items: 2,
                                margin: 50
                            }
                        }
                    });

                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };

    // handle Information Slider ============
    var handleInformationSlider = function () {
        if (jQuery('.information-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $('.information-slider').each(function () {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        items: 1,
                        loop: false,
                        margin: 25,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {
                            575: {
                                items: 2
                            },
                            768: {
                                items: 3
                            },
                            991: {
                                items: 4
                            }
                        }
                    });
                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };

    // handle Previously Missed Slider ============
    var handlePreviouslyMissedSlider = function () {
        if (jQuery('.previously-missed-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $('.previously-missed-slider').each(function () {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        items: 1,
                        loop: true,
                        margin: 20,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {
                            575: {
                                items: 2
                            },
                            991: {
                                items: 3
                            }
                        }
                    });
                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };

    // handle Post Carousel Slider ============
    var handlePostCarouselSlider = function () {
        if (jQuery('.post-carousel > .swiper-wrapper').length > 0) {
            jQuery(document).ready(function ($) {
                $('.post-carousel > .swiper-wrapper').each(function (index) {
                    var $slider = $(this);
                    var owl = $slider.owlCarousel({
                        items: 1,
                        loop: true,
                        margin: 20,
                        autoplay: true,
                        autoplayTimeout: 3000,
                        autoplayHoverPause: true,
                        smartSpeed: 1000,
                        nav: false,
                        dots: false,
                        autoHeight: true,
                        responsive: {
                            0: {
                                items: 1
                            },
							768: {
                                items: 2
                            }
                        }
                    });
                    var container = $(this).closest('.slider-wrapper').prev();
                    container.find('.custom-prev').off('click').on('click', function () {
                        owl.trigger('prev.owl.carousel');
                    });
                    container.find('.custom-next').off('click').on('click', function () {
                        owl.trigger('next.owl.carousel');
                    });
                });
            });
        }
    };

    // handle Above Social Slider ============
    var handleAboveSocialSlider = function () {
        if (jQuery('.above-social-slider').length > 0) {
            jQuery(document).ready(function ($) {
                var owl = $(".above-social-slider").owlCarousel({
                    items: 6,
                    loop: true,
                    margin: 20,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        0: {
                            items: 2
                        },
                        450: {
                            items: 3
                        },
                        650: {
                            items: 5
                        },
                        991: {
                            items: 6
                        }
                    }
                });
            });
        }
    }

    /* Magnific Video Popup =============== */
    var MagnificVideoPopup = function () {
        if ($.fn.magnificPopup) {
            $(".popup-youtube, .popup-vimeo").magnificPopup({
                disableOn: 700,
                type: 'iframe',
                mainClass: 'mfp-fade',
                removalDelay: 160,
                preloader: false,
                fixedContentPos: true,
                iframe: {
                    patterns: {
                        youtube: {
                            index: 'youtube.com/',
                            id: function (url) {
                                var match = url.match(/[\\?&]v=([^&#]*)/);
                                return match ? match[1] : null;
                            },
                            src: 'https://www.youtube.com/embed/%id%?autoplay=1'
                        },
                        vimeo: {
                            index: 'vimeo.com/',
                            id: function (url) {
                                var match = url.match(/vimeo.com\/(\d+)/);
                                return match ? match[1] : null;
                            },
                            src: 'https://player.vimeo.com/video/%id%?autoplay=1'
                        }
                    }
                }
            });
        } else {
            console.error("Magnific Popup is not loaded!");
        }
    }

    // Function to Plyr ==================
    // var plyrMasterVideo = function () {
        // $('.plyrMasterVideo').each(function (index, element) {
            // var playerElement = $(element).find('video')[0];
            // if (playerElement) {
                // new Plyr(playerElement); // no need to pass options again
            // }
        // });
    // };
	var plyrMasterVideo = function () {
        $('.plyrMasterVideo').each(function (index, element) {
            var videoElement = $(element).find('video')[0];
            if (videoElement) {
                new Plyr(videoElement);
            } else if ($(element).data('plyr-provider') === 'youtube') {
                new Plyr(element);
            }
        });
    };
	
    // handle Widget Video Slider ============
    var handleWidgetVideoSlider = function () {
        if (jQuery('.widget_video_carousel').length > 0) {
            jQuery(document).ready(function ($) {
                var owl = $(".widget_video_carousel").owlCarousel({
                    items: 1,
                    loop: false,
                    margin: 10,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: true,
                    dots: false,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                });
            });
        }
    }

    // handle Trap Focus  ============
    var handleTrapFocus = function (focusDelay = 0) {
        let $containers = $('.docker-widget-popup, .header-search-popup');

        $containers.each(function () {
            let $container = $(this);
            let tabbable = $container
                .find('select, input, textarea, button, a, [href], [tabindex]:not([tabindex="-1"])')
                .filter(':visible');

            if (tabbable.length === 0) return;

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

            setTimeout(() => {
                firstTabbable.focus();
            }, focusDelay);

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

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

    // Counter Number ============ 
    var counter = function () {
        if (jQuery('.counter').length) {
            jQuery('.counter').counterUp({
                delay: 100,
                time: 5000
            });
        }
    }

    // handle skill Bar =============
    var handleSkillBar = function () {
        $(".progress-bar").each(function () {
            let $this = $(this);
            const isRTL = $("body").hasClass("rtl");
            if (isScrolledIntoView($this) && !$this.hasClass("animated")) {
                $this.addClass("animated");
                let percent = $this.attr("data-percent");
                let progressFill = $this.find(".progress-fill");
                let progressText = $this.find(".circle-fill");
                let countBar = $this.find(".count-bar");
                progressFill.animate({ width: percent }, 3000);
                let animProps = isRTL ? { right: percent } : { left: percent };
                progressText.animate(animProps, 3000);
                $({ countNum: 0 }).animate({ countNum: parseInt(percent) }, {
                    duration: 3000,
                    easing: 'linear',
                    step: function () {
                        countBar.text(Math.floor(this.countNum));
                    },
                    complete: function () {
                        countBar.text(this.countNum);
                    }
                });
            }
        });
    };
    // Scroll START function---
    function isScrolledIntoView(element) {
        let windowHeight = $(window).height();
        let elementTop = $(element).offset().top;
        let scrollTop = $(window).scrollTop();
        return elementTop < (scrollTop + windowHeight - 50);
    }

    // handle Box Hover =============
    var handleBoxHover = function () {
        const boxHover = document.querySelectorAll('.box-hover');
        if (boxHover) {
            boxHover.forEach(function (element) {
                element.addEventListener('mouseenter', function () {
                    const selector = element.parentElement.parentElement;
                    selector.querySelectorAll('.box-hover').forEach(function (element) {
                        element.classList.remove('active');
                    });
                    element.classList.add('active');
                });
            });
        }
    }

    // handle Load More =============
    var handleLoadMore = function () {
        const itemsToShow = 4;
        const hiddenItemsOnLoad = document.querySelectorAll('.hidden-item');
        for (let i = 0; i < itemsToShow && i < hiddenItemsOnLoad.length; i++) {
            hiddenItemsOnLoad[i].classList.remove('hidden-item');
        }
        const loadMoreBtn = document.querySelector('.load-more-btn');
        if (loadMoreBtn) {
            loadMoreBtn.addEventListener('click', function () {
                const refreshIcon = loadMoreBtn.querySelector('.fa-refresh');
                if (refreshIcon) {
                    refreshIcon.classList.add('loading-icon');
                }
                setTimeout(() => {
                    const hiddenItems = document.querySelectorAll('.hidden-item');
                    for (let i = 0; i < itemsToShow && i < hiddenItems.length; i++) {
                        hiddenItems[i].classList.remove('hidden-item');
                    }
                    if (document.querySelectorAll('.hidden-item').length === 0) {
                        loadMoreBtn.innerHTML = 'No More';
                    }
                    if (refreshIcon) {
                        refreshIcon.classList.remove('loading-icon');
                    }
                }, 1000);
            });
        }
    };


    // handle CustomTab  ============
    var handleCustomTab = function () {
        document.querySelectorAll(".toggle-group").forEach(group => {
            const toggles = group.querySelectorAll(".clcik-toggle");
            const groupName = group.getAttribute("data-group");
            const sections = document.querySelectorAll(`.custom-tab[data-group='${groupName}']`);
            toggles.forEach(toggle => {
                toggle.addEventListener("click", function () {
                    toggles.forEach(el => el.classList.remove("active"));
                    sections.forEach(sec => sec.classList.remove("active"));

                    this.classList.add("active");
                    document.getElementById(this.getAttribute("data-target")).classList.add("active");
                });
            });
            // Default Active State
            if (toggles.length > 0) {
                toggles[0].classList.add("active");
                sections[0].classList.add("active");
            }
        });
    };

    // handle Grid List Toggle  ============
    var handleGridListToggle = function () {
        if (jQuery('.gridlistToggle').length > 0) {
            document.querySelectorAll('.gridlistToggle').forEach(button => {
                button.addEventListener('click', function () {
                    const layout = this.getAttribute('data-layout');
                    document.querySelectorAll('.gridlistToggle').forEach(btn => {
                        btn.classList.remove('active');
                    });
                    document.querySelectorAll(`.gridlistToggle[data-layout="${layout}"]`).forEach(btn => {
                        btn.classList.add('active');
                    });
                    document.querySelectorAll('.posts').forEach(postList => {
                        postList.classList.remove('grid2', 'grid3', 'list');
                        postList.classList.add(layout);
                    });
                });
            });
        }
    };


    // Scroll To Top ============
    var handleScrollIndicator = function () {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        const scrollProgress = document.querySelectorAll('.scrollup');

        if (scrollProgress.length > 0) {
            scrollProgress.forEach(el => {
                if (scrollTop > 200) {
                    el.classList.add('is-active');
                } else {
                    el.classList.remove('is-active');
                }

                // Add click listener
                el.addEventListener('click', function () {
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                });
            });
            const scrollHeight = document.documentElement.scrollHeight;
            const windowHeight = document.documentElement.clientHeight;
            const maxScrollTop = scrollHeight - windowHeight;
            const scrollPercentage = (scrollTop / (maxScrollTop - 200)) * 100;
            const scrollPoint = document.querySelector('.scroll-point');
            if (scrollPoint) {
                scrollPoint.style.height = Math.min(scrollPercentage, 100) + '%';
            }
        }
    }

    // handle Weather Widget ==========
    var initWeatherWidget = function () {
        //const apiKey = "5b27a6ef3547402582e62007222306";
        const apiKey = "66078b6cc6f4a920e0e653b41e1cb6ee";
        const city = "london";
	
        fetch(`https://api.OpenWeatherMap.org/v1/current.json?key=${apiKey}&q=${city}&aqi=yes`)
            .then(response => response.json())
            .then(data => {
                const {
                    current: {
                        temp_c,
                        air_quality
                    },
                    location: { name, localtime }
                } = data;

                const pm25 = air_quality.pm2_5;
                const pm10 = air_quality.pm10;
                const epaIndex = air_quality["us-epa-index"];
                // Helper: Get AQI Category
                function getAQICategory(index) {
                    switch (index) {
                        case 1: return "Satisfactory";
                        case 2: return "Moderate";
                        case 3: return "Unhealthy for Sensitive Groups";
                        case 4: return "Unhealthy";
                        case 5: return "Very Unhealthy";
                        case 6: return "Hazardous";
                        default: return "Unknown";
                    }
                }

                document.querySelector('#temp').textContent = temp_c+' ℃';
                document.querySelector('#cityName').textContent = name;
                document.querySelector('#aqi').textContent = `${epaIndex.toFixed(1)}`;
                document.querySelector('#aqiCategory').textContent = `${getAQICategory(epaIndex)}`;
                // document.querySelector('#aqi').textContent = `PM2.5: ${pm25.toFixed(1)}, PM10: ${pm10.toFixed(1)}, AQI (EPA): ${epaIndex}`;

                let localTime = new Date(localtime.replace(' ', 'T'));
                function updateClock() {
                    localTime.setSeconds(localTime.getSeconds() + 1);
                    document.querySelector('.widget-date-time .time').textContent = localTime.toLocaleTimeString();
                }
                updateClock();
                setInterval(updateClock, 1000);
                const day = localTime.getDate();
                const month = localTime.toLocaleString('default', { month: 'long' });
                const year = localTime.getFullYear();
                document.querySelector('.widget-date-time .day').textContent = day;
                document.querySelector('.widget-date-time .month').textContent = month;
                document.querySelector('.widget-date-time .year').textContent = year;
            })
            .catch(error => {
                // console.error("Error fetching weather or AQI:", error);
            });
			
    };

		var initWeatherWidget1 = function () {
			const apiKey = "66078b6cc6f4a920e0e653b41e1cb6ee";
			const lat = 25.1825;
			const lon = 75.8391;

		// AQI Fetch
		fetch(`https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${apiKey}`)
		  .then(response => response.json())
		  .then(data => {
			const aqi = data.list[0].main.aqi;

			function getAQICategory(index) {
			  switch (index) {
				case 1: return "Good";
				case 2: return "Fair";
				case 3: return "Moderate";
				case 4: return "Poor";
				case 5: return "Very Poor";
				default: return "Unknown";
			  }
			}

			document.querySelector('#aqi').textContent = aqi;
			document.querySelector('#aqiCategory').textContent = getAQICategory(aqi);
		  })
		  .catch(error => {
			console.error("Error fetching AQI:", error);
		  });

}
    // handle Footer Content Widget ==========
    var handleFooterContent = function () {
        const isDesktop = window.innerWidth > 767;
        const footerWraps = document.querySelectorAll(".footer_content_wrap");

        footerWraps.forEach(wrap => {
            const content = wrap.querySelector(".footer_content:not(:has(.wp-block-heading))");
            wrap.querySelectorAll(".collaps, .collapsd").forEach(icon => icon.remove());

            const newWrap = wrap.cloneNode(true);
            wrap.parentNode.replaceChild(newWrap, wrap);

            const contentPanel = newWrap.querySelector(".footer_content:not(:has(.wp-block-heading))");

            if (isDesktop) {
                newWrap.classList.add("active");
                if (contentPanel) {
                    contentPanel.style.maxHeight = contentPanel.scrollHeight + "px";
                }
            } else {
                const plusIcon = document.createElement("span");
                plusIcon.className = "collaps";
                plusIcon.innerHTML = "<i class='fa fa-plus-circle'></i>";
                plusIcon.style.cursor = "pointer";

                const minusIcon = document.createElement("span");
                minusIcon.className = "collapsd";
                minusIcon.innerHTML = "<i class='fa fa-minus-circle'></i>";
                minusIcon.style.cursor = "pointer";

                newWrap.insertBefore(minusIcon, newWrap.firstChild);
                newWrap.insertBefore(plusIcon, newWrap.firstChild);

                newWrap.classList.remove("active");
                contentPanel.style.maxHeight = "0";
                contentPanel.style.overflow = "hidden";
                contentPanel.style.transition = "max-height 0.4s ease";

                plusIcon.style.display = "inline";
                minusIcon.style.display = "none";

                const toggle = () => {
                    const isActive = newWrap.classList.contains("active");
                    newWrap.classList.toggle("active");
                    if (isActive) {
                        contentPanel.style.maxHeight = "0";
                        plusIcon.style.display = "inline";
                        minusIcon.style.display = "none";
                    } else {
                        contentPanel.style.maxHeight = contentPanel.scrollHeight + "px";
                        plusIcon.style.display = "none";
                        minusIcon.style.display = "inline";
                    }
                };
                plusIcon.addEventListener("click", toggle);
                minusIcon.addEventListener("click", toggle);
            }
        });
    }

    // handle Ticker Slider ============
    var handleTickerSlider = function () {
        jQuery(document).ready(function ($) {
            $(".ticker-slider").each(function () {
                var $slider = $(this);
                $slider.owlCarousel({
                    autoWidth: true,
                    loop: true,
                    margin: 15,
                    autoplay: true,
                    autoplayTimeout: 6000,
                    autoplaySpeed: 6000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
                    slideTransition: 'linear',
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        991: {
                            margin: 30
                        }
                    }
                });
            });
        });
    };
	
	// handle Masonry Filter  ============
    // var handleMasonryFilter = function() {	
        // jQuery(document).ready(function ($) {
            // jQuery('.av-filter-init').mixItUp({
                // selectors: {
                    // target: '.tile',
                    // filter: '.filter',
                    // sort: '.sort-btn'
                // },
                // animation: {
                    // animateResizeContainer: false,
                    // effects: 'fade scale'
                // }
            // });
        // });
    // };
	
	// handle Masonry Filter  ============
    var handleMasonryFilter = function() {
        const filterGroups = document.querySelectorAll('.filter-group');
        filterGroups.forEach(group => {
            const filterLinks = group.querySelectorAll('.filter-container a');
            const mixItems = group.querySelectorAll('.mix');
            const owlItemsMap = new WeakMap();

            filterLinks.forEach(link => {
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    filterLinks.forEach(l => l.classList.remove('active'));
                    link.classList.add('active');

                    const filter = link.getAttribute('data-filter');

                    // OWL Filter
                    handleOwlFilter(group, filter, owlItemsMap);

                    mixItems.forEach(item => {
                        // item.classList.remove('show');
                        // if (filter === 'all' || item.classList.contains(filter)) {
                        //     item.classList.add('show');
                        // }
                        if (filter === 'all' || item.classList.contains(filter)) {
                            item.style.display = 'block';
                            item.classList.remove('zooming-out');
                            void item.offsetWidth;
                            item.classList.add('show');
                        } else {
                            item.classList.remove('show');
                            item.classList.add('zooming-out');

                            setTimeout(() => {
                                item.style.display = 'none';
                                item.classList.remove('zooming-out');
                            }, 300);
                        }
                    });
                });
            });
        });
    };
	
	 // handle Post Tiny Slider ============
    var handlePostTinySlider = function () {
        jQuery(function ($) {
            $(".post-list-vertical").each(function () {
                var itemsCount = $(this).data("items") || 3;
                var slider = tns({
                    container: this,
                    items: itemsCount,
                    axis: "vertical",
                    swipeAngle: true,
                    speed: 400,
                    nav: false,
                    controls: false,
					gutter: 15
                });
                var $heading = $(this).closest(".vertical-wrapper").prevAll(".heading-default").first();
                $heading.find(".custom-prev").off("click").on("click", function () {
                    slider.goTo("prev");
                });
                $heading.find(".custom-next").off("click").on("click", function () {
                    slider.goTo("next");
                });
            });
        });
    };

    // handle ZodiacTiny Slider ============
    var handleZodiacTinySlider = function () {
        jQuery(function ($) {
            $(".zodiac-list-horizontal").each(function () {
                var itemsCount = $(this).data("items") || 4;
                var slider = tns({
                    container: this,
                    loop: false,
                    items: itemsCount,
                    axis: "horizontal",
                    swipeAngle: true,
                    speed: 400,
                    nav: false,
                    controls: false,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayButtonOutput: false 
                });
                var $heading = $(this).closest(".row").prevAll(".heading-default").first();
                $heading.find(".custom-prev").off("click").on("click", function () {
                    slider.goTo("prev");
                });
                $heading.find(".custom-next").off("click").on("click", function () {
                    slider.goTo("next");
                });
            });
        });
    };

document.addEventListener("DOMContentLoaded", function () {
	handleSetupZodiacFilter();
    handleMasonryFilter();
	
    //Auto-click on default active filter link
    const defaultFilter = document.querySelector('.filter-group .filter-container a.active');
    if (defaultFilter) {
        defaultFilter.click();
    }
});

    function handleOwlFilter(group, filter, owlItemsMap) {
        const owlContainer = group.querySelector('.news-slider');
        if (!owlContainer) return;

        if (!owlItemsMap.has(group)) {
            const originalItems = Array.from(owlContainer.querySelectorAll('.news-item')).map(item => item.cloneNode(true));
            owlItemsMap.set(group, originalItems);
        }

        const originalOwlItems = owlItemsMap.get(group);

        $(owlContainer).trigger('destroy.owl.carousel');
        owlContainer.innerHTML = '';

        const filtered = originalOwlItems.filter(item => {
            return filter === 'all' || item.classList.contains(filter);
        });

        filtered.forEach(item => {
            owlContainer.appendChild(item.cloneNode(true));
        });

        setTimeout(() => {
            handleLatestNewsSlider();
        }, 100);
    }
	
	//handleAnySliderFilter
	var handleAnySliderFilter = function() {	
		$( '.tab-filter-slider' ).on( 'click', '.filter', function() {

			var $item = $(this);
			var filter = $item.data( 'filter' )

			entertainmentNews.owlcarousel2_filter( filter );

		} )
    };
	
	//Magnific
	jQuery(document).ready(function($) {
    $('.popup-youtube').magnificPopup({
        type: 'iframe'
    });
	
		const preloader = document.querySelector(".preloader");
        const closeBtn = document.querySelector(".preloader__close-btn");
        if (preloader) {
            setTimeout(() => {
                preloader.style.opacity = "0";
                preloader.style.visibility = "hidden";
            }, 5000);
            if (closeBtn) {
                closeBtn.addEventListener("click", () => {
                    preloader.style.opacity = "0";
                    preloader.style.visibility = "hidden";
                });
            }
        }
});

    /* Function ============ */
    return {
        init: function () {
            // handlePreloaderOnClick();
            videoPlayer();
			// handleAnySliderFilter();
            Theme_dark_light();
            handleSearchToggle();
            // initRtlToggle();
             handleTogglerMobileMenu();
            handleStickyHeader();
            handleHeaderMenu();
            handleBreakingNewsSlider();
            handleLatestNewsSlider();
            handleFilterSlider();
            //handleSetupZodiacFilter();
            handleToggleTabs();
            handlePostSlider();
            handleWebStoreSlider();
			handleEditorSlider();
            handleTeamSlider();
            handleAwaradsSlider();
            handleTimelineSlider();
            handleInformationSlider();
            handlePreviouslyMissedSlider();
            handlePostCarouselSlider();
            handleAboveSocialSlider();
            MagnificVideoPopup();
            plyrMasterVideo();
            handleWidgetVideoSlider();
            handleTrapFocus();
            handleSkillBar();
            handleBoxHover();
            handleLoadMore();
            handleCustomTab();
            handleGridListToggle();
            // initWeatherWidget();
			// initWeatherWidget1();
            handleFooterContent();
            handleTickerSlider();
            //handleMasonryFilter();
			handleSportNewsSlider();
			handleFashionNewsSlider();
			handlePostTinySlider();
            handleZodiacTinySlider();
        },

        load: function () {
            counter();
            handleSkillBar();
        },

        resize: function () {
            screenWidth = $(window).width();
            handleHeaderMenu();
            handleFooterContent();
        },

        scroll: function () {
            handleSkillBar();
            handleScrollIndicator();
        }
    }
}(jQuery);


/* Document.ready Start */
document.addEventListener('DOMContentLoaded', function () {
    appStart.init();

    document.querySelectorAll('.post-items').forEach(item => {
        const hasBlogImg = item.querySelector('.featured-image .blog-img');
        if (!hasBlogImg) {
            item.classList.add('no-img');
        }
    });
});
/* Document.ready END */

/* Window Load START */
window.addEventListener('load', function () {
    appStart.load();
});
/* Window Load END */

/* Window Resize START */
window.addEventListener('resize', function () {
    appStart.resize();
});
/*  Window Resize END */

/* Window Scroll START */
window.addEventListener("scroll", function () {
    appStart.scroll();
});
/*  Window Scroll END */