/**
 * Handles theme general events
 * 
 * @package One Newspaper
 * @since 1.0.0
 */
jQuery(document).ready(function($) {
    "use strict"
    const { ajaxUrl, _wpnonce, stt: sttOption, isRtl, toc, headerInsta, footerInsta, headerAdsBannerOption, themeColor } = oneNewspaperObject,
        wpadminbar = $( 'body #wpadminbar' ).height(),
        isLoggedIn = $( 'body' ).hasClass( 'admin-bar' )

    var desktopHeaderHeight = $( 'header#masthead .bb-bldr--normal' ).outerHeight(),
        responsiveHeaderHeight = $( 'header#masthead .bb-bldr--responsive' ).outerHeight()

    /**
     * MARK: Initialize Slick js
     * 
     * @since 1.0.0
     */
    const oneNewspaperInitializeSlick = ( props, returnInstance = false ) => {
        let { responsive = [], dots = false, arrows = true, fade = false, infinite = true, speed = 300, autoplay = false, autoplaySpeed = 3000, slidesToShow = 1, slidesToScroll = 1, prevIcon = 'fa-solid fa-angle-left', nextIcon = 'fa-solid fa-angle-right', focusOnSelect = false, selector, ...remains } = props,
        slickObject = {
            dots,
            arrows,
            infinite,
            speed,
            autoplay,
            autoplaySpeed,
            slidesToShow,
            slidesToScroll,
            fade,
            focusOnSelect,
            rtl: isRtl === '1' ? true : false,
            prevArrow: `<button type="button" class="slick-test-arrow slick-prev"><i class="${ prevIcon }"></i></button>`,
            nextArrow: `<button type="button" class="slick-test-arrow slick-next"><i class="${ nextIcon }"></i></button>`,
            responsive: [
                {
                    breakpoint: 1100,
                    settings: {
                        slidesToShow: 3,
                    },
                },
                {
                    breakpoint: 940,
                    settings: {
                        slidesToShow: 2,
                    },
                },
                {
                    breakpoint: 700,
                    settings: {
                        slidesToShow: 1,
                    },
                }
            ],
            ...remains
        }
        if( ! responsive ) slickObject.responsive = []
        let slickInstance = $( selector ).slick( slickObject )
        if( returnInstance ) return slickInstance;
    }

    // on element outside click function
    function onElementOutsideClick( currentElement, callback ) {
        $( document ).mouseup(function( e ) {
            var container = $( currentElement );
            if ( ! container.is( e.target ) && container.has( e.target ).length === 0 ) callback();
        })
    }

    if( ! oneNewspaperObject.is_customizer ) {
        setTimeout(function() {
            $('body .one_newspaper_loading_box').hide();
        }, 2000);
    } else {
        $('body .one_newspaper_loading_box').hide();
    }

    /**
     * Calculate header Height
     * 
     * @since 1.0.2
     */
    const oneNewspaperCalculateHeaderHeight = () => {
        let isDesktop = $( 'body' ).hasClass( 'is-desktop' )
        $( 'header#masthead' ).height( isDesktop ? desktopHeaderHeight : responsiveHeaderHeight )   
    }

    /**
     * Add device class
     * 
     * @since 1.0.2
     */
    const oneNewspaperAddDeviceClass = () => {
        let selector = $('body')
        if( $( window ).width() <= 426 ) {
            selector.removeClass( 'is-desktop is-tablet' ).addClass( 'is-smartphone' )
        } else if( $( window ).width() <= 769 ) {
            selector.removeClass( 'is-desktop is-smartphone' ).addClass( 'is-tablet' )
        } else {
            selector.removeClass( 'is-smartphone is-tablet' ).addClass( 'is-desktop' )
        }
    }

    oneNewspaperAddDeviceClass()
    $( window ).on("resize", function() {
        oneNewspaperAddDeviceClass()
        let isDesktop = $( 'body' ).hasClass( 'is-desktop' )
        if( isDesktop ) {
            desktopHeaderHeight = $( 'header#masthead .bb-bldr--normal' ).outerHeight()
        } else {
            responsiveHeaderHeight = $( 'header#masthead .bb-bldr--responsive' ).outerHeight()
        }
        oneNewspaperCalculateHeaderHeight()
    })

    var nrtl = false
    var ndir = "left"
    if ($('body').hasClass("rtl")) {
        nrtl = true;
        ndir = "right";
    };
    
    // theme trigger modal close
    function oneNewspaperCloseModal( elm, callback ) {
        $(document).mouseup(function (e) {
            var container = $(elm);
            if (!container.is(e.target) && container.has(e.target).length === 0) callback();
        });
    }

    // ticker news slider events
    var tc = $( ".ticker-news-wrap" );
    if( tc.length ) {
        var tcSpeed = tc.data("speed") || 20000
        var tcM = tc.find( ".ticker-item-wrap" ).marquee({
            duration: tcSpeed,
            gap: 0,
            delayBeforeStart: 0,
            direction: ndir,
            duplicated: true,
            startVisible: true,
            pauseOnHover: true,
        });
        tc.on( "click", ".one-newspaper-ticker-pause", function() {
            $(this).find( "i" ).toggleClass( "fa-pause fa-play" )
            tcM.marquee( "toggle" );
        })
    }

    // top date time
    var timeElement = $( ".top-date-time .time" )
    if( timeElement.length > 0 ) {
        setInterval(function() {
            timeElement.html(new Date().toLocaleTimeString())
        },1000);
    }
    
    // search form and off canvas trigger
    $( "#masthead" ).on( "click", ".off-canvas-trigger", function() {
        // $(this).next().addClass('toggle_show');
        $(this).addClass('slideshow');
        $('body').addClass('off-canvas-active');
    });
    $( "#masthead" ).on( "click", ".off-canvas-trigger.slideshow, .sidebar-toggle .off-canvas-close", function() {
        $('.off-canvas-trigger').removeClass('slideshow');
        $('body').removeClass('off-canvas-active');
        $("#masthead .search-wrap").find(".search-results-wrap").remove()
        $("#masthead .search-wrap form").removeClass( 'results-loaded' )
    });


    /**
     * MARK: Search
     */
    const themeSearch = {
        init: function(){
            this.openSearch();
            this.closeSearch();
            onElementOutsideClick(  "#masthead .search-trigger, #masthead .search-form-wrap", function(){
                $( 'body' ).removeClass( 'bodynoscroll' )
                $( '#masthead .search-form-wrap' ).slideUp()
                $( '#masthead .search-trigger' ).removeClass( 'hide' ).siblings( '.search-close-btn' ).addClass( 'hide' )
            })
            this.closePopupOnESCPress()
        },
        openSearch: function(){
            $( "#masthead" ).on( "click", ".search-trigger", function() {
                let _this = $( this );
                $( '#masthead .search-form-wrap' ).slideDown();
                _this.addClass( 'hide' )
                _this.siblings( '.search-close-btn' ).removeClass( 'hide' )
                $( '#masthead .search-form-wrap input[type="search"]' ).focus()
                $( 'body' ).addClass( 'bodynoscroll' )
            });
        },
        closeSearch: function(){
            $( "#masthead" ).on( "click", ".search-close-btn", function() {
                let _this = $( this )
                _this.addClass( 'hide' )
                $( '#masthead .search-form-wrap' ).slideUp()
                $( '#masthead .search-trigger' ).removeClass( 'hide' )
                $( 'body' ).removeClass( 'bodynoscroll' )
            });
        },
        closePopupOnESCPress: function(){
            $(document).on( 'keydown', function( event ) {
                if( event.keyCode == 27 && $( '#masthead .search-trigger' ).hasClass( 'hide' ) ) {
                    $( '#masthead .search-trigger' ).removeClass( 'hide' )
                    $( '#masthead .search-close-btn' ).addClass( 'hide' )
                    $( '#masthead .search-form-wrap' ).slideUp()
                    $( 'body' ).removeClass( 'bodynoscroll' )
                }
            });
        },
    }
    themeSearch.init()

    oneNewspaperCloseModal( $( ".sidebar-toggle-wrap" ), function () {
        $( ".sidebar-toggle-wrap .off-canvas-trigger" ).removeClass( "slideshow" );
        $('body').removeClass('off-canvas-active');
    }); // trigger htsidebar close

    oneNewspaperCloseModal( $( ".newsletter-popup-modal" ), function () {
        $( ".newsletter-popup-modal" ).removeClass( "open" );
        $("body").removeClass("newsletter-popup-active")
    }); // trigger header newsletter popup close

    // header newsletter popup handler
    var nPopup = $( ".newsletter-element" )
    if( nPopup.length > 0 ) {
        var nPopupType = nPopup.find( "a" ).data("popup")
        if( nPopupType == 'popup' ) {
            nPopup.on( "click", "a", function(e) {
                e.preventDefault()
                var _this = $(this)
                $("body").addClass("newsletter-popup-active")
                _this.next(".newsletter-popup-modal").addClass("open")
            })
        }
        $(document).on( "click", ".newsletter-popup-modal.open .modal-close", function () {
            $( ".newsletter-popup-modal" ).removeClass( "open" );
            $("body").removeClass("newsletter-popup-active")
        }); // trigger header newsletter popup close
    }

    // main banner slider events
    var bc = $( "#main-banner-section" );
    if( bc.length ) {
        var bic = bc.find( ".main-banner-slider" )
        var bAuto = bic.data( "auto" )
        var bArrows = bic.data( "arrows" )
        var bDots = bic.data( "dots" )
        var bSpeed = bic.data( "speed" )
        bic.slick({
            dots: bDots,
            infinite: true,
            rtl: nrtl,
            arrows: bArrows,
            autoplay: bAuto,
            speed: bSpeed,
            nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
            prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
        });
    }

    // banner-tabs
    var bptc = bc.find( ".main-banner-tabs" )
    bptc.on( "click", ".banner-tabs li.banner-tab", function() {
        var _this = $(this), tabItem = _this.attr( "tab-item" );
        _this.addClass( "active" ).siblings().removeClass( "active" );
        bptc.find( '.banner-tabs-content div[tab-content="' + tabItem + '"]' ).addClass( "active" ).siblings().removeClass( "active" );
    })

    // main banner popular posts slider events
    var bpc = bc.find( ".popular-posts-wrap" );
    if( bpc.length ) {
        var bpcAuto = bpc.data( "auto" )
        var bpcArrows = bpc.data( "arrows" )
        var bpcVertical = bpc.data( "vertical" );
        if( bpcVertical) {
            bpc.slick({
                vertical: bpcVertical,
                slidesToShow: 5,
                dots: false,
                infinite: true,
                arrows: bpcArrows,
                autoplay: bpcAuto,
                nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
            })
        } else {
            bpc.slick({
                dots: false,
                infinite: true,
                arrows: bpcArrows,
                rtl: nrtl,
                draggable: true,
                autoplay: bpcAuto,
                nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
            })
        }  
    }

    // main banner layout five grid posts slider events
    var bpc = bc.find( ".main-banner-grid-posts .grid-posts-wrap" );
    if( bpc.length ) {
        var bpcAuto = bpc.data( "auto" )
        var bpcArrows = bpc.data( "arrows" )
        var bpcVertical = bpc.data( "vertical" );
        if( bpcVertical) {
            bpc.slick({
                vertical: bpcVertical,
                slidesToShow: 3,
                dots: false,
                infinite: true,
                arrows: bpcArrows,
                autoplay: bpcAuto,
                nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
            })
        } else {
            bpc.slick({
                dots: false,
                infinite: true,
                arrows: bpcArrows,
                rtl: nrtl,
                draggable: true,
                autoplay: bpcAuto,
                nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
            })
        }  
    }

    // news carousel events
    var nc = $( ".one-newspaper-section .news-carousel .news-carousel-post-wrap" );
    if( nc.length ) {
        nc.each(function() {
            var _this = $(this)
            var multiColumnSection = _this.parents('.one-newspaper-multi-column-section')
            var ncDots= _this.data("dots") == '1'
            var ncLoop= _this.data("loop") == '1'
            var ncArrows= _this.data("arrows") == '1'
            var ncAuto  = _this.data("auto") == '1'
            var ncColumns  = _this.data("columns")
            var ncColumnsTablet = 2
            if( multiColumnSection.length > 0 ) {
                ncColumnsTablet = 1
                ncColumns = 1
            }
            _this.slick({
                dots: ncDots,
                infinite: ncLoop,
                arrows: ncArrows,
                autoplay: ncAuto,
                rtl: nrtl,
                slidesToShow: ncColumns,
                nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
                responsive: [
                  {
                    breakpoint: 910,
                    settings: {
                      slidesToShow: ncColumnsTablet,
                    },
                  },
                  {
                    breakpoint: 640,
                    settings: {
                      slidesToShow: 1,
                    },
                  }
                ]
            });
        })
    }

    // Filter posts
     $( ".one-newspaper-section .news-filter" ).each(function() {
        var $scope = $(this), $scopeOptions = $scope.data("args"), newTabs = $scope.find( ".filter-tab-wrapper" ), newTabsContent = $scope.find( ".filter-tab-content-wrapper" );
        newTabs.on( "click", ".tab-title", function() {
          var a = $(this), aT = a.data("tab"), isLayoutFiveOrSix = a.parents().is( '.layout--five, .layout--six' )
          a.addClass( "isActive" ).siblings().removeClass( "isActive" );
          if( newTabsContent.find( ".tab-content.content-" + aT ).length < 1 ) {
            $scopeOptions.category_id = aT
            $.ajax({
                method: 'get',
                url: ajaxUrl,
                data: {
                    action: ( ! isLayoutFiveOrSix ? 'one_newspaper_filter_posts_load_tab_content' : 'one_newspaper_filter_layout_five_posts_load_tab_content' ),
                    options : JSON.stringify( $scopeOptions ),
                    _wpnonce: _wpnonce
                },
                beforeSend: function() {
                    $scope.addClass( 'retrieving-posts' );
                },
                success : function(res) {
                    if( res.data.loaded ) {
                        newTabsContent.append( res.data.posts )
                        $scope.removeClass( 'retrieving-posts' );
                    }
                },
                complete: function() {
                    newTabsContent.find( ".tab-content.content-" + aT ).show().siblings().hide()
                }
            })
          } else {
            newTabsContent.find( ".tab-content.content-" + aT ).show().siblings().hide()
          }
        })
    })

    // popular posts widgets
    var ppWidgets = $( ".one-newspaper-widget-popular-posts" )
    ppWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_one_newspaper_popular_posts_widget" ).attr( "id" ), parentWidgetContainer = $( "#" + parentWidgetContainerId )
        var ppWidget = parentWidgetContainer.find( ".popular-posts-wrap" );
        if( ppWidget.length > 0 ) {
            var ppWidgetVertical = ppWidget.data( "vertical" )
            if( ppWidgetVertical == 'vertical' ) {
                ppWidget.slick({
                    vertical: true,
                    slidesToShow: 4,
                    dots: false,
                    infinite: true,
                    arrows: true,
                    autoplay: true,
                    nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                    prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`
                })
            } else {
                ppWidget.slick({
                    dots: false,
                    infinite: true,
                    rtl: nrtl,
                    arrows: true,
                    autoplay: true,
                    nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                    prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`
                })
            }  
        }
    })

    // carousel posts widgets
    var cpWidgets = $( ".one-newspaper-widget-carousel-posts" )
    cpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_one_newspaper_carousel_widget" ).attr( "id" ), parentWidgetContainer
        if( typeof parentWidgetContainerId != 'undefined' ) {
            parentWidgetContainer = $( "#" + parentWidgetContainerId )
            var ppWidget = parentWidgetContainer.find( ".carousel-posts-wrap" );
        } else {
            var ppWidget = _this;
        }
        if( ppWidget.length > 0 ) {
            var ppWidgetVertical = ppWidget.data( "vertical" )
            if( ppWidgetVertical == 'vertical' ) {
                ppWidget.slick({
                    vertical: true,
                    dots: false,
                    infinite: true,
                    arrows: true,
                    autoplay: true,
                    nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                    prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`
                })
            } else {
                ppWidget.slick({
                    dots: false,
                    infinite: true,
                    rtl: nrtl,
                    arrows: true,
                    autoplay: true,
                    adaptiveHeight: true,
                    nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
                    prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`
                })
            }  
        }
    })

    // tabbed posts
    var tabpWidgets = $( ".one-newspaper-tabbed-widget-tabs-wrap" )
    tabpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_one_newspaper_tabbed_posts_widget" ).attr( "id" ), parentWidgetContainer
        if( typeof parentWidgetContainerId != 'undefined' ) {
            parentWidgetContainer = $( "#" + parentWidgetContainerId )
            var tabpWidget = parentWidgetContainer.find( ".one-newspaper-tabbed-widget-tabs-wrap" );
        } else {
            var tabpWidget = _this;
        }
        if( tabpWidget.length > 0 ) {
            tabpWidget.on( "click", ".tabbed-widget-tabs li.tabbed-widget", function() {
                var _this = $(this), tabItem = _this.attr( "tab-item" );
                _this.addClass( "active" ).siblings().removeClass( "active" );
                tabpWidget.find( '.widget-tabs-content div[tab-content="' + tabItem + '"]' ).addClass( "active" ).siblings().removeClass( "active" );
            })
        }
    })

    // news filter tabbed posts
    var nftabpWidgets = $( ".one-newspaper-news-filter-tabbed-widget-tabs-wrap" )
    nftabpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_one_newspaper_news_filter_tabbed_widget" ).attr( "id" ), parentWidgetContainer
        if( typeof parentWidgetContainerId != 'undefined' ) {
            parentWidgetContainer = $( "#" + parentWidgetContainerId )
            var nftabpWidget = parentWidgetContainer.find( ".one-newspaper-news-filter-tabbed-widget-tabs-wrap" );
        } else {
            var nftabpWidget = _this;
        }
        if( nftabpWidget.length > 0 ) {
            nftabpWidget.on( "click", ".widget-tabs li.widget-tab", function() {
                var _this = $(this), tabItem = _this.attr( "tab-item" );
                _this.addClass( "active" ).siblings().removeClass( "active" );
                nftabpWidget.find( '.tabs-content-wrap div.tabs-content.' + tabItem ).addClass( "show" ).siblings().removeClass( "show" );
            })
        }
    })

    /**
     * MARK: Theme Mode
     */
    if( localStorage.getItem( "themeMode" ) != null ) {
        if( localStorage.getItem("themeMode") == "dark" ) {
            $( 'body' ).addClass( 'one-newspaper-dark-mode' ).removeClass( 'one-newspaper-light-mode ')
        } else {
            $( 'body' ).addClass( 'one-newspaper-light-mode' ).removeClass( 'one-newspaper-dark-mode' )
        }
    }
    const themeModeContainer = $( '#masthead .mode-toggle-wrap' )
    if( themeModeContainer.length > 0 ) {
        themeModeContainer.on( 'click', function(){
            var _this = $(this), bodyElement = $( 'body' )
            if( bodyElement.hasClass( 'one-newspaper-dark-mode' ) ) {
                localStorage.setItem( 'themeMode', 'light' )
                bodyElement.removeClass( 'one-newspaper-dark-mode' ).addClass( 'one-newspaper-light-mode' )
            } else {
                localStorage.setItem( 'themeMode', 'dark' )
                bodyElement.removeClass( 'one-newspaper-light-mode' ).addClass( 'one-newspaper-dark-mode' )
            }
        })
    }

    // back to top script
    var scrollContainer = $( "#one-newspaper-scroll-to-top" );
    if( sttOption && scrollContainer.length ) {
        $( window ).scroll(function() {
            if ( $( this ).scrollTop() > 800 ) {
                scrollContainer.addClass( 'show' );
            } else {
                scrollContainer.removeClass( 'show' );
            }
        });
        scrollContainer.click(function( event ) {
            event.preventDefault();
            // Animate the scrolling motion.
            $( "html, body" ).animate({ scrollTop: 0 }, "slow" );
        });
    }

    // back to top script
    var headerAdsBannerContainer = $( "#masthead .ads-banner" );
    if( headerAdsBannerOption && headerAdsBannerContainer.length ) {
        $( window ).scroll(function() {
            if ( $( this ).scrollTop() > 800 ) {
                headerAdsBannerContainer.addClass( 'show' );
            } else {
                headerAdsBannerContainer.removeClass( 'show' );
            }
        });
        headerAdsBannerContainer.click(function( event ) {
            event.preventDefault();
            // Animate the scrolling motion.
            $( "html, body" ).animate({ scrollTop: 0 }, "slow" );
        });
    }

    // category archive hide featured post in list
    var featuredPost = $( ".archive.category .featured-post.is-sticky" )
    if( featuredPost.length > 0 ) {
        var postHide = "#post-" + featuredPost.data("id")
        $(postHide).addClass( "sticky-hide" );
    }

    // ads slide block
    var adsSliderContainer = $(".ads-banner.ads-banner-slider")
    if( adsSliderContainer.length > 0 ) {
        adsSliderContainer.slick({
            dots: false,
            infinite: true,
            rtl: nrtl,
            vertical: false,
            arrows: true,
            autoplay: true,
            nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
            prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
        })
    }

    // ads slider widget
    var adsSliderWidget = $(".widget_one_newspaper_ads_slider_widget .one-newspaper-advertisement-block")
    if( adsSliderWidget.length > 0 ) {
        adsSliderWidget.slick({
            dots: false,
            infinite: true,
            rtl: nrtl,
            vertical: false,
            arrows: true,
            autoplay: true,
            nextArrow: `<button type="button" class="slick-next"><i class="fas fa-chevron-right"></i></button>`,
            prevArrow: `<button type="button" class="slick-prev"><i class="fas fa-chevron-left"></i></button>`,
        })
    }

    // post format - gallery
    var gallery = $('.wp-block-gallery')
    if( gallery.length > 0 ) {
        gallery.each(function(){
            var _this = $(this)
            var findImageSrc = _this.find('.wp-block-image img')
            var srcArgs = []
            findImageSrc.each(function(){
                srcArgs.push({
                    src: $(this).attr('src'),
                    type: 'image'
                })
            })
            _this.magnificPopup({
                items: srcArgs,
                gallery: {
                    enabled: true
                },
                type: 'image'
            })
        })
    }

    // news filter burger
    var newsFilterContainer = $('.news-filter')
    if( newsFilterContainer.length > 0 ) {
        newsFilterContainer.each(function(){
            $(this).on('click', '.one-newspaper-burger', function(){
                var _this = $(this)
                _this.siblings().toggleClass('isactive')
            })
        })
    }

    /**
     * MARK: Cursor Animation
     */
    var cursorContainer = $('.one-newspaper-cursor')
    if( cursorContainer.length > 0 ) {
        $(document).on( 'mousemove', function( event ){
            cursorContainer.css({
                'top': 'calc('+ event.clientY +'px - 15px)',
                'left': 'calc('+ event.clientX +'px - 15px)'
            })
        })
        var selector = 'a, button, input[type="submit"], #one-newspaper-scroll-to-top .icon-text, #one-newspaper-scroll-to-top .icon-holder, .pagination .ajax-load-more, .one-newspaper-widget-loader .load-more, .blaze-switcher-button, .one-newspaper-canvas-menu .canvas-menu-icon, .one-newspaper-table-of-content .toc-fixed-icon, .one-newspaper-social-share .social-share'
        $( selector ).on( 'mouseover', function(){
            $( cursorContainer ).addClass( 'isActive' )
        })
        $( selector ).on( 'mouseout', function(){
            $( cursorContainer ).removeClass( 'isActive' )
        })
    }

    /**
     * MARK: Web Stories
     */
    const WebStories = {
        container: $( '.one-newspaper-web-stories' ),
        activeStoryId: null,
        allStoryIds: [],
        activeStoryCount: null,
        storiesWrap: $( '.one-newspaper-web-stories .stories-wrap' ),
        innerStories: $( '.one-newspaper-web-stories .inner-stories-wrap .inner-stories' ),
        actionButtons: $( '.one-newspaper-web-stories .action-buttons' ),
        isPaused: false,
        outsideClickEnabled: false,
        init: function(){
            if( this.container.length ) {
                this.outsideClickEnabled = this.container.hasClass( 'outside-click--enabled' )
                this.countClick();
                this.storyClick();
                this.close();
                this.pause();
                this.scrollButtons();
                this.closePopupOnESCPress();
                $( 'body' ).css({
                    '--expandWidth-timer': `${ 5000 / 1000 }s`
                })
                let self = this
                this.container.find( '.story' ).each(function(){
                    let _this = $( this )
                    self.allStoryIds = [ ...self.allStoryIds, _this.data( 'id' ) ]
                })
            }
        },
        countClick: function(){
            this.container.on( 'click', '.story .story-count', function( event ) {
                event.stopPropagation()
            })
        },
        storyClick: function() {
            let self = this
            this.container.on( 'click', '.story', function() {
                let _this = $( this ),
                    storyId = _this.data( 'id' ),
                    count = _this.data( 'count' )
                
                self.innerStories.parent().addClass( `cat-${ storyId }` )
                $( 'body' ).addClass( 'web-stories--open' )
                self.activeStoryId = storyId
                self.activeStoryCount = count
                if( ! self.container.hasClass( 'added' ) ) {
                    self.ajaxCall();
                } else {
                    oneNewspaperInitializeSlick({
                        selector: self.storiesWrap,
                        arrows: true,
                        fade: true,
                        infinite: true,
                        appendArrows: self.container.find( '.story-arrows' ),
                        pauseOnFocus: false,
                        pauseOnHover: false
                    })
                    self.innerStories.parent().addClass( 'open' )
                    let storyWrap = self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` )
                    self.initSecondarySlider( storyWrap );
                    self.addAmbient( storyWrap.find( '.story-cover img' ) )
                    self.actionButtons.appendTo( storyWrap.parent() )
                    self.container.find( '.story-arrows' ).appendTo( storyWrap.parent() )
                    self.container.addClass( 'added' )
                }
                self.afterChange();
                if( _this.is( ':first-child' ) ) {
                  self.container.find( '.slider-arrow.prev' ).addClass( 'disabled' )
                } else {
                    self.container.find( '.slider-arrow.prev' ).removeClass( 'disabled' )
                }
                if( _this.is( ':last-child' ) ) {
                    self.container.find( '.slider-arrow.next' ).addClass( 'disabled' )
                } else {
                    self.container.find( '.slider-arrow.next' ).removeClass( 'disabled' )
                }
            });
        },
        afterChange: function(){
            let self = this
            self.storiesWrap.on( 'afterChange', function( a, slick, currentSlide ){
                let slide = $( slick.$slides.get( currentSlide ) )
                self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` ).slick( 'unslick' )
                self.activeStoryId = slide.data( 'id' )
                let storyWrap = self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` )
                self.initSecondarySlider( storyWrap );
                self.actionButtons.appendTo( storyWrap.parent() )
                self.container.find( '.story-arrows' ).appendTo( storyWrap.parent() )
                self.innerStories.parent().removeClass(( index, className ) => {
                    return ( className.match( /\bcat-\S+/g ) || [] ).join( ' ' )
                }).addClass( `cat-${ self.activeStoryId }` )
                if( currentSlide === 0 ) {
                    self.container.find( '.slider-arrow.prev' ).addClass( 'disabled' )
                } else {
                    self.container.find( '.slider-arrow.prev' ).removeClass( 'disabled' )
                }

                if( currentSlide === ( slick.slideCount - 1 ) ) {
                    self.container.find( '.slider-arrow.next' ).addClass( 'disabled' )
                } else {
                    self.container.find( '.slider-arrow.next' ).removeClass( 'disabled' )
                }
                self.afterLastSlide()
                self.addAmbient( storyWrap.find( '.story-cover img' ) )
            })
        },
        afterLastSlide: function(){
            let self = this
            self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` ).on( 'afterChange', function( a, slick, currentSlide ){
                let isLastSlide = ( currentSlide === ( slick.slideCount - slick.options.slidesToShow ) ),
                    slide = $( slick.$slides.get( currentSlide ) )
                if( slide.hasClass( 'no-thumb' ) ) {
                    slide.parents( '.inner-story' ).addClass( 'no-thumb' )
                } else {
                    slide.parents( '.inner-story' ).removeClass( 'no-thumb' )
                }
                self.addAmbient( slide.find( '.story-cover img' ) )
                if( isLastSlide ) {
                    setTimeout(() => {
                        self.storiesWrap.slick( 'slickNext' )
                    }, 5000 - 600 );
                }
            })
        },
        ajaxCall: function(){
            let self = this
            $.ajax({
                method: 'POST',
                url: ajaxUrl,
                data: {
                    action: 'one_newspaper_stories_ajax_call',
                    _wpnonce: _wpnonce,
                    storyIds: self.allStoryIds,
                    count: self.activeStoryCount
                },
                beforeSend: function() {
                    self.storiesWrap.addClass( 'retrieving-stories' )
                },
                success: function( result ) {
                    let { success, data } = result
                    if( success ) {
                        oneNewspaperInitializeSlick({
                            selector: self.storiesWrap,
                            arrows: true,
                            fade: true,
                            infinite: true,
                            appendArrows: self.container.find( '.story-arrows' ),
                            pauseOnFocus: false,
                            pauseOnHover: false
                        })
                        self.innerStories.append( data )
                        let storyWrap = self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` ),
                            storyCover = storyWrap.find( '.story-cover img' )
                        self.addAmbient( storyCover[ 0 ] ) 
                        self.initSecondarySlider( storyWrap );
                        self.afterLastSlide();
                        self.actionButtons.appendTo( storyWrap.parent() )
                        self.container.find( '.story-arrows' ).appendTo( storyWrap.parent() )
                        self.container.addClass( 'added' )
                        self.innerStories.parent().addClass( 'open' )
                    }
                },
                complete: function() {
                    self.storiesWrap.removeClass( 'retrieving-stories' )
                }
            })
        },
        close: function(){
            let self = this
            self.container.find( '.action-btn.close' ).on( 'click', function(){
                $( 'body' ).removeClass( 'web-stories--open' )
                self.innerStories.parent().removeClass( 'open' )
                self.storiesWrap.slick( 'unslick' )
                self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` ).slick( 'unslick' )
                self.container.find( '.ambient-wrapper' ).css({
                    'background-image': ''
                })
                self.container.find( '.action-btn.pause' ).removeClass( 'paused' )
                self.activeStoryId =  null
                self.allStoryIds =  []
                self.activeStoryCount =  null
                self.innerStories.parent().removeClass(function(index, className) {
                    return (className.match(/\bcat-[^\s]+/g) || []).join(' ');
                });
                self.storiesWrap.find( '.story' ).removeAttr( 'style' )
                self.container.find( '.action-btn' ).addClass( 'pause' )
                self.container.find( '.action-btn i' ).removeClass( 'fa-play' ).addClass( 'fa-pause' )
            })
        },
        pause: function(){
            let self = this
            self.container.find( '.action-btn.pause' ).on( 'click', function(){
                let _this = $( this )
                _this.find( 'i' ).toggleClass( 'fa-pause fa-play' )
                _this.toggleClass( 'paused' )
                self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` ).slick( _this.hasClass( 'paused' ) ? 'slickPause' : 'slickPlay' )
            })
        },
        initSecondarySlider: function( selector ) {
            $( selector ).slick({
                autoplay: true,
                arrows: true,
                fade: true,
                infinite: false,
                autoplaySpeed: 5000,
                speed: 300,
                dots: true,
                customPaging: function(slider, i) {
                    return `<button></button>`;
                },
                pauseOnFocus: false,
                pauseOnHover: false,
                prevArrow: `<button type="button" class="slick-prev"><i class="fa-solid fa-chevron-left"></i></button>`,
                nextArrow: `<button type="button" class="slick-next"><i class="fa-solid fa-chevron-right"></i></button>`,
                rtl: isRtl === '1' ? true : false,
            })
        },
        /* Add ambient */
        addAmbient: function( imageTag ) {
            let storyImage = $( imageTag ).attr( 'src' );

            this.container.find( '.ambient-wrapper' ).css({
                'background-image': 'url('+ storyImage +')'
            })
        },
        /* Close Popup on ESC Button Press */
        closePopupOnESCPress: function(){
            let self = this
            $(document).on( 'keydown', function( event ) {
                if( event.keyCode == 27 ) {
                    $( 'body' ).removeClass( 'web-stories--open' )
                    self.innerStories.parent().removeClass( 'open' )
                    self.storiesWrap.slick( 'unslick' )
                    self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` ).slick( 'unslick' )
                    self.container.find( '.action-btn.pause' ).removeClass( 'paused' )
                    self.activeStoryId =  null
                    self.allStoryIds =  []
                    self.activeStoryCount =  null
                    self.innerStories.parent().removeClass(function(index, className) {
                        return (className.match(/\bcat-[^\s]+/g) || []).join(' ');
                    });
                    self.storiesWrap.find( '.story' ).removeAttr( 'style' )
                    self.container.find( '.action-btn' ).addClass( 'pause' )
                    self.container.find( '.action-btn i' ).removeClass( 'fa-play' ).addClass( 'fa-pause' )
                }
            });
        },
        /* Scroll Button Handles */
        scrollButtons: function() {
            let self = this
            self.container.on( 'click', '.scroll-button', function(){
                let _this = $( this ),
                    leftButton = _this.hasClass( 'left' ),
                    rightButton = _this.hasClass( 'right' ),
                    storiesWrap = _this.siblings( '.stories-wrap' ),
                    sign = '-'
                if( leftButton ) sign = '-'
                if( rightButton ) sign = '+'
                storiesWrap.animate({
                    scrollLeft: `${ sign }=100`
                })
            })
        }
    }
    WebStories.init();
    
    /**
     * MARK: Sticky Posts
     */
    const StickyPosts = {
        container: $( '.one-newspaper-sticky-posts' ),
        init: function() {
            if( this.container.length ) {
                this.click()
                this.zIndex()
            }
        },
        click: function(){
            let self = this
            this.container.on( 'click', '.indicator.active', function(){
                let _this = $( this )
                _this.removeClass( 'active' ).siblings().addClass( 'active' )
                _this.parent().siblings( '.post.append' ).toggleClass( 'hide' )
                if( ! _this.parents( '.post-list' ).hasClass( 'added' ) ) self.ajaxCall()
            })
        },
        /* Adding z-index */
        zIndex: function(){
            let initialZindex = this.container.find( '.post' ).length
            this.container.find( '.post' ).each(function(){
                let _this = $( this )
                _this.css({
                    'z-index': initialZindex--
                })
            })
        },
        ajaxCall: function(){
            let self = this
            $.ajax({
                method: 'POST',
                url: ajaxUrl,
                data: {
                    action: 'one_newspaper_sticky_posts_ajax_call',
                    _wpnonce: _wpnonce
                },
                beforeSend: function() {
                    self.container.find( '.post-list' ).addClass( 'retrieving-stories' )
                },
                success: function( result ) {
                    let { success, data } = result
                    if( success ) {
                        self.container.find( '.post:last' ).after( data )
                        self.container.find( '.post-list' ).addClass( 'added' )
                        self.zIndex()
                    }
                },
                complete: function() {
                    self.container.find( '.post-list' ).removeClass( 'retrieving-stories' )
                }
            })
        }
    }
    StickyPosts.init()

    /**
     * MARK: SEARCH QUERY
     */
    const SearchQuery = {
        container: $( 'body.search .filter-wrapper' ),
        query: {
            'post_type': [],
            'post_status': 'publish',
            'category__in': [],
            'tag__in': [],
            's': '',
            'author__in': [],
            'date_query': {
                'relation': 'OR',
            },
            'after': {
                'after': '',
                'inclusive': true
            },
            'before': {
                'before': '',
                'inclusive': true
            },
            'paged': 1
        },
        clickedButton: 'filter',
        hasQueryChanged: false,
        init: function() {
            if( this.container.length ) {
                let datePickerObj = {
                    changeMonth: true,  // adds month dropdown
                    changeYear: true,   // adds year dropdown
                    yearRange: "1900:2050", // optional: limit years,
                    dateFormat: "M dd, y",
                    monthNamesShort: [
                        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
                    ]
                }
                this.container.find( '#before' ).datepicker( datePickerObj )
                this.container.find( '#after' ).datepicker( datePickerObj )
                this.filterClick()
                this.headClick()
                this.checkboxChange()
                this.datepickerChange()
                this.loadMoreClick()
                this.checkboxClear()
                this.clearSearchQuery()
            }
        },
        filterClick: function() {
            let self = this
            this.container.on( 'click', '.filter-button', function(){
                if( ! self.hasQueryChanged ) return
                let _this = $( this ),
                    searchField = _this.parent().siblings( '.page-header' ).find( '.one-newspaper-search-page .search-form .search-field' ),
                    searchValue = searchField.val()

                self.clickedButton = 'filter'
                self.query.s = searchValue
                self.query.paged = 1
                self.ajaxCall()
                if( self.hasQueryChanged ) {
                    self.hasQueryChanged = false
                    _this.addClass( 'disabled' )
                }
            })
        },
        ajaxCall: function() {
            let self = this,
                contentWrap = self.container.siblings( '.post-inner-wrapper' ).find( '.news-list-wrap ' ),
                hasLoadedClass = contentWrap.hasClass( 'loaded' ),
                loadMoreButton = contentWrap.siblings( '.pagination' ).find( '.ajax-load-more' )
            $.ajax({
                method: 'POST',
                url: ajaxUrl,
                data: {
                    action: 'one_newspaper_search_page_ajax_call',
                    _wpnonce: _wpnonce,
                    query: self.query,
                    clickedButton: self.clickedButton
                },
                beforeSend: function() {
                    contentWrap.addClass( 'retrieving-posts' )
                    loadMoreButton.text( 'Retrieving posts...' )
                },
                success: function( result ) {
                    let { success, data } = result
                    if( self.clickedButton === 'filter' ) contentWrap.empty()
                    if( ! success ) {
                        let { message } = data
                        self.container.siblings().find( '.pagination' ).find( '.ajax-load-more' ).hide()
                        self.container.siblings().find( '.news-list-wrap' ).append( message )
                    } else {
                        contentWrap.append( data )
                        self.container.siblings().find( '.pagination' ).find( '.ajax-load-more' ).show()
                        self.container.siblings().find( '.pagination' ).find( '.failure-message' ).remove()
                    }
                },
                complete: function() {
                    contentWrap.removeClass( 'retrieving-posts' )
                    if( ! hasLoadedClass ) contentWrap.addClass( 'loaded' )
                    loadMoreButton.text( 'Load More' )
                }
            })
        },
        headClick: function(){
            let self = this
            this.container.on( 'click', '.filter .head', function(){
                let _this = $( this )
                self.toggleClass( _this )
            })
        },
        checkboxChange: function() {
            let self = this
            this.container.on( 'change', '.filter .body .item input[type="checkbox"]', function(){
                let _this = $( this ),
                    value = _this.val(),
                    isChecked = _this.is( ':checked' ),
                    parent = _this.parents( '.filter' ),
                    isType = parent.hasClass( 'type' ),
                    isAuthor = parent.hasClass( 'authors' ),
                    isCategory = parent.hasClass( 'categories' ),
                    isTag = parent.hasClass( 'tags' ),
                    param = ''

                if( ! self.hasQueryChanged ) {
                    self.hasQueryChanged = true
                    parent.siblings( '.filter-button' ).removeClass( 'disabled' )
                    parent.siblings( '.clear-button' ).removeClass( 'disabled' )
                }
                if( isType ) {
                    param = 'post_type'
                } else if( isAuthor ) {
                    param = 'author__in'
                } else if( isCategory ) {
                    param = 'category__in'
                } else if( isTag ) {
                    param = 'tag__in'
                }

                if( isChecked ) {
                    self.query[ param ] = [ ...self.query[ param ], value ]
                } else {
                    self.query[ param ] = self.query[ param ].filter( item => item !== value );
                }
            })
        },
        datepickerChange: function() {
            let self = this
            this.container.on( 'change focus', '.filter input[type="text"]', function(){
                let _this = $( this ),
                    value = _this.val(),
                    parent = _this.parent(),
                    isBefore = parent.hasClass( 'before' ),
                    isAfter = parent.hasClass( 'after' ),
                    param = ''

                if( ! self.hasQueryChanged ) {
                    self.hasQueryChanged = true
                    parent.siblings( '.filter-button' ).removeClass( 'disabled' )
                    parent.siblings( '.clear-button' ).removeClass( 'disabled' )
                }

                if( isBefore ) {
                    param = 'before'
                } else if( isAfter ) {
                    param = 'after'
                }

                self.query[ param ] = { ...self.query[ param ], [ param ]: value }

                self.toggleClass( _this )
            })
        },
        toggleClass: function( _this ) {
            let parent = _this.parents( '.filter' )
            parent.toggleClass( 'active' )
            parent.siblings( '.filter' ).removeClass( 'active' )
            onElementOutsideClick( _this.parents( '.filter-wrapper' ), function(){
                parent.removeClass( 'active' )
            })
        },
        loadMoreClick: function() {
            let self = this
            this.container.siblings().find( '.pagination' ).on( 'click', '.ajax-load-more', function() {
                self.query.paged++
                self.clickedButton = 'load-more'
                self.ajaxCall()
            })
        },
        checkboxClear: function() {
            this.container.on( 'click', '.filter .clear', function() {
                let _this = $( this )
                _this.siblings().find( 'input[type="checkbox"]' ).prop( 'checked', false )
            })
        },
        clearSearchQuery: function() {
            this.container.on( 'click', '.clear-button', function() {
                let _this = $( this )
                if( _this.hasClass( 'disabled' ) ) return
                location.reload()
            })
        }
    }
    SearchQuery.init()

    /**
     * Responsive header builder toggle button
     * 
     * @since 1.0.0
     */
    var responsiveHeaderBuilderWrapper = $('.bb-bldr--responsive')
    if( responsiveHeaderBuilderWrapper.length > 0 ) {
        let toggleButton = responsiveHeaderBuilderWrapper.find( '.toggle-button-wrapper' )
        toggleButton.on("click", function() {
            let _this = $(this)
            _this.parents( '.row-wrap' ).siblings( '.bb-bldr-row.mobile-canvas' ).toggleClass( 'open' )
        })
    }

    /**
     * Header Sticky
     */
    const { headerSticky } = oneNewspaperObject
    if( headerSticky ) {
        let lastScroll = 0,
            sidebarSelector = $( 'aside#secondary.widget-area' ),
            allStickyRows = $( 'header#masthead .row-sticky' ),
            dynamicTopValue = 0
            allStickyRows.each(function(){
                let _this = $( this )
                dynamicTopValue += _this.outerHeight()
            })
        if( isLoggedIn ) dynamicTopValue += wpadminbar
        $( window ).on('scroll',function() {
            oneNewspaperCalculateHeaderHeight()
            let scroll = $( this ).scrollTop(),
                mainHeaderContainer = $('body header.site-header')

            if( $( 'header#masthead' ).hasClass( 'fixed--on' ) && $( 'body' ).hasClass( 'one-newspaper-sticky-sidebar--enabled' ) ) {
                sidebarSelector.css({
                    'top': `${ dynamicTopValue }px`
                })
            } else {
                sidebarSelector.css({
                    'top': ( isLoggedIn ) ? `${ wpadminbar }px` : '0px'
                })
            }
            if( scroll >= 200 ) {
                mainHeaderContainer.addClass( 'header-sticky--enabled' ).removeClass( 'header-sticky--disabled' )
            } else {
                mainHeaderContainer.addClass( 'header-sticky--disabled' ).removeClass( 'header-sticky--enabled' )
            }

            if( scroll > 50 ) {
                if ( scroll > lastScroll ) {
                    /* Scrolling Down */
                    mainHeaderContainer.addClass( 'fixed--on' ).removeClass( 'fixed--off' )
                } else {
                    /* Scrolling UP */
                    mainHeaderContainer.removeClass( 'fixed--on' ).addClass( 'fixed--off' )
                }
                lastScroll = scroll
            } else {
                $( mainHeaderContainer ).addClass("header-sticky--disabled fixed--off").removeClass( 'fixed--on' );
            }
        });
    }

    /**
     * Mark: Progress Bar
     */
    const progressBar = {
        init: function() {
            this.scrollEvent()
        },
        selectors: {
            'single-progress': {
                'selector': 'body.page .single-progress, body.single .single-progress, body.archive .single-progress, body.search .single-progress',
                'property': 'width',
                'usesBackground': false
            }
        },
        totalScrollableArea: $('body')[0].clientHeight,
        sizeOfScrollBar: window.innerHeight,
        scrollEvent: function() {
            let self = this
            $(window).on("scroll", function(){
                let scrollBarPosition = window.scrollY
                if( scrollBarPosition < 1 ) {   /* Hide when Top is reached */
                    $( self.selectors['single-progress'].selector ).hide()
                } else {
                    $( self.selectors['single-progress'].selector ).show()
                }
                let width = self.getWidth( scrollBarPosition )
                if( self.isBottom() ) width = 100   /* Run when bottom is reached */
                let background = `conic-gradient(${ themeColor } ${ width }%, transparent ${ width }%)`
                Object.entries( self.selectors ).forEach(( current ) => {
                    const [ ID, selectorValues ] = current
                    const { selector, property, usesBackground } = selectorValues
                    if( usesBackground ) {
                        $( selector ).attr( 'style', property + ': ' + background )
                    } else {
                        $( selector ).css( property, width + '%' )
                    }
                })
            })
        },
        getWidth: function( scrollBarPosition ) {
            let width = ( ( ( scrollBarPosition + this.sizeOfScrollBar ) / this.totalScrollableArea ) * 100 )
            return Math.round( width );
        },
        isBottom: function() {
            if ( $(window).scrollTop() + $(window).height() >= $(document).height()) return true
        }
    }
    progressBar.init()
})