/**
 * File libra.js.
 *
 * Handles all JavaScript for the theme
 */
( function( $ ) {
	var body = $( 'body' );
	var panelToggle = $( '.panel-toggle' );
	var panel = $( '.panel' );
	var toggleText = panelToggle.find( '.screen-reader-text' );
	var menu = $( '.site-navigation ul' );
	var links = menu.find( 'a' );
	var subMenus = menu.find( 'ul' );
	
	function initMainNavigation( container ) {
		var dropdownToggle = $( '<button />', {
			'class': 'dropdown-toggle',
			'aria-expanded': false
		} ).append( $( '<span />', {
			'class': 'screen-reader-text',
			text: libraChildMenuToggle.expand
		} ) );

		container.find( '.menu-item-has-children > a' ).after( dropdownToggle );
		container.find( '.page_item_has_children > a' ).after( dropdownToggle );
		
		container.find( '.current-menu-ancestor > button' ).addClass( 'toggled-on' );
		container.find( '.current-menu-ancestor > .sub-menu' ).addClass( 'toggled-on' );

		container.find( '.menu-item-has-children' ).attr( 'aria-haspopup', 'true' );

		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' );

			// jscs:disable
			_this.attr( 'aria-expanded', _this.attr( 'aria-expanded' ) === 'false' ? 'true' : 'false' );
			// jscs:enable
			screenReaderSpan.text( screenReaderSpan.text() === libraChildMenuToggle.expand ? libraChildMenuToggle.collapse : libraChildMenuToggle.expand );
		} );
	}
	initMainNavigation( $( '.site-navigation' ) );
	
	panelToggle.on( 'click', function( e ) {
		var $this = $( this );
		e.preventDefault();
		
		panel.toggleClass( 'expanded' ).resize();
		body.toggleClass( 'panel-open' );

		$this.toggleClass( 'toggle-on' );
		$this.attr( 'aria-expanded', $( this ).attr( 'aria-expanded' ) == 'false' ? 'true' : 'false');

		if ( panel.hasClass( 'expanded' ) ) {
			toggleText.text( 'Hide panel' );
		} else {
			toggleText.text( 'Show panel' );
		}
	} );
	
	function toggleFocus() {
		$( this ).parentsUntil( menu, 'li' ).toggleClass( 'focus' );
	}
	
	subMenus.each( function() {
		$( this ).parent().attr( 'aria-haspopup', 'true' );
	} );
	
	links.each( function() {
		$( this ).on( 'focus blur', toggleFocus );
	} );
} )( jQuery );
