/**
 * ----------------------------------------------------------------------------
 * GXJS Footer
 * @module:   GX
 * @version:  1.4
 * @modified: 04/13/2023 - Cnix
 * ----------------------------------------------------------------------------
 */

'use strict';

// Set the var for which skuid page is active
let gx_skuid_page;

if (typeof $('body').data('pagename') !== 'undefined') {
    // Append the pagename data attribute to the body tag
    gx_skuid_page = $('body').data('pagename');
}

let ncf;

if (!ncf) {
    ncf = window.ncf;
}

// Displays Affiliate office data in the "Contact us" dropdown
ncf.displayAffiliateData = function() {

    // Get and output the affiliateData
    let affiliateData = '';

    if (ncf && ncf.affiliateRow && ncf.affiliateRow.Id !== null) {
        affiliateData = ncf.affiliateRow;
    } else if (ncf && ncf.contactRow && ncf.contactRow.Primary_Fund__r && ncf.contactRow.Primary_Fund__r.Affiliate__r) {
        affiliateData = ncf.contactRow.Primary_Fund__r.Affiliate__r;
    }

    if (ncf && affiliateData) {
        $('.affiliate-phones').html(
            (affiliateData.Phone__c ? '<span><a href="tel:' + affiliateData.Phone__c + '">' + affiliateData.Phone__c + '</a> phone</span>'  : '') +
            (affiliateData.Phone_cf800__c ? '<span><a href="tel:' + affiliateData.Phone_cf800__c + '">' + affiliateData.Phone_cf800__c + '</a> toll-free</span>'  : '') +
            (affiliateData.Fax__c ? '<span>' + affiliateData.Fax__c + ' fax</span>'  : '')
        );

        $('.affiliate-email').attr('href', 'mailto:' + affiliateData.Email__c);
        $('.affiliate-email').text(affiliateData.Email__c);

        $('.affiliate-address').html(
            '<span>' + affiliateData.Street1__c +
            (affiliateData.Street2__c ? ', ' + affiliateData.Street2__c : '') + '</span>' +
            '<span>' +
            affiliateData.City__c + ', ' +
            affiliateData.State__c + ' ' +
            affiliateData.ZIP__c + '</span>'
        );

        const google_directions_url = 'https://maps.google.com/?q=' + affiliateData.Street1__c + ' ' + affiliateData.City__c + ' ' + affiliateData.State__c + ' ' + affiliateData.ZIP__c;

        $('.affiliate-google-directions').attr('href', google_directions_url).attr('target', '_blank');

        ncf.timerStart();

        $(document).on('click','.are-you-still-there .button--close-window', function() {
            $('.are-you-still-there').each(function() {
                $(this).closest('.ui-dialog').remove();
            });
            ncf.timerStart();
        });
    }
};

