/**
 * Handles theme general events
 * 
 * @package News Event
 * @since 1.0.0
 */
jQuery(document).ready(function($) {
    "use strict"
    var ajaxUrl = newsEventObject.ajaxUrl, _wpnonce = newsEventObject._wpnonce, sttOption = newsEventObject.stt;

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

    var nrtl = false
    var ndir = "left"
    if ($('body').hasClass("rtl")) {
        nrtl = true;
        ndir = "right";
    };
    
    // theme trigger modal close
    function newsEventCloseModal( 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 tcM = tc.find( ".ticker-item-wrap" ).marquee({
            duration: 15000,
            gap: 0,
            delayBeforeStart: 0,
            direction: ndir,
            duplicated: true,
            startVisible: true,
            pauseOnHover: true,
        });
        tc.on( "click", ".news-event-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, .search_close_btn", 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' )
    });

     // search form 
    $( "#masthead" ).on( "click", ".search-trigger", function() {
        $(this).next().slideDown();
        $( '#masthead .search-wrap input[type="search"]' ).focus()
        $(this).addClass('slideshow');
        $('body').addClass('bodynoscroll');
    });

    $( "#masthead" ).on( "click", ".search-trigger.slideshow", function() {
        $(this).next().slideUp();
        $(this).removeClass('slideshow');
        $('body').removeClass('bodynoscroll');
    });

    $( ".search-popup--style-three #masthead" ).on( "click", ".search-trigger", function() {
        $(this).parents( '#masthead' ).find( '.search-form-wrap' ).slideDown();
        $(this).parents( '#masthead' ).find( '.search-form-wrap input[type="search"]' ).focus()
        $(this).addClass('slideshow');
        $('body').addClass('bodynoscroll');
    });

    $( ".search-popup--style-three #masthead" ).on( "click", ".search_close_btn", function() {
        $(this).parents( '.main-header' ).find( '.search-form-wrap' ).slideUp();
        $(this).siblings().removeClass('slideshow');
        $('body').removeClass('bodynoscroll');
    });


    $( ".search-popup--style-two #masthead" ).on( "click", ".search-trigger", function() {
        $(this).next().fadeIn();
        $(this).addClass('slideshow');
        $('body').addClass('bodynoscroll');
    });

    $( "body.search-popup--style-one #masthead, body.search-popup--style-two #masthead" ).on( "click", ".search_close_btn", function() {
        $(this).prev().fadeOut();
        $(this).prev().prev().removeClass('slideshow');
        $('body').removeClass('bodynoscroll');
    });

    newsEventCloseModal( $( ".search-wrap, .search-form-wrap" ), function () {
        $( ".search-wrap .search-trigger" ).removeClass( "slideshow" );
        $( ".search-form-wrap" ).slideUp();
        $('body').removeClass('bodynoscroll');
    }); // trigger search close


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

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

    // top header ticker news slider events
    var thtn = $( ".top-ticker-news" );
    if( thtn.length ) {
        var thtnitems = thtn.find( ".ticker-item-wrap" )
        thtnitems.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>`,
        });
    }

    // 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 = $( ".news-event-section .news-carousel .news-carousel-post-wrap" );
    if( nc.length ) {
        nc.each(function() {
            var _this = $(this)
            var multiColumnSection = _this.parents('.news-event-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
     $( ".news-event-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")
          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: 'news_event_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 = $( ".news-event-widget-popular-posts" )
    ppWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_news_event_popular_posts_widget" ).attr( "id" ), parentWidgetContainer = $( "#" + parentWidgetContainerId )
        var ppWidget = parentWidgetContainer.find( ".popular-posts-wrap" );
        if( ppWidget.length > 0 ) {
            var ppWidgetAuto = ppWidget.data( "auto" )
            var ppWidgetArrows = ppWidget.data( "arrows" )
            var ppWidgetLoop = ppWidget.data( "loop" )
            var ppWidgetVertical = ppWidget.data( "vertical" )
            if( ppWidgetVertical == 'vertical' ) {
                ppWidget.slick({
                    vertical: true,
                    slidesToShow: 4,
                    dots: false,
                    infinite: ppWidgetLoop,
                    arrows: ppWidgetArrows,
                    autoplay: ppWidgetAuto,
                    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: ppWidgetLoop,
                    rtl: nrtl,
                    arrows: ppWidgetArrows,
                    autoplay: ppWidgetAuto,
                    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 = $( ".news-event-widget-carousel-posts" )
    cpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_news_event_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 = $( ".news-event-tabbed-widget-tabs-wrap" )
    tabpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_news_event_tabbed_posts_widget" ).attr( "id" ), parentWidgetContainer
        if( typeof parentWidgetContainerId != 'undefined' ) {
            parentWidgetContainer = $( "#" + parentWidgetContainerId )
            var tabpWidget = parentWidgetContainer.find( ".news-event-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 = $( ".news-event-news-filter-tabbed-widget-tabs-wrap" )
    nftabpWidgets.each(function() {
        var _this = $(this), parentWidgetContainerId = _this.parents( ".widget.widget_news_event_news_filter_tabbed_widget" ).attr( "id" ), parentWidgetContainer
        if( typeof parentWidgetContainerId != 'undefined' ) {
            parentWidgetContainer = $( "#" + parentWidgetContainerId )
            var nftabpWidget = parentWidgetContainer.find( ".news-event-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" );
            })
        }
    })

    // check for dark mode drafts
    if( localStorage.getItem( "themeMode" ) != null ) {
        if( localStorage.getItem("themeMode") == "dark" ) {
            $('body').addClass( 'news_event_dark_mode' ).removeClass('news_event_main_body')
            $('body .blaze-switcher-button').addClass( 'active' )
        } else {
            $('body').addClass( 'news_event_main_body' ).removeClass('news_event_dark_mode')
            $('body .blaze-switcher-button').removeClass( 'active' )
        }
    }
    
    // header - theme mode
    var themeModeContainer = $('.blaze-switcher-button')
    if( themeModeContainer.length > 0 ) {
        themeModeContainer.on( 'click', function(){
            var _this = $(this), bodyElement = _this.parents('body')
            if( bodyElement.hasClass('news_event_dark_mode') ) {
                localStorage.setItem( 'themeMode', 'light' )
                bodyElement.removeClass('news_event_dark_mode').addClass('news_event_main_body')
                $('body .blaze-switcher-button').removeClass( 'active' )
            } else {
                localStorage.setItem( 'themeMode', 'dark' )
                bodyElement.removeClass('news_event_main_body').addClass('news_event_dark_mode')
                $('body .blaze-switcher-button').addClass( 'active' )
            }
        })
    }

    // back to top script
    if( sttOption && $( "#news-event-scroll-to-top" ).length ) {
        var scrollContainer = $( "#news-event-scroll-to-top" );
        $(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");
        });
    }

    // 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_news_event_ads_slider_widget .news-event-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', '.news-event-burger', function(){
                var _this = $(this)
                _this.siblings().toggleClass('isactive')
            })
        })
    }

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

    // social share
    var socialShareContainer = $( '.news-event-social-share' )
    if( socialShareContainer.length > 0 ) {
        // for print
        var printButton = socialShareContainer.find( '.print' )
        printButton.each(function(){
            $(this).on( 'click', function(){ 
                $(this).find( 'a' ).removeAttr( 'href' )
                window.print()
            })
        })
        // for copy link
        var copyLinkButton = socialShareContainer.find( '.copy_link' )
        copyLinkButton.each(function(){
            $(this).on( 'click', function( event ) { 
                event.preventDefault()
                var copyLinkButtonAnchor = $(this).find( 'a' )
                var linkToCopy = copyLinkButtonAnchor.attr( 'href' )
                navigator.clipboard.writeText( linkToCopy )
            })
        })

        // share icon
        if( socialShareContainer.hasClass( 'show-on-click' ) ) {
            socialShareContainer.on('click', '.share-icon', function(){
                $(this).toggleClass('active')
            })
        }
    }

     // cursor animation
     var cursorContainer = $('.news-event-cursor')
     if( cursorContainer.length > 0 ) {
         $(document).on( 'mousemove', function( event ){
            cursorContainer.css({
                'top': 'calc('+ event.pageY +'px - 15px)',
                'left': 'calc('+ event.pageX +'px - 15px)'
            })
         })
         var selector = 'a, button, input[type="submit"], #news-event-scroll-to-top .icon-text, #news-event-scroll-to-top .icon-holder, .pagination .ajax-load-more, .news-event-widget-loader .load-more, .blaze-switcher-button, .news-event-canvas-menu .canvas-menu-icon'
         $( selector ).on( 'mouseover', function(){
             $( cursorContainer ).addClass( 'isActive' )
         })
         $( selector ).on( 'mouseout', function(){
             $( cursorContainer ).removeClass( 'isActive' )
         })
     }
})