(function( $ ){
    /**
     * This file handle all ajax related js
     * 
     * @package Blog Bee
     * @since 1.0.0
     */
    const { ajaxUrl, webStories, isRTL } = BlogBeeAjaxConfig

    const Body = $( 'body' ),
        openState = {
            searchFilter: false
        }

      /**
     * MARK: Outside click handle
     * 
     * @since 1.0.0
     */
    const HandleOutsideClick = {
        /**
         * Init
         * 
         * @since 1.0.0
         */
        init: function() {
            this.bindEvent()
        },
        /**
         * Bind event
         * 
         * @since 1.0.0
         */
        bindEvent: function(){
            $( document ).on( 'click', ( event ) => {
                const _this = $( event.target )
                this.handleSearchFilterOutsideClick( _this )
                this.handleSearchFieldOutsideClick( _this )
            } )
        },
        /**
         * Handle search filter outside click
         * 
         * @since 1.0.0
         */
        handleSearchFilterOutsideClick: function( clickedElement ){
            const container = ! SearchFilter.container.is( clickedElement ) && ! SearchFilter.container.has( clickedElement ).length

            if( openState.searchFilter && container ) {
                SearchFilter.container.children().removeClass( 'active' )
                openState.searchFilter = false
            }
        },
        /**
         * Handle search field outside click
         * 
         * @since 1.0.0
         */
        handleSearchFieldOutsideClick: function( clickedElement ){
            const container = ! SearchFieldLiveSearch.container.is( clickedElement ) && ! SearchFieldLiveSearch.container.has( clickedElement ).length

            if( container ) {
                SearchFieldLiveSearch.container.removeClass( 'loaded' )
            }
        }
    }

    /**
     * MARK: Helper Functions
     * 
     * @since 1.0.0
     */
    const Helpers = {
        /**
         * Sanitize bool
         * 
         * @since 1.0.0
         * @param { string }    param   The value to sanitize
         */
        sanitizeBool( param ){
            if( param === '1' ) {
                return true
            } else if( param === '0' ) {
                return false
            } else {
                return false
            }
        }
    }

    /**
     * Nonce manager
     * to prevent nonce from going state when a cache plugin is used
     * that caches the site and when an ajax call is triggered nonce has
     * already expired causing 403(forbidden) when ajax is called.
     * 
     * @since 1.0.0
     */
    const NonceManager = {
        /**
         * Current nonce
         * 
         * @since 1.0.0
         */
        nonce: null,
        /**
         * Get a fresh new nonce
         * 
         * @since 1.0.0
         */
        getNonce: function() {
            let self = this
            return new Promise( resolve => {
                if( self.nonce ) {
                    resolve( self.nonce )
                    return
                }
                $.post( ajaxUrl, { action: 'get_nonce' }, function( res ) {
                    if( res.success ) {
                        self.nonce = res.data.nonce
                        resolve( self.nonce )
                    }
                })
            })
        }
    }

    /**
     * Search Field Live Search js
     * MARK: Search Field
     * 
     * @since 1.0.0
     */
    const SearchFieldLiveSearch = {
        /**
         * Container
         * 
         * @since 1.0.0
         */
        get container() {
            if( ! this._container ) {
                this._container = $( '.bbe-search-field' )
            }
            return this._container
        },
        /**
         * Live Search container
         * 
         * @since 1.0.0
         */
        get liveSearchContainer() {
            if( ! this._liveSearchContainer ) {
                this._liveSearchContainer = this.container.find( '.bbe-live-search' )
            }
            return this._liveSearchContainer
        },
        /**
         * Initialization Function
         * 
         * @since 1.0.0
         */
        init() {
            if( this.container.length && this.liveSearchContainer.length ) {
                this.bindChangeEvent()
                this.bindViewAllResultsClick()
            }
        },
        /**
         * Bind change event
         * 
         * @since 1.0.0
         */
        bindChangeEvent() {
            let self = this,
                timeout
            this.container.on( 'input', '.search-field', function(){
                let _this = $( this ),
                    value = _this.val()

                self.container.addClass( 'retrieving' )
                clearTimeout( timeout )
                timeout = setTimeout( () => {
                    self.bindAjax( value )
                }, 300 )
            } )
        },
        /**
         * Bind ajax
         * 
         * @sicne 1.0.0
         * @param { string } value The typed value
         */
        bindAjax( value ) {
            NonceManager.getNonce().then( nonce => {
                $.ajax( {
                    method: 'POST',
                    url: ajaxUrl,
                    data: {
                        action: 'header_search_ajax',
                        _wpnonce: nonce,
                        search_query: value
                    },
                    success: ( response ) => {
                        this.liveSearchContainer.find( '.article-wrap' ).empty()
                        this.container.addClass( 'loaded' )
                        if( response.data.message ) this.liveSearchContainer.find( '.article-wrap' ).append( response.data.message )
                        if( response.success && response.data.continue ) {
                            this.liveSearchContainer.find( '.no-results-label' ).addClass( 'hidden' )
                            this.liveSearchContainer.find( '.ajax-button' ).removeClass( 'hidden' )
                        }
                        if( ! response.data.continue ) {
                            this.liveSearchContainer.find( '.ajax-button' ).addClass( 'hidden' )
                            this.liveSearchContainer.find( '.no-results-label' ).removeClass( 'hidden' )
                        }
                    },
                    complete: () => {
                        this.container.removeClass( 'retrieving' )
                    }
                } )
            } ) 
        },
        /**
         * Bind view all results click
         * 
         * @since 1.0.0
         */
        bindViewAllResultsClick() {
            this.liveSearchContainer.on( 'click', '.ajax-button .label', () => {
                this.container.find( '.search-form' ).trigger( 'submit' )
            } )
        }
    }

    /**
     * Search Icon Live Search js
     * MARK: Search Icon
     * 
     * @since 1.0.0
     */
    const SearchIconLiveSearch = {
        /**
         * Container
         * 
         * @since 1.0.0
         */
        get container() {
            if( ! this._container ) {
                this._container = $( '.bbe-search-icon' )
            }
            return this._container
        },
        /**
         * Search form container
         * 
         * @since 1.0.0
         */
        get inputSearchForm() {
            if( ! this._inputSearchForm ) {
                let formWrapper = $( '#masthead .form-wrapper' )
                if( ! formWrapper.hasClass( 'layout--one' ) ) {
                    this._inputSearchForm = formWrapper.find( '.search-form' )
                } else {
                    this._inputSearchForm = this.container.find( '.search-form' )
                }
            }
            return this._inputSearchForm
        },
        /**
         * Live Search container
         * 
         * @since 1.0.0
         */
        get liveSearchContainer() {
            if( ! this._liveSearchContainer ) {
                this._liveSearchContainer = this.inputSearchForm.siblings( '.bbe-live-search' )
            }
            return this._liveSearchContainer
        },
        /**
         * Initialization Function
         * 
         * @since 1.0.0
         */
        init() {
            if( this.container.length && this.liveSearchContainer.length ) {
                this.bindChangeEvent()
                this.bindViewAllResultsClick()
            }
        },
        /**
         * Bind change event
         * 
         * @since 1.0.0
         */
        bindChangeEvent() {
            let self = this,
                timeout
            this.inputSearchForm.on( 'input', '.search-field', function(){
                let _this = $( this ),
                    value = _this.val()

                self.container.addClass( 'retrieving' )
                clearTimeout( timeout )
                timeout = setTimeout( () => {
                    self.bindAjax( value )
                }, 300 )
            } )
        },
        /**
         * Bind ajax
         * 
         * @sicne 1.0.0
         * @param { string } value The typed value
         */
        bindAjax( value ) {
            NonceManager.getNonce().then( nonce => {
                $.ajax( {
                    method: 'POST',
                    url: ajaxUrl,
                    data: {
                        action: 'header_search_ajax',
                        _wpnonce: nonce,
                        search_query: value
                    },
                    success: ( response ) => {
                        this.liveSearchContainer.find( '.article-wrap' ).empty()
                        this.inputSearchForm.parents( '.form-wrapper' ).addClass( 'loaded' )
                        if( response.data.message ) this.liveSearchContainer.find( '.article-wrap' ).append( response.data.message )
                        if( response.success && response.data.continue ) {
                            this.liveSearchContainer.find( '.no-results-label' ).addClass( 'hidden' )
                            this.liveSearchContainer.find( '.ajax-button' ).removeClass( 'hidden' )
                        }
                        if( ! response.data.continue ) {
                            this.liveSearchContainer.find( '.ajax-button' ).addClass( 'hidden' )
                            this.liveSearchContainer.find( '.no-results-label' ).removeClass( 'hidden' )
                        }
                    },
                    complete: () => {
                        this.container.removeClass( 'retrieving' )
                    }
                } )
            } )
        },
        /**
         * Bind view all results click
         * 
         * @since 1.0.0
         */
        bindViewAllResultsClick() {
            this.liveSearchContainer.on( 'click', '.ajax-button .label', () => {
                if( this.container.hasClass( 'layout--one' ) ) {
                    this.container.find( '.search-form' ).trigger( 'submit' )
                } else {
                    this.container.parents( '#masthead' ).children( '.form-wrapper' ).find( '.search-form' ).submit()
                }
            } )
        }
    }

    /**
     * MARK: Search Filter
     * 
     * @since 1.0.0
     */
    const SearchFilter = {
        /**
         * Container 
         * 
         * @since 1.0.0
         */
        get container() {
            if( ! this._container ) {
                this._container = $( 'body.search .filter-wrapper' )
            }
            return this._container
        },
        /**
         * WP_Query object
         * 
         * @since 1.0.0
         */
        query: {
            'post_type': [],
            'post_status': 'publish',
            'category__in': [],
            'tag__in': [],
            's': '',
            'author__in': [],
            'after': {},
            'before': {},
            'paged': 1
        },
        /**
         * Detect clicked button
         * 
         * @since 1.0.0
         */
        clickedButton: 'filter',
        /**
         * Detect whether or not the query should be changed
         * 
         * @since 1.0.0
         */
        hasQueryChanged: false,
        /**
         * Initialization
         * 
         * @since 1.0.0
         */
        init: function() {
            if( this.container.length ) {
                let self = this
                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"
                    ],
                    onSelect( dateString, inst ) {
                        const year = inst.currentYear
                        const month = inst.currentMonth + 1
                        const day = inst.currentDay
                        const parent = inst.input.parent()
                        const dateArr = {
                            year,
                            month,
                            day
                        }

                        if( parent.hasClass( 'after' ) ) {
                            self.query.after = dateArr
                        } else {
                            self.query.before = dateArr
                        }
                    }
                }
                this.container.find( '#before' ).datepicker( datePickerObj )
                this.container.find( '#after' ).datepicker( datePickerObj )
                this.bindSearchedQuery()
                this.filterClick()
                this.headClick()
                this.checkboxChange()
                this.datepickerChange()
                this.loadMoreClick()
                this.checkboxClear()
                this.clearSearchQuery()
            }
        },
        /**
         * Bind searched query
         * 
         * @since 1.0.0
         */
        bindSearchedQuery: function() {
            let searchField = this.container.siblings( '.page-header' ).find( '.search-form .search-field' )

            let value = searchField.val()

            let self = this

            // set it on page load
            this.query.s = value

            // update search query on field change
            searchField.on( 'input change', function() {
                let _this = $( this )
                self.query.s = _this.val()
            } )
        },
        /**
         * Bind filter button click
         * 
         * @since 1.0.0
         */
        filterClick: function() {
            let self = this
            this.container.on( 'click', '.filter-button', function(){
                if( ! self.hasQueryChanged ) return
                let _this = $( this ),
                    searchField = self.container.siblings( '.page-header' ).find( '.search-form .search-field' ),
                    searchValue = searchField.val()

                
                self.clickedButton = 'filter'
                self.query.paged = 1
                self.ajaxCall()
                if( self.hasQueryChanged ) {
                    self.hasQueryChanged = false
                    _this.addClass( 'disabled' )
                }
            })
        },
        /**
         * Bind ajax call
         * 
         * @since 1.0.0
         */
        ajaxCall: function() {
            let self = this,
                contentWrap = self.container.siblings( '.content-wrapper' ).find( '#primary .article-wrap' ),
                ajaxButton = contentWrap.siblings( '.ajax-wrapper' ),
                hasLoadedClass = contentWrap.hasClass( 'loaded' )
            NonceManager.getNonce().then( nonce => {
                $.ajax({
                    method: 'POST',
                    url: ajaxUrl,
                    data: {
                        action: 'search_filter_ajax_call',
                        _wpnonce: nonce,
                        query: self.query,
                        clickedButton: self.clickedButton
                    },
                    success: function( result ) {
                        let { success, data } = result
                        if( self.clickedButton === 'filter' ) contentWrap.empty()
                        
                        if( success && data.message ) contentWrap.append( data.message )
                        if( success && data.continue ) {
                            ajaxButton.find( '.no-results-label' ).addClass( 'hidden' )
                            ajaxButton.find( '.ajax-button' ).removeClass( 'hidden' )
                        } else {
                            ajaxButton.find( '.no-results-label' ).removeClass( 'hidden' )
                            ajaxButton.find( '.ajax-button' ).addClass( 'hidden' )
                        }
                    },
                    complete: function() {
                        ajaxButton.removeClass( 'retrieving' )
                        if( ! hasLoadedClass ) contentWrap.addClass( 'loaded' )
                    }
                })
            })
        },
        /**
         * Bind event to show checkbox dropdown
         * 
         * @since 1.0.0
         */
        headClick: function(){
            let self = this
            this.container.on( 'click', '.filter .head', function(){
                let _this = $( this )
                self.toggleClass( _this )
                openState.searchFilter = true
            })
        },
        /**
         * Bind checkbox change
         * 
         * @since 1.0.0
         */
        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 );
                }
            })
        },
        /**
         * Bind date picker change
         * 
         * @since 1.0.0
         */
        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 )
            })
        },
        /**
         * Toggle active clss
         * 
         * @param { Object } _this The current clicked instance
         * @since 1.0.0
         */
        toggleClass: function( _this ) {
            let parent = _this.parents( '.filter' )
            parent.toggleClass( 'active' )
            parent.siblings( '.filter' ).removeClass( 'active' )
        },
        /**
         * Bind load more click
         * 
         * @since 1.0.0
         */
        loadMoreClick: function() {
            let self = this
            this.container.siblings( '.content-wrapper' ).find( '#primary .ajax-button' ).on( 'click', function() {
                let _this = $( this )
                self.query.paged++
                self.clickedButton = 'load-more'

                _this.parents( '.ajax-wrapper' ).addClass( 'retrieving' )
                self.ajaxCall()
            })
        },
        /**
         * Bind currently opened dropdown clear button click
         * 
         * @since 1.0.0
         */
        checkboxClear: function() {
            this.container.on( 'click', '.filter .clear', function() {
                let _this = $( this )
                _this.siblings().find( 'input[type="checkbox"]' ).prop( 'checked', false )
            })
        },
        /**
         * Bind event to clear all checkboxes
         * 
         * @since 1.0.0
         */
        clearSearchQuery: function() {
            let self = this
            this.container.on( 'click', '.clear-button', function() {
                let _this = $( this )
                if( _this.hasClass( 'disabled' ) ) return
                self.container.siblings( '.page-header' ).find( '.search-form' ).submit()
            })
        }
    }

    /**
     * MARK: Web Stories
     * 
     * @since 1.0.0
     */
    const WebStories = {
        /**
         * Container
         * 
         * @since 1.0.0
         */
        get container() {
            if( ! this._container ) {
                this._container = $( '.bbe-web-stories' )
            }
            return this._container
        },
        /**
         * Active story id
         * 
         * @since 1.0.0
         */
        activeStoryId: null,
        /**
         * Ids of all stories
         * 
         * @since 1.0.0
         */
        allStoryIds: [],
        /**
         * Count total posts of each story
         * 
         * @since 1.0.0
         */
        activeStoryCount: null,
        /**
         * Stories wrapper
         * 
         * @since 1.0.0
         */
        get storiesWrap(){
            if( ! this._storiesWrap ) {
                this._storiesWrap = this.container.find( '.stories-wrap' )
            }
            return this._storiesWrap
        },
        /**
         * Stories wrapper
         * 
         * @since 1.0.0
         */
        get innerStories(){
            if( ! this._innerStories ) {
                this._innerStories = this.container.find( '.inner-stories-wrap .inner-stories' )
            }
            return this._innerStories
        },
        /**
         * Stories wrapper
         * 
         * @since 1.0.0
         */
        get actionButtons(){
            if( ! this._actionButtons ) {
                this._actionButtons = this.container.find( '.action-buttons' )
            }
            return this._actionButtons
        },
        /**
         * Is the web stories slider paused
         * 
         * @since 1.0.0
         */
        isPaused: false,
        /**
         * Detect outside click
         * 
         * @since 1.0.0
         */
        outsideClickEnabled: false,
        /**
         * Initialize
         * 
         * @since 1.0.0
         */
        init: function(){
            if( this.container.length ) {
                this.outsideClickEnabled = this.container.hasClass( 'outside-click--enabled' )
                this.countClick();
                this.storyClick();
                this.close();
                this.pause();
                this.scrollButtons();
                if( webStories.closeOnESC ) this.closePopupOnESCPress();
                $( 'body' ).css({
                    '--expandWidth-timer': `${ 3000 / 1000 }s`
                })
                let self = this
                this.container.find( '.story' ).each(function(){
                    let _this = $( this )
                    self.allStoryIds = [ ...self.allStoryIds, _this.data( 'id' ) ]
                })
            }
        },
        /**
         * Count click
         * 
         * @since 1.0.0
         */
        countClick: function(){
            this.container.on( 'click', '.story .story-count', function( event ) {
                event.stopPropagation()
            })
        },
        /**
         * Bind story click
         * 
         * @since 1.0.0
         */
        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.storiesWrap.addClass( 'retrieving-stories' )
                    self.ajaxCall();
                } else {
                    self.storiesWrap.slick( {
                        fade: true,
                        infinite: false,
                        prevArrow: self.container.find( '.story-arrows .prev-arrow' ),
                        nextArrow: self.container.find( '.story-arrows .next-arrow' ),
                        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();
            });
        },
        /**
         * Bind after change event
         * 
         * @since 1.0.0
         */
        afterChange: function(){
            let self = this
            self.storiesWrap.off( 'afterChange' ).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' ) )
            })
        },
        /**
         * Bind after last slide event
         * 
         * @since 1.0.0
         */
        afterLastSlide: function(){
            let self = this
            self.innerStories.find( `.inner-story-wrap[data-id="${ self.activeStoryId }"]` ).off( 'afterChange' ).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 ) {
                    self.advanceToNextStory();
                }
            })
        },
        /**
         * Bind ajax call
         * 
         * @since 1.0.0
         */
        ajaxCall: function(){
            let self = this
            NonceManager.getNonce().then( nonce => {
                $.ajax({
                    method: 'POST',
                    url: ajaxUrl,
                    data: {
                        action: 'web_stories_ajax_call',
                        _wpnonce: nonce,
                        storyIds: self.allStoryIds,
                        count: self.activeStoryCount
                    },
                    success: function( result ) {
                        let { success, data } = result
                        if( success ) {
                            self.storiesWrap.slick( {
                                arrows: true,
                                fade: true,
                                infinite: false,
                                prevArrow: self.container.find( '.story-arrows .prev-arrow' ),
                                nextArrow: self.container.find( '.story-arrows .next-arrow' ),
                                pauseOnFocus: false,
                                pauseOnHover: false
                            } )
                            self.innerStories.append( data.message )
                            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' )
                    }
                })
            })
        },
        /**
         * Bind close event
         * 
         * @since 1.0.0
         */
        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.pause' ).addClass( 'pause' )
                self.container.find( '.action-btn.pause i' ).removeClass( 'fa-play' ).addClass( 'fa-pause' )
            })
        },
        /**
         * Bind pause event
         * 
         * @since 1.0.0
         */
        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' )
            })
        },
        /**
         * Bind secondary slick slider
         * 
         * @since 1.0.0
         */
        initSecondarySlider: function( selector ) {
            $( selector ).slick({
                autoplay: webStories.autoplay,
                arrows: webStories.arrows,
                fade: webStories.fade,
                infinite: false,
                autoplaySpeed: 3000,
                speed: webStories.speed,
                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,
            })

             let slick = $( selector ).data( 'slick' )
            if( slick && slick.slideCount <= slick.options.slidesToShow ) {
                // only one "page" of slides exists — afterChange will never fire,
                // so manually schedule the advance to the next outer story
                this.advanceToNextStory();
            }
        },
        /**
         * Advance to next slide
         * 
         * @since 1.0.0
         */
        advanceToNextStory: function(){
            let self = this
            setTimeout(() => {
                self.storiesWrap.slick( 'slickNext' )
            }, 3000 - 600 )
        },
        /**
         * Add ambient
         * 
         * @since 1.0.0
         */
        addAmbient: function( imageTag ) {
            let storyImage = $( imageTag ).attr( 'src' );

            this.container.find( '.ambient-wrapper' ).css({
                'background-image': 'url('+ storyImage +')'
            })
        },
        /**
         * Close Popup on ESC Button Press
         * 
         * @since 1.0.0
         */
        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
         * 
         * @since 1.0.0
         */
        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`
                })
            })
        }
    }

    /**
     * Execute all on ready
     * MARK: Document Ready
     * 
     * @since 1.0.0
     */
    $( document ).ready( function() {
        SearchFieldLiveSearch.init()
        SearchIconLiveSearch.init()
        HandleOutsideClick.init()
        /**
         * Carousel Widget
         */
        if( $( 'body.search' ).length ) SearchFilter.init()

        /**
         * Web stories
         */
        WebStories.init();
    } )
})( jQuery )