jQuery(document).ready(function($) {
    const { ajaxUrl, themeColor, _wpnonce: wpnonce, ticker, headerMarginBottom = 40, isRtl, headerSticky } = blogPostXObject,
        globalPrevIcon = blogPostXObject.globalPrevIcon.value || 'fa-solid fa-chevron-left',
        globalNextIcon = blogPostXObject.globalNextIcon.value || 'fa-solid fa-chevron-right',
        isLoggedIn = $('body').hasClass('admin-bar'),
        wpadminbar = $('body #wpadminbar').height()

    /**
     * Calculate header height and set margin top
     */
    function calculateHeaderHeight() {
        let header = $( 'body header#masthead' ),
            element = $( 'body .row.blog-postx-single-header' ),
            height = isLoggedIn ? header.outerHeight( true ) + wpadminbar : header.outerHeight( true ),
            breadcrumbHeight = $( 'body .blog-postx-container.breadcrumb-wrapper' ).outerHeight( true )

            if( breadcrumbHeight && $( '.single-post--layout-seven').length ) height += breadcrumbHeight
            if( $( '.single-post--layout-three').length ) {
                element = $( 'body .blog-postx-main-wrap' )
                if( $(window).width() <= 940 ) {
                    height = headerMarginBottom.tablet.bottom
                } else if( $(window).width() <= 610 ) {
                    height = headerMarginBottom.smartphone.bottom
                } else {
                    height = headerMarginBottom.desktop.bottom
                }
            }
        element.css({
            'margin-top': `-${ height }px`
        })
    }

    /**
     * MARK: SINGLE LAYOUT SEVEN
     */
    let singleLayoutSeven = $( 'body.single.single-post--layout-seven, body.single.single-post--layout-three' )
    if( singleLayoutSeven.length ) {
        $( window ).on( 'resize', function(){
            calculateHeaderHeight()
        })
        calculateHeaderHeight()
    }

    // top date time
    var timeElement = $( ".top-date-time .time" )
    if( timeElement.length > 0 ) {
        setInterval(function() {
            timeElement.html(new Date().toLocaleTimeString())
        },1000);
    }
    
    // handle preloader
    function blogPostXPreloader( timeOut = 3000 ) {
        setTimeout(function() {
            $('body .blog_postx_loading_box').hide();
        }, timeOut);
    }

    blogPostXPreloader()

    $(window).on('unload', function(){
        $.removeCookie('showPreloader', { path: '/' })
    })

    // breadcrumb separator
    var breadcrumbSeparatorContainer = $('.blog-postx-breadcrumb-element')
    if( breadcrumbSeparatorContainer.length > 0 ) {
        var listElement = breadcrumbSeparatorContainer.find('li.trail-item')
        var elementToAppend = '<span class="item-separator"><i class="fa-solid fa-angles-right"></i></span>'
        listElement.append(elementToAppend)
    }

    // header - normal search
    var searchSectionContainer = $('.search-wrap')
    if( searchSectionContainer.length > 0 ) {
        searchSectionContainer.on( 'click', '.search-trigger', function(){
            var _this = $(this)
            _this.siblings().show()
            _this.parent().addClass('toggled')
            _this.siblings().find('.search-field').focus()
            onElementOutsideClick( _this.parent(), function(){
                _this.parent().removeClass( 'toggled' )
                _this.siblings().find( '.search-form-close' ).click()
                $( 'body' ).removeClass( 'search-active' )
            })
            if( ! _this.parent().hasClass( 'search-type--default' ) ) $( 'body' ).addClass( 'search-active' )
        })

        // close search popup
        var closeButton = searchSectionContainer.find('.search-form-wrap')
        if( closeButton.length > 0 ) {
            closeButton.on('click', '.search-form-close', function(){
                var _thisButton = $(this), parentElement = _thisButton.parents('.search-wrap')
                parentElement.removeClass('toggled')
                _thisButton.parents( '.search-form-wrap' ).hide()
                $('body').removeClass( 'search-active' )
            })
        }

        // on ESC button click
        $(document).on('keydown', function( event ){
            if( event.keyCode == 27 ) {
                closeButton.hide()
                closeButton.parent().removeClass('toggled')
            }
        })
    }
    
    // check for dark mode drafts
    if( localStorage.getItem( "themeMode" ) != null ) {
        if( localStorage.getItem("themeMode") == "dark" ) {
            $('body').addClass( 'blog-postx-dark-mode' ).removeClass('blog-postx-light-mode')
        } else {
            $('body').addClass( 'blog-postx-light-mode' ).removeClass('blog-postx-dark-mode')
        }
    }

    // header - theme mode
    var themeModeContainer = $('.mode-toggle-wrap')
    if( themeModeContainer.length > 0 ) {
        themeModeContainer.on( 'click', '.mode-toggle', function(){
            var _this = $(this), bodyElement = _this.parents('body')
            if( bodyElement.hasClass('blog-postx-dark-mode') ) {
                localStorage.setItem( 'themeMode', 'light' )
                bodyElement.removeClass('blog-postx-dark-mode').addClass('blog-postx-light-mode')
            } else {
                localStorage.setItem( 'themeMode', 'dark' )
                bodyElement.removeClass('blog-postx-light-mode').addClass('blog-postx-dark-mode')
            }
        })
    }

    // header - canvas menu
    var canvasMenuContainer = $('.blog-postx-canvas-menu')
    if( canvasMenuContainer.length > 0 ) {
        canvasMenuContainer.on( 'click', '.canvas-menu-icon', function() {
            var _this = $(this), bodyElement = _this.parents('body')
            bodyElement.toggleClass('blog-postx-model-open');
            onElementOutsideClick( _this.siblings(), function(){
                bodyElement.removeClass( 'blog-postx-model-open' )
            })
        })
    }

    // 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();
        })
    }

    // back to top script
    if( $( "#blog-postx-scroll-to-top" ).length ) {
        var scrollContainer = $( "#blog-postx-scroll-to-top" );
        $(window).scroll(function() {
            if ( $(this).scrollTop() > 500 ) {
                scrollContainer.addClass('show');
            } else {
                scrollContainer.removeClass('show');
            }
        });
        scrollContainer.on( 'click', '.scroll-to-top-wrapper, .icon-text', function(event) {
            event.preventDefault();
            // Animate the scrolling motion.
            $("html, body").animate({scrollTop:0},"slow");
        });
    }

    // cursor animation
    var cursorContainer = $('.blog-postx-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"], #blog-postx-scroll-to-top .icon-text, #blog-postx-scroll-to-top .icon-holder, .video-playlist-wrap .playlist-items-wrap .video-item, .thumb-video-highlight-text .thumb-controller, .pagination.pagination-type--ajax-load-more, .blog-postx-widget-loader .load-more, .mode-toggle-wrap .mode-toggle, .blog-postx-canvas-menu .canvas-menu-icon, .blog-postx-table-of-content .toc-fixed-icon, .blog-postx-social-share.show-on-click'
        $( selector ).on( 'mouseover', function(){
            $( cursorContainer ).addClass( 'isActive' )
        })
        $( selector ).on( 'mouseout', function(){
            $( cursorContainer ).removeClass( 'isActive' )
        })
    }

    /**
     * Initialize Slick js
     * 
     * @since 1.0.0
     */
    const blogPostxInitializeSlick = ( props, returnInstance = false ) => {
        let { responsive = [], dots = false, arrows = true, fade = false, infinite = true, speed = 300, autoplay = false, autoplaySpeed = 3000, slidesToShow = 1, slidesToScroll = 1, prevIcon = globalPrevIcon, nextIcon = globalNextIcon, 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;
    }

    /**
     * Main Banner JS
     * 
     * @since 1.0.0
     */
    var fullWidthBannerContainer = $('#blog-postx-main-banner-section')
    if( fullWidthBannerContainer.length > 0 ) {
        blogPostxInitializeSlick({
            arrows: true,
            fade: true,
            infinite: true,
            autoplay: false,
            speed: 500,
            responsive: false,
            selector: fullWidthBannerContainer.find( '.main-banner-wrap' )
        })
    }

    /**
     * Carousel JS
     * 
     * @since 1.0.0
     */
    var carouselContainer = $('.blog-postx-carousel-section')
    if( carouselContainer.length > 0 ) {
        let carouselSlickObject = {
            arrows: true,
            infinite: true,
            speed: 500,
            slidesToScroll: 1,
            slidesToShow: 3
        }
        carouselSlickObject.selector = carouselContainer.find( '.carousel-wrap' )
        blogPostxInitializeSlick({
            ...carouselSlickObject,
            gap: 24
        })
    }

    /**
     * Carousel Posts JS
     * 
     * @since 1.0.0
     */
    var cpWidgets = $( ".widget_blog_postx_carousel_widget" )
    cpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_blog_postx_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 ) {
            blogPostxInitializeSlick({
                autoplay: true,
                arrows: true,
                infinite: true,
                vertical: false,
                selector: _this.find( '.carousel-posts-wrap' ),
                responsive: false,
                fade: true
            })
        }
    })

    // handle the post gallery post format
    var postGalleryElems = $("body #primary article.format-gallery .post-thumbnail-wrapper")
    if( postGalleryElems.length > 0 ) {
        postGalleryElems.each(function() {
            let _this = $( this )
            blogPostxInitializeSlick({ selector: _this.find( '.thumbnail-gallery-slider' ), responsive: false })
        })
    }

    /**
     * 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( '.bb-bldr-row' ).siblings( '.bb-bldr-row.mobile-canvas' ).toggleClass( 'open' )
        })
    }

    const progressBar = {
        init: function() {
            this.scrollEvent()
        },
        selectors: {
            'scroll-to-top': {
                'selector': '#blog-postx-scroll-to-top.display--fixed .scroll-to-top-wrapper',
                'property': 'background',
                'usesBackground': true
            },
            '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 +'%)'
                $( 'body.single .post-read-time-wrap' ).attr( 'style', 'background: ' + background )
                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()

    /**
     * Ticker News
     * 
     * @since 1.0.0
     */
    let tickerNewsContainer = $( '.blog-postx-ticker-news' )
    if( tickerNewsContainer.length > 0 ) {
        if( $.fn.marquee ) {
            let { direction } = ticker
            let marqueeInstance = tickerNewsContainer.find( ".ticker-item-wrap" ).marquee({
                duration: 15000,
                gap: 20,
                delayBeforeStart: 0,
                direction: ( direction ? 'right' : 'left' ),
                duplicated: true,
                startVisible: true,
                pauseOnHover: true
            });
            tickerNewsContainer.on( "click", ".controller-icon", function() {
                let _this = $( this ),
                    parent = _this.parent();
                    
                _this.find( 'i' ).removeClass().addClass( parent.hasClass( 'playing' ) ? 'fa-solid fa-pause' : 'fa-solid fa-play' )
                parent.toggleClass( 'playing paused' )
                marqueeInstance.marquee( "toggle" )
            })
        }
    }

    $( '.video-overlay' ).on( 'click', function(){
        let _this = $( this ),
            iframe = _this.siblings( 'iframe' ),
            parent = _this.parents( '.blog-postx-article-inner' ),
            src = iframe.attr( 'src' ),
            newSrc = '';
        _this.remove()
        parent.toggleClass( 'playing' )
        if( parent.hasClass( 'playing' ) ) {
            newSrc = src + '&autoplay=1';
        } else {
            newSrc = src.replace(/[?&]autoplay=1/, '');
        }
        iframe.attr( 'src', newSrc )
    })

    /**
     * Sticky Posts
     */
    const StickyPosts = {
        container: $( '.blog-postx-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({
                    author: self.container.data( 'author' ),
                    date: self.container.data( 'date' )
                })
            })
        },
        /* 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( params ){
            let self = this
            $.ajax({
                method: 'POST',
                url: ajaxUrl,
                data: {
                    action: 'blog_postx_sticky_posts_ajax_call',
                    _wpnonce: wpnonce,
                    ...params
                },
                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()

    /**
     * Web Stories
     */
    const WebStories = {
        container: $( '.blog-postx-web-stories' ),
        activeStoryId: null,
        allStoryIds: [],
        activeStoryCount: null,
        storiesWrap: $( '.blog-postx-web-stories .stories-wrap' ),
        innerStories: $( '.blog-postx-web-stories .inner-stories-wrap .inner-stories' ),
        actionButtons: $( '.blog-postx-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 {
                    blogPostxInitializeSlick({
                        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: 'blog_postx_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 ) {
                        blogPostxInitializeSlick({
                            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: SEARCH QUERY
     */
    const SearchQuery = {
        container: $( 'body.search .filter-wrapper' ),
        query: {
            'post_type': [],
            'post_status': 'publish',
            's': '',
            'author__in': [],
            'paged': 1
        },
        clickedButton: 'filter',
        hasQueryChanged: false,
        init: function() {
            if( this.container.length ) {
                this.filterClick()
                this.headClick()
                this.checkboxChange()
                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( '.blog_postx_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( '.blog-postx-inner-content-wrap' ),
                hasLoadedClass = contentWrap.hasClass( 'loaded' )
            $.ajax({
                method: 'POST',
                url: ajaxUrl,
                data: {
                    action: 'blog_postx_search_page_ajax_call',
                    _wpnonce: wpnonce,
                    query: self.query,
                    clickedButton: self.clickedButton
                },
                beforeSend: function() {
                    contentWrap.addClass( 'retrieving-posts' )
                },
                success: function( result ) {
                    let { success, data } = result
                    if( self.clickedButton === 'filter' ) contentWrap.empty()
                    if( ! success ) {
                        let { message } = data
                        self.container.siblings( '.pagination' ).find( '.ajax-load-more-wrap' ).hide()
                        self.container.siblings( '.pagination' ).append( message )
                    } else {
                        contentWrap.append( data )
                        self.container.siblings( '.pagination' ).find( '.ajax-load-more-wrap' ).show()
                        self.container.siblings( '.pagination' ).find( '.failure-message' ).remove()
                    }
                },
                complete: function() {
                    contentWrap.removeClass( 'retrieving-posts' )
                    if( ! hasLoadedClass ) contentWrap.addClass( 'loaded' )
                }
            })
        },
        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' ),
                    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'
                }

                if( isChecked ) {
                    self.query[ param ] = [ ...self.query[ param ], value ]
                } else {
                    self.query[ param ] = self.query[ param ].filter( item => item !== value );
                }
            })
        },
        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( '.pagination' ).on( 'click', '.ajax-load-more-wrap.blog-postx-button', function() {
                let _this = $( this )
                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
                _this.parent().siblings( '.page-header' ).find( '.blog_postx_search_page .search-form' ).submit()
            })
        }
    }
    SearchQuery.init()

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

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

    function blogPostxAddDeviceClass() {
        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' )
        }
    }
    blogPostxAddDeviceClass();

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

    // header sticky
    if( headerSticky ) {
        let 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(){
            blogPostxCalculateHeaderHeight()
            if( $('header#masthead').hasClass( 'fixed--on' ) && $('body').hasClass( 'blog-postx-stickey-sidebar--enabled' ) ) {
                sidebarSelector.css({
                    'top': dynamicTopValue + 'px'
                })
            } else {
                sidebarSelector.css({
                    'top': ( isLoggedIn ) ? `${ wpadminbar }px` : '0px'
                })
            }
            let scroll = $(this).scrollTop(),
                mainHeaderContainer = $( 'header.site-header' )

            if( scroll >= $( 'header.site-header' ).height() ) {
                mainHeaderContainer.addClass('header-sticky--enabled').removeClass('header-sticky--disabled')
            } else {
                mainHeaderContainer.addClass('header-sticky--disabled').removeClass('header-sticky--enabled')
            }

            if( scroll > 50 ) {
                mainHeaderContainer.removeClass( 'fixed--off' ).addClass( 'fixed--on' )
            } else {
                $( mainHeaderContainer ).addClass("header-sticky--disabled fixed--off").removeClass( 'fixed--on' );
            }
        })
    }
})