// Run ECMAScript in strict mode.
'use strict';

jQuery( () => {

	// Check if the post-type-hdsnav is on the page.
	if ( ! jQuery( 'body' ).hasClass( 'post-type-hdsnav' ) ) {

		// If the secondary navigation "usa-accordion__button" is clicked, change "aria-expanded" to
		// true and remove "hidden" from the "usa-nav__submenu" item directly beneath it.
		jQuery(document).on( 'click', '.hds-secondary-navigation .usa-accordion__button', function() {

			// Before we do this, we need to close any other open submenus.
			// Any submenu that is not this one, and is open, should be closed.
			jQuery( '.hds-secondary-navigation .usa-accordion__button' ).not(this).attr( 'aria-expanded', 'false' );
			jQuery( '.hds-secondary-navigation .usa-accordion__button' ).not(this).next().attr( 'hidden', 'hidden' );

			// Now we can open the submenu that was clicked.
			// Toggle this in case the menu is already open.
			jQuery( this ).attr( 'aria-expanded', function(index, attr) {
				return attr === 'true' ? 'false' : 'true';
			});

			jQuery( this ).next( '.usa-nav__submenu' ).attr( 'hidden', function(index, attr) {
				return attr === 'hidden' ? null : 'hidden';
			});
		});

		// Let's make sure the .hds-secondary-navigation-menu-items is hidden but set to flex.
		jQuery( '.hds-secondary-navigation-menu-items' ).attr( 'hidden', 'hidden' );

		// If the user clicks on the mobile secondary nav trigger, let's open the mobile nav.
		jQuery(document).on( 'click', '.hds-secondary-nav-mobile-button', function() {

			// Add an "is-active" class to both.
			jQuery( this ).toggleClass( 'hds-active' );
			jQuery( '.hds-secondary-navigation-menu-items' ).toggleClass( 'hds-active' );

			// Slide toggle the secondary nav track.
			jQuery( '.hds-secondary-navigation-menu-items' ).slideToggle(300);

			// Toggle the "hidden" attribute on the "hds-secondary-nav-mobile" class.
			jQuery( '.hds-secondary-navigation-menu-items' ).attr( 'hidden', function(index, attr) {
				return attr === 'hidden' ? null : 'hidden';
			});

			// Now, toggle the "hds-secondary-nav-mobile-button" class to aria-expanded.
			jQuery( '.hds-secondary-nav-mobile-button' ).attr( 'aria-expanded', function(index, attr) {
				return attr === 'true' ? 'false' : 'true';
			}
			);
		});
	}
});
;
jQuery( function(jQuery) {
    jQuery( document ).ready( function() {
        bindAudioPlayers();
    });
});

