1/**
2 * navigation.js
3 *
4 * Handles toggling the navigation menu for small screens and enables tab
5 * support for dropdown menus.
6 */
7( function() {
8	"use strict";
9	var container, button, menu, links, subMenus;
10
11	container = document.getElementById( 'site-navigation' );
12	if ( ! container ) {
13		return;
14	}
15
16	button = container.getElementsByTagName( 'button' )[0];
17	if ( 'undefined' === typeof button ) {
18		return;
19	}
20
21	menu = container.getElementsByTagName( 'ul' )[0];
22
23	if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
24		menu.className += ' nav-menu';
25	}
26
27	function setARIA() {
28		if ( 783 > window.innerWidth ) {
29			button.setAttribute( 'aria-controls', 'primary-menu' );
30			button.setAttribute( 'aria-expanded', 'false' );
31			menu.setAttribute( 'aria-expanded', 'false' );
32		} else {
33			button.removeAttribute( 'aria-controls' );
34			button.removeAttribute( 'aria-expanded' );
35			menu.removeAttribute( 'aria-expanded' );
36		}
37	}
38
39	button.onclick = function() {
40		if ( -1 !== container.className.indexOf( 'toggled' ) ) {
41			container.className = container.className.replace( ' toggled', '' );
42			button.setAttribute( 'aria-expanded', 'false' );
43			menu.setAttribute( 'aria-expanded', 'false' );
44		} else {
45			container.className += ' toggled';
46			button.setAttribute( 'aria-expanded', 'true' );
47			menu.setAttribute( 'aria-expanded', 'true' );
48		}
49	};
50
51	// Get all the link elements within the menu.
52	links    = menu.getElementsByTagName( 'a' );
53	subMenus = menu.getElementsByTagName( 'ul' );
54
55	// Set ARIA attributes properly.
56	window.addEventListener( 'load', setARIA, false );
57	window.addEventListener( 'resize', setARIA, true );
58
59	// Set menu items with submenus to aria-haspopup="true".
60	for ( var i = 0, len = subMenus.length; i < len; i++ ) {
61		subMenus[i].parentNode.setAttribute( 'aria-haspopup', 'true' );
62	}
63
64	// Each time a menu link is focused or blurred, toggle focus.
65	for ( i = 0, len = links.length; i < len; i++ ) {
66		links[i].addEventListener( 'focus', toggleFocus, true );
67		links[i].addEventListener( 'blur', toggleFocus, true );
68	}
69
70	/**
71	 * Sets or removes .focus class on an element.
72	 */
73	function toggleFocus() {
74		var self = this;
75
76		// Move up through the ancestors of the current link until we hit .nav-menu.
77		while ( -1 === self.className.indexOf( 'nav-menu' ) ) {
78
79			// On li elements toggle the class .focus.
80			if ( 'li' === self.tagName.toLowerCase() ) {
81				if ( -1 !== self.className.indexOf( 'focus' ) ) {
82					self.className = self.className.replace( ' focus', '' );
83				} else {
84					self.className += ' focus';
85				}
86			}
87
88			self = self.parentElement;
89		}
90	}
91} )();
92