/* global rubik_news_l10n */
/**
 * Theme functions file.
 *
 * Contains handlers for navigation and widget area.
 */

(function( $ ) {
	var masthead, menuToggle, siteNavContain, siteNavigation;

	function initMainNavigation( container ) {

		// Add dropdown toggle that displays child menu items.
		var dropdownToggle = $( '<button />', { 'class': 'dropdown-toggle', 'aria-expanded': false })
			.append( rubik_news_l10n.icon )
			.append( $( '<span />', { 'class': 'screen-reader-text', text: rubik_news_l10n.expand }) );

		container.find( '.menu-item-has-children > a, .page_item_has_children > a' ).after( dropdownToggle );

		// Set the active submenu dropdown toggle button initial state.
		container.find( '.current-menu-ancestor > button' )
			.addClass( 'toggled-on' )
			.attr( 'aria-expanded', 'true' )
			.find( '.screen-reader-text' )
			.text( rubik_news_l10n.collapse );
		// Set the active submenu initial state.
		container.find( '.current-menu-ancestor > .sub-menu' ).addClass( 'toggled-on' );

		container.find( '.dropdown-toggle' ).click( function( e ) {
			var _this = $( this ),
				screenReaderSpan = _this.find( '.screen-reader-text' );

			e.preventDefault();
			_this.toggleClass( 'toggled-on' );
			_this.next( '.children, .sub-menu' ).toggleClass( 'toggled-on' );

			_this.attr( 'aria-expanded', _this.attr( 'aria-expanded' ) === 'false' ? 'true' : 'false' );

			screenReaderSpan.text( screenReaderSpan.text() === rubik_news_l10n.expand ? rubik_news_l10n.collapse : rubik_news_l10n.expand );
		});
	}

	initMainNavigation( $( '.main-navigation' ) );

	masthead       = $( '#masthead' );
	menuToggle     = masthead.find( '.menu-toggle' );
	siteNavContain = masthead.find( '.main-navigation' );
	siteNavigation = masthead.find( '.main-navigation > div > ul' );

	// Enable menuToggle.
	(function() {

		// Return early if menuToggle is missing.
		if ( ! menuToggle.length ) {
			return;
		}

		// Add an initial value for the attribute.
		menuToggle.attr( 'aria-expanded', 'false' );

		menuToggle.on( 'click.rubik_news', function() {
			siteNavContain.toggleClass( 'toggled-on' );

			$( this ).attr( 'aria-expanded', siteNavContain.hasClass( 'toggled-on' ) );
		});
	})();

	// Fix sub-menus for touch devices and better focus for hidden submenu items for accessibility.
	(function() {
		if ( ! siteNavigation.length || ! siteNavigation.children().length ) {
			return;
		}

		// Toggle `focus` class to allow submenu access on tablets.
		function toggleFocusClassTouchScreen() {
			if ( 'none' === $( '.menu-toggle' ).css( 'display' ) ) {

				$( document.body ).on( 'touchstart.rubik_news', function( e ) {
					if ( ! $( e.target ).closest( '.main-navigation li' ).length ) {
						$( '.main-navigation li' ).removeClass( 'focus' );
					}
				});

				siteNavigation.find( '.menu-item-has-children > a, .page_item_has_children > a' )
					.on( 'touchstart.rubik_news', function( e ) {
						var el = $( this ).parent( 'li' );

						if ( ! el.hasClass( 'focus' ) ) {
							e.preventDefault();
							el.toggleClass( 'focus' );
							el.siblings( '.focus' ).removeClass( 'focus' );
						}
					});

			} else {
				siteNavigation.find( '.menu-item-has-children > a, .page_item_has_children > a' ).unbind( 'touchstart.rubik_news' );
			}
		}

		if ( 'ontouchstart' in window ) {
			$( window ).on( 'resize.rubik_news', toggleFocusClassTouchScreen );
			toggleFocusClassTouchScreen();
		}

		siteNavigation.find( 'a' ).on( 'focus.rubik_news blur.rubik_news', function() {
			$( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' );
		});
	})();

})( jQuery );

document.addEventListener('DOMContentLoaded', function () {
	const headerSearches = document.querySelectorAll('.header-search');

	headerSearches.forEach(function (headerSearch) {
		const toggle = headerSearch.querySelector('.header-search-toggle');
		const searchForm = headerSearch.querySelector('.header-search-form');
		const searchField = searchForm
			? searchForm.querySelector('.search-field')
			: null;

		if (!toggle || !searchForm || !searchField) {
			return;
		}

		const screenReaderText = toggle.querySelector(
			'.screen-reader-text'
		);

		function getFocusableElements() {
			return Array.from(
				headerSearch.querySelectorAll(
					'button:not([disabled]), ' +
					'input:not([disabled]), ' +
					'a[href], ' +
					'[tabindex]:not([tabindex="-1"])'
				)
			).filter(function (element) {
				return !element.closest('[hidden]');
			});
		}

		function openSearch() {
			searchForm.hidden = false;
			toggle.setAttribute('aria-expanded', 'true');
			headerSearch.classList.add('search-open');

			if (screenReaderText) {
				screenReaderText.textContent = 'Close search form';
			}

			window.requestAnimationFrame(function () {
				searchField.focus();
			});
		}

		function closeSearch() {
			searchForm.hidden = true;
			toggle.setAttribute('aria-expanded', 'false');
			headerSearch.classList.remove('search-open');

			if (screenReaderText) {
				screenReaderText.textContent = 'Open search form';
			}

			toggle.focus();
		}

		toggle.addEventListener('click', function () {
			const isOpen =
				toggle.getAttribute('aria-expanded') === 'true';

			if (isOpen) {
				closeSearch();
			} else {
				openSearch();
			}
		});

		headerSearch.addEventListener('keydown', function (event) {
			const isOpen =
				toggle.getAttribute('aria-expanded') === 'true';

			if (!isOpen) {
				return;
			}

			// Close the search form with Escape.
			if (event.key === 'Escape') {
				event.preventDefault();
				closeSearch();
				return;
			}

			// Keep keyboard focus inside the open search area.
			if (event.key !== 'Tab') {
				return;
			}

			const focusableElements = getFocusableElements();

			if (!focusableElements.length) {
				return;
			}

			const firstElement = focusableElements[0];
			const lastElement =
				focusableElements[focusableElements.length - 1];

			if (
				event.shiftKey &&
				document.activeElement === firstElement
			) {
				event.preventDefault();
				lastElement.focus();
			} else if (
				!event.shiftKey &&
				document.activeElement === lastElement
			) {
				event.preventDefault();
				firstElement.focus();
			}
		});
	});
});