function bindAudioPlayers(){

    //Bind to body:not(.wp-admin) .hds-audio-player-wrap so that all frontend audio players are bound.
    //Bind to .server-side-render .hds-audio-player-wrap so that the server side render audio player is bound for the featured podcast block.
    jQuery("body:not(.wp-admin) .hds-audio-player-wrap, .server-side-render .hds-audio-player-wrap ").each(function() {
        var audioWrapper = jQuery(this);
        var audioPlayer = audioWrapper.find('.audioPlayer')[0];

        //Remove any old handlers
        audioWrapper.off('click', '.hds-audio-player__playpause');
        audioWrapper.off('click', '.hds-audio-player__mute');
        audioWrapper.off('keydown', '.hds-audio-player__mute');


        //remove any event listeners
        audioPlayer.removeEventListener('play', toggleIcons);
        audioPlayer.removeEventListener('pause', toggleIcons);
        audioPlayer.removeEventListener('volumechange', toggleIcons);
        

        function toggleIcons() {
            audioWrapper.find('.muteIcon').toggle(audioPlayer.muted);
            audioWrapper.find('.volumeIcon').toggle(!audioPlayer.muted);
        }

        audioWrapper.on('click', '.hds-audio-player__playpause', function() {
            jQuery(this).find('.playPauseIcon, .pauseIcon').toggle();
            audioPlayer.paused ? audioPlayer.play() : audioPlayer.pause();
        });

        audioWrapper.on('click', '.hds-audio-player__mute', function() {
            audioPlayer.muted = !audioPlayer.muted;
            audioPlayer.volume = audioPlayer.muted ? 0 : .3;
            audioWrapper.find('.hds-audio-player__volume').val(audioPlayer.volume);
            toggleIcons();
        });

        audioWrapper.on('keydown', '.hds-audio-player__mute', function( event ) {
            let input = jQuery(this).parent().find('.hds-audio-player__volume-wrapper input');
            let volume = parseFloat(input.val());
            
            var flag = false;
            switch (event.key) {
                case 'ArrowLeft':
                    if (volume > 0) {
                        if ((volume - 0.1) < 0) {
                            volume = 0;
                            jQuery(this).attr("aria-valuetext", "0% volume");
                        } else {
                            volume = (volume - 0.1).toFixed(2);
                            jQuery(this).attr("aria-valuetext", `${~~(volume * 100)}% volume`);
                        }
                    }
                    flag = true;
                    break;
                case 'ArrowRight':
                    if (volume < 1) {
                        if ((volume + 0.1) > 1) {
                            volume = 1;
                            jQuery(this).attr("aria-valuetext", `100% volume`);
                        } else {
                            volume = (volume + 0.1).toFixed(2);
                            jQuery(this).attr("aria-valuetext", `${~~(volume * 100)}% volume`);
                        }
                    }
                    flag = true;
                    break;
                case 'ArrowDown':
                    if (volume > 0) {
                        if ((volume - 0.1) < 0) {
                            volume = 0;
                            jQuery(this).attr("aria-valuetext", "0% volume");
                        } else {
                            volume = (volume - 0.1).toFixed(2);
                            jQuery(this).attr("aria-valuetext", `${~~(volume * 100)}% volume`);
                        }
                    }
                    flag = true;
                    break;
                case 'ArrowUp':
                    if (volume < 1) {
                        if ((volume + 0.1) > 1) {
                            volume = 1;
                            jQuery(this).attr("aria-valuetext", `100% volume`);
                        } else {
                            volume = (volume + 0.1).toFixed(2);
                            jQuery(this).attr("aria-valuetext", `${~~(volume * 100)}% volume`);
                        }
                    }
                    flag = true;
                    break;
                default:
                    break;
            }
            input.val(volume).trigger('input');
            audioPlayer.muted = !(audioPlayer.volume > 0);

            if (flag) {
                event.stopPropagation();
                event.preventDefault();
            }
        });

        audioWrapper.on('input', '.hds-audio-player__volume', function() {
            audioPlayer.volume = this.value;
            audioPlayer.muted = !(audioPlayer.volume > 0);
            toggleIcons();
        });

        audioWrapper.on('input', '.hds-audio-player__scrubber', function() {
            audioPlayer.currentTime = audioPlayer.duration * (this.value / 100);
        });

        jQuery(audioPlayer).on('timeupdate', function() {
            const scrubberSlider = audioWrapper.find('.hds-audio-player__scrubber');
            const currStep = ((audioPlayer.currentTime / audioPlayer.duration) * 100).toFixed(0);
            scrubberSlider.val(currStep);
            scrubberSlider.attr("aria-valuenow", currStep);
            let currentMinutes = ~~(audioPlayer.currentTime / 60);
            let currentSeconds = (~~(audioPlayer.currentTime % 60)).toString().padStart(2, '0');
            let totalMinutes = ~~(audioPlayer.duration / 60);
            let totalSeconds = (~~(audioPlayer.duration % 60)).toString().padStart(2, '0');

            //ensure that none are NAN
            if (isNaN(currentMinutes)) currentMinutes = "00";
            if (isNaN(currentSeconds)) currentSeconds = "00";
            if (isNaN(totalMinutes)) totalMinutes = "00";
            if (isNaN(totalSeconds)) totalSeconds = "00";

            //if we are completed, stop the audio
            if (audioPlayer.currentTime === audioPlayer.duration) {
                audioPlayer.pause();
                audioWrapper.find('.playPauseIcon, .pauseIcon').toggle();
            }

            //Update the time
            audioWrapper.find('.hds-audio-time').text(`${currentMinutes}:${currentSeconds} / ${totalMinutes}:${totalSeconds}`);
            scrubberSlider.attr("aria-valuetext", `${currentMinutes} Minutes ${currentSeconds} Seconds of ${totalMinutes} Minutes ${totalSeconds} Seconds`);
        }).trigger('timeupdate');

        toggleIcons();
    });
}