$(document).ready(function() {

    ncf.mobileProfileMenuSlider();

    // Run the invoked modals
    $(document).on('click', '.js-modal', function() {
        const modalData = $(this).data('modal');
        modalDialogFn(modalData);
    });

    // Close a targeted dialog
    $(document).on('click', '.js-hide-modal', function() {
        const modalDialog = $(this).parents('.ui-dialog-content');
        $(modalDialog).dialog('destroy');
    });

    // @todo .ui-widget-overlay could be removed in favor of using clickOutside: true in dialog settings when jQuery is upgraded
    $(document).on('click', '.ui-widget-overlay', function() {
        // Get all open dialogs
        const openDialogs = $('.ui-dialog.ui-widget:visible');

        if (ncf && ncf.userRow && ncf.userRow.Id !== null) {
            $('.are-you-still-there').each(function() {
                $(this).closest('.ui-dialog').remove();
            });

            ncf.timerStart();
        }

        // Close each dialog
        openDialogs.each(function() {
            const dialog = $(this);

            // Find the close button element within the dialog
            const closeButton = dialog.find('.ui-dialog-titlebar-close');

            // Trigger a click event on the close button element
            closeButton.click();
        });
    });

    // Get the device type
    let deviceType = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

    // Add a listener to change detect device type on resize
    window.addEventListener('resize', function(event) {
        deviceType = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    });

    /**
     * Quick grab to retrieve the with of the scrollbar and use it to set right
     * padding on body and prevent content shift
     */
    const windowWidth = window.innerWidth;
    const documentWidth = document.documentElement.clientWidth;

    // Init the mobile menu dialog window
    $('.mobile-nav__container').dialog({
        dialogClass: 'mobile-nav',
        resizable: false,
        modal: false,
        autoOpen: false,
        open: function() {
            // Set the icon active class
            $('.js-mobile-nav-icon').addClass('is-active');

            $(this).dialog(
                'option',
                'height',
                $(document).height()
            );

            // Set body styles to prevent window scroll
            $('html, body').css({
                'overflow': 'hidden',
                'position': 'relative',
            });
        },
        close: function() {
            // Remove the icon active class
            $('.js-mobile-nav-icon').removeClass('is-active');

            // Clear out the temp body styles
            $('html, body').css({
                'overflow': '',
                'position': '',
                'height': ''
            });
        }
    });

    // Mobile menu trigger
    $('.js-mobile-nav-icon').on('click', function() {
        if ($('.mobile-nav__container').dialog('isOpen')) {
            $('.mobile-nav__container').dialog('close');
            $('body').removeAttr('style');
        } else {
            $('.mobile-nav__container').dialog('open');
            // Add the right padding if this is not a scrollbar-less device
            document.body.style.paddingRight = !deviceType ? windowWidth - documentWidth + 'px' : '';
        }
    });

    $('.js-mobile-close-icon').on('click', function() {
        $('.mobile-nav__container').dialog('close');
        $('body').removeAttr('style');
    });

    // Handle closing the menu on outside click
    $(document).on('click touchstart', function(event) {
        if ($('.mobile-nav__container').dialog('isOpen') && !$(event.target).is('.mobile-nav__container, .mobile-nav__item, a') && !$(event.target).closest('.mobile-nav__container').length) {
            $('.mobile-nav__container').dialog('close');
        }
    });

    //Events
    $('.ncf-navigation__search-clear-icon').on('click', function(e){
        e.preventDefault();
        $('.ncf-navigation__search-input').val('');
        $('.ncf-navigation__search-clear-icon').css('visibility', 'hidden');
    });

    $('.ncf-navigation__search-input').on('input', function(){
        if($(this).val().length > 0){
            $('.ncf-navigation__search-clear-icon').css('visibility','visible');
        }
        else{
            $('.ncf-navigation__search-clear-icon').css('visibility','hidden');
        }
    });
});

if ($('.menu-container__settings').length) {
    // Settings menu vars
    const settingsLink = '.js-settings-link';
    const settingsLinkElement = document.querySelector(settingsLink);
    const settingsContainer = '.menu-container__settings';
    const settingsContainerElement = document.querySelector(settingsContainer);

    // Build click event listener for settings link
    settingsLinkElement.addEventListener('click', function(event) {
        if (settingsContainerElement.classList.contains('is-visible')) {
            settingsContainerElement.classList.remove('is-visible');
        } else {
            settingsContainerElement.classList.add('is-visible');
        }
    });

    document.addEventListener('click', function(event) {
        const settingsLinkClicked = event.target.closest(settingsContainer);
        const settingsContainerClicked = event.target.closest(settingsLink);

        if (!settingsLinkClicked && !settingsContainerClicked && settingsContainerElement.classList.contains('is-visible')) {
            settingsContainerElement.classList.remove('is-visible');
        }
    });

    // Add a listener for escape keypress to close the menu
    window.addEventListener('keydown', function(event) {
        if (event.key === 'Escape' && settingsContainerElement.classList.contains('is-visible')) {
            settingsContainerElement.classList.remove('is-visible');
        }
    });
}

if ($('.menu-container__contact').length) {
    let menu_container__contact = new Spry.Widget.Tooltip('menu-container__contact', '.ncf-quicknav__link--contact', {
        closeOnTooltipLeave: true,
        offsetX: '0px',
        offsetY: '44px',
        showDelay: 10000,
        hideDelay: 200
    });
}

if ($('#menu-container__search').length) {
    let ncfquicknavsearchwrapper = new Spry.Widget.ValidationTextField('menu-container__search', 'none', {
        hint: 'Search charities'
    });
}

$(document.body).one('pageload', function() {
    // Remove any inline style Skuid applies
    $('.page-panel__primary').removeAttr('style');
    $('.page-panel__secondary').removeAttr('style');

    $('.nx-tabset-header > div').removeAttr('style');
    $('.nx-tabset-header > div input').removeAttr('style');
    $('.nx-tabset-header > div label').removeAttr('style');
    $('.nx-tabset-header label').removeAttr('style');

    $('.ui-tabs-nav').removeAttr('style');
    $('.ui-tabs-panel').css({
        'width': 'auto',
        'padding': '0'
     });

    $('td').removeAttr('style');
});
