/*****
Top section: Default suckerfish JS
Bottom section: Modifications to make the main menu more accessible to keyboard users
CSS: Modified to add :focus equivalent to every :hover
******/
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

/* Mootools section: Only execute if Mootools is present */
if(typeof $ != 'undefined') 
	{ 
	var AddKeyboardNav = function() {
		$$('li.main > a').each(function(mainNav)
			{
			var navParent = mainNav.getParent(); 

			/* Add sfhover class to the submenu that currently has focus */
			var showSubmenu = function() { this.addClass('sfhover'); }.bind(navParent);
			/* Remove sfhover class when it loses focus */
			var hideSubmenu = function() { this.removeClass('sfhover'); }.bind(navParent); 

			/* Use the left/right keys to jump to the next submenu */
			var nextSubmenu = function(e) { 
				var moveTo;
				if(e.key == 'right')
					{
					moveTo = this.getNext();
					}
				if(e.key == 'left')
					{
					moveTo = this.getPrevious();
					}

				if(moveTo != null)
					{
					moveTo.getChildren()[0].focus();
					}

				}.bind(navParent); 

			/* Use the down key to enter the submenu from the main menu */
			var enterMenu = function(e) {
				var moveTo;
				if(e.key == 'down')
					{
					moveTo = this.getElements('li a')[0];
					}

				if(moveTo != null)
					{
					e.stop();
					moveTo.focus();
					}
				}.bind(navParent);

			/* Use the up/down keys within the submenu to move around it */
			var nextSubitem = function(e) { 
				var moveTo;
				if(e.key == 'down')
					{
					e.stop();
					moveTo = this.getNext();
					}
				if(e.key == 'up')
					{
					e.stop();
					moveTo = this.getPrevious();
					}

				if(moveTo != null)
					{
					moveTo.getChildren()[0].focus();
					}

				}; 

			/* Bind the relevent events to their functions 
			   Note the use of keypress instead of keyup or keydown */
			mainNav.addEvent('focus', showSubmenu);
			mainNav.addEvent('blur', hideSubmenu);
			mainNav.addEvent('keypress', nextSubmenu);
			mainNav.addEvent('keypress', enterMenu);

			navParent.getElements('ul a').each(function(subNav)
				{
				/* ... and do the same in the submenu */
				var subParent = subNav.getParent(); 

				subNav.addEvent('focus', showSubmenu);
				subNav.addEvent('blur', hideSubmenu);
				subNav.addEvent('keypress', nextSubmenu);
				subNav.addEvent('keypress', nextSubitem.bind(subParent));
				});
	
			});

	
		};

	window.addEvent('domready', AddKeyboardNav);
	}
 
if (window.attachEvent) window.attachEvent("onload", sfHover);