//Export the bindAudioPlayers function to the window so we can call it from the editor
window.bindAudioPlayers = bindAudioPlayers;;
'use strict';

jQuery( function() {
    // Get all the content-lists paginations a tags on the page.
    const contentListsPaginations = jQuery( '.hds-pagination--content-lists' );
    let paginationLinks = contentListsPaginations.find( 'a' );

    // Add click handlers to each of the a tags.
    addClickhandlers( paginationLinks );


    /**
     * Deletes the children of contentList and fadesIn
     * data.html in it's place.Also updates data-current-page to the
     * pageClicked.
     * 
     * @param data: data.html is formatted string of data to insert into the dom
     * @param contentList: Dom element that children will be erased and
     * 'data' will be inserted into as new children.
     * @param pageClicked: int value of the pagination page clicked on.
     *  
     */ 
    function updateBlockData( data, contentList, pageClicked ) {
        // Get all the children items and remove them from the dom.
        const children = jQuery( contentList ).children()
        jQuery( contentList ).children().remove();
        
        // Add the data from the api request.
        jQuery( contentList ).append( data.html ).hide().fadeIn(200); // phpcs:ignore WordPressVIPMinimum.JS.HTMLExecutingFunctions

        // Update the current-page data attribute in the content lists block.
        jQuery( contentList ).data( 'current-page', pageClicked );
        jQuery( contentList ).attr( 'data-current-page', pageClicked );
    }


    /**
     * Replaces the DOM content of parentNav in the DOM with new navigation.
     * And recreates the pagination on click handlers on it.
     * 
     * @param data: data.pagination is formatted string of data to insert into the dom
     * @param parentNav: Dom element that holds the pagination items.
     *  
     */
    function updatePagination( data, parentNav ) {    
        const rent = jQuery( parentNav ).parent();
        jQuery( parentNav ).replaceWith( data.pagination ); // phpcs:ignore WordPressVIPMinimum.JS.HTMLExecutingFunctions
        parentNav = rent.find( 'nav' );

        // Grab the Nav that just changed and add update click handlers.
        const thisPagination = jQuery( parentNav );
        const newPagination = jQuery( thisPagination ).find( 'a' );
        // Add click handlers to the new generated pagination links.
        addClickhandlers( newPagination );
    }


    /**
     *
     * Adds a click handler on all paginationLinks that grabs data from 
     * restEndpoint.endpoint and adds it to the dom. 
     * 
     * @param paginationLinks: list of dom items to add a click handler to
     */
    function addClickhandlers( paginationLinks ) {

        paginationLinks.each(function() {
            // if a function exists delete it.
            jQuery( this ).off("click");

            // add onclick handler.
            jQuery( this ).on( "click", function(e) {
                // prevent any default actions.
                e.preventDefault();
                e.stopPropagation();

                // Get nav parent and hds item sibling.
                const parentNav = jQuery( this ).parent().closest( 'nav' );
                const contentList = jQuery( parentNav ).prev( '.hds-content-items' );
                
                // Get data attributes.
                const postType = contentList.data( 'post-type' );
                const postId = contentList.data( 'post-id' );
                const maxPages = contentList.data( 'max-num-pages' );
                const perPage = contentList.data( 'per-page' );
                const categories = contentList.data( 'categories' );
                const newsTags = contentList.data( 'news-tags' );
                const layout = contentList.data( 'layout' );
                const showThumbnails = contentList.data( 'show-thumbnails' );
                const showReadTime = contentList.data( 'show-readtime' );
                const showExcerpts = contentList.data( 'show-excerpts' );
                const showContentTypeTags = contentList.data( 'show-content-type-tags' );
                
                // Get page number that is clicked.
                const pageClicked = jQuery( this ).data( 'page-number' );
    
                // Create json for api request.
                const _json = {
                    postType,
                    postId,
                    maxPages,
                    perPage,
                    categories,
                    newsTags,
                    layout,
                    showThumbnails,
                    showReadTime,
                    showExcerpts,
                    showContentTypeTags,
                    pageClicked
                }
                
                // Send api request.
                jQuery.get(
                    restEndpoint.endpoint,
                    _json,
                    function( data ){ 
                        updateBlockData( data, contentList, pageClicked );
                        updatePagination( data, parentNav );
                    },
                    'json' 
                )         
            });
        });
    }
});
;