/**
 * Files to manage theme scripts.
 *
 * @package Blogbuster
 */

jQuery(document).ready(function($) {

    var headerSticky    = MT_JSObject.header_sticky,
        sidebarSticky   = MT_JSObject.sidebar_sticky,
        ajaxUrl         = MT_JSObject.ajaxUrl,
        _wpnonce        = MT_JSObject._wpnonce,
        KEYCODE_TAB     = 9;
        KEYCODE_ESC     = 27;
    
    /**
     * Header Search script
     */
    $('.header-search-wrapper .mt-search-icon').click(function() {
        $('.search-form-wrap').toggleClass('active-search');
        $('.search-form-wrap .search-field').focus();
        var element = document.querySelector('.header-search-wrapper');
        if (element) {
            $(document).on('keydown', function(e) {
                if (element.querySelectorAll('.search-form-wrap.active-search').length === 1) {
                    var focusable = element.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
                    var firstFocusable = focusable[0];
                    var lastFocusable = focusable[focusable.length - 1];
                   blogbuster_focus_trap(firstFocusable, lastFocusable, e);
                }
            })
        }
    });

    $('.header-search-wrapper .mt-form-close').click(function() {
        $('.search-form-wrap').removeClass('active-search');
    });

    var rtl = false;
    var dir = "left";
    if ($('body').hasClass("rtl")) {
        rtl = true;
        dir = "right";
    };

    /**
     * Preloader
     */
    if ($('#mt-preloader').length > 0) {
        setTimeout(function() {
            $('#mt-preloader').hide();
        }, 600);
    }

    /**
     * Scroll Top.
     */
        $(window).scroll(function() {
            if ($(this).scrollTop() > 1000) {
                $('#mt-scrollup').fadeIn('slow');
            } else {
                $('#mt-scrollup').fadeOut('slow');
            }
        });
        $('#mt-scrollup').click(function() {
            $("html, body").animate({
                scrollTop: 0
            }, 600);
            return false;
        });

	// site mode switcher
    function siteModeToggle(siteModeVal) {
        $.removeCookie('blogbuster-site-mode-cookie', {
            path: '/'
        });
        if (siteModeVal === 'light-mode') {
            updateVal = 'dark-mode';
        } else {
            updateVal = 'light-mode';
        }
        $("#mode-switcher").removeClass(siteModeVal);
        $("#mode-switcher").addClass(updateVal);
        $('body').removeClass(siteModeVal);
        $('body').addClass(updateVal);
        var exDate = new Date();
        exDate.setTime(exDate.getTime() + (3600 * 1000)); // expire in 1 hr
        $.cookie('blogbuster-site-mode-cookie', updateVal, {
            expires: exDate,
            path: '/'
        });
    }

    $("#mode-switcher").click(function(event) {
        event.preventDefault();
        var siteModeClass = $(this).attr('class');
        siteModeAttr = $(this).data('site-mode');

        if ($(this).hasClass(siteModeAttr)) {
            siteModeToggle(siteModeAttr);
        } else {
            siteModeToggle(siteModeClass);
        }
    });
    
    /**
     * Settings of the header sticky menu
     */
    var $window   = $(window);
    var $wpBar    = $('#wpadminbar');
    var $header   = $('#masthead .header-main-wrapper');
    var $menuIcon = $('#masthead .responsive-menu-icon-wrapper');

    // only run if headerSticky is true
    function initSticky() {
        if ('true' !== headerSticky) return;

        var width     = $window.width();
        var topOffset = $wpBar.length ? $wpBar.height() : 0;

        // Unstick everything first to avoid duplicates
        $header.unstick && $header.unstick();
        $menuIcon.unstick && $menuIcon.unstick();

        if (width > 979) {
            // Desktop: stick the main header
            $header.sticky({ topSpacing: topOffset });
        } else {
            // Mobile: only stick the menu icon if it’s visible/active
            if ($menuIcon.is(':visible')) {
                $menuIcon.sticky({ topSpacing: 0 });
            }
        }
    }

    $(function(){
        initSticky();
    });
    var resizeTimer;
    $window.on('resize', function(){
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(initSticky, 100);
    });
    $('.responsive-menu-icon-wrapper .mt-menu-toggle').on('click', function() {
        const $menuWrap = $(this).siblings('.primary-menu-wrap');
        $menuWrap.toggleClass('isActive').slideToggle('slow');

        const element = $menuWrap[0];
        if (element) {
            $(document).on('keydown.responsiveMenu', function(e) {
                if (element.classList.contains('isActive')) {
                    const focusable = element.querySelectorAll(
                        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
                    );
                    const firstFocusable = document.querySelector('.responsive-menu-icon-wrapper .mt-menu-toggle');
                    const lastFocusable = focusable[focusable.length - 1];
                    blogbuster_focus_trap(firstFocusable, lastFocusable, e);
                }
            });
        }
    });

    $('<a class="sub-toggle" href="javascript:void(0);"><i class="fa fa-angle-right"></i></a>')
        .insertAfter('#site-navigation .menu-item-has-children > a, #site-navigation .page_item_has_children > a');

    $('#site-navigation .sub-toggle').on('click', function() {
        const $parentLi = $(this).parent();
        $parentLi.children('ul.sub-menu, ul.children').first().slideToggle(400);
        $(this).children('i.fa-angle-right').toggleClass('fa-angle-down');
    });

    $(document).on('keydown', function(event) {
        if (event.keyCode === KEYCODE_ESC) {
            $('#site-navigation.isActive').removeClass('isActive').slideUp('slow');
            $('.search-form-wrap.active-search').removeClass('active-search');
        }
    });

    /**
     * focus trap
     * 
     * @returns void
     * @since 1.0.0
     */
    function blogbuster_focus_trap( firstFocusable, lastFocusable, e ) {
        if (e.key === 'Tab' || e.keyCode === KEYCODE_TAB) {
            if ( e.shiftKey ) /* shift + tab */ {
                if (document.activeElement === firstFocusable) {
                    lastFocusable.focus();
                    e.preventDefault();
                }
            } else /* tab */ {
                if ( document.activeElement === lastFocusable ) {
                    firstFocusable.focus();
                    e.preventDefault();
                }
            }
        }
    }

    /**
     * theia sticky sidebar
     */
    if ('true' === sidebarSticky) {
        $('#primary, #secondary').theiaStickySidebar({
            additionalMarginTop: 30
        });

        $('#primary, #left-secondary').theiaStickySidebar({
            additionalMarginTop: 30
        });

        $('.primary-content-wrapper, .secondary-content-wrapper').theiaStickySidebar({
            additionalMarginTop: 30
        });
    }

});