$(document).ready( function(){
		$( ".nav", "#head" ).mouseover( navMouseOver ).mouseout( navMouseOut );
		$( ".submenu", "#head" ).mouseover( subMouseOver ).mouseout( subMouseOut );
	}
)

function getContainer( evtTarget, match )
{
	var $target = $( evtTarget );
	var $container = ( $target.is( match ) )? $target : $target.parents( match );
	
	return $container;
}

function getSubmenu( menuID )
{
	return $( "#" + menuID + "-sub" );
}

function navMouseOver( evt )
{
	var $theLI = getContainer( evt.target, "li" );
	
	showSubNav( $theLI );
}

function navMouseOut( evt )
{
	var $theLI = getContainer( evt.target, "li" );
	
	var $theSub = getSubmenu( $theLI.attr( "id" ) );
	if ( $theSub.length == 1 ) {
		$theSub.removeAttr( "pinned" );
		setTimeout( function() { hideSubNav( $theSub ); }, 10 );
	}
}

function subMouseOver( evt )
{
	var $theMenu = getContainer( evt.target, "div.submenu" );
	$theMenu.attr( "pinned", "1" );
}

function subMouseOut( evt )
{
	var $theMenu = getContainer( evt.target, "div.submenu" );
	
	$theMenu.removeAttr( "pinned" );
	// Allow 10ms for someone to re-pin
	setTimeout( function() { hideSubNav( $theMenu ); }, 10 );
}

function showSubNav( $theLI )
{
	var $theSub = getSubmenu( $theLI.attr( "id" ) );
		
	if ( $theSub.length == 1 ) {
		$theSub.slideDown( 150 );
		$theSub.attr( "pinned", "1" );
	}
}

function hideSubNav( $theSub )
{
	if ( $theSub.length == 1 && $theSub.attr( "pinned" ) != "1" ) {
		$theSub.slideUp( 150 );
	}
}

$(document).ready(function(){
	var $expandos = $( ".expando" );
	// First, create a click handler for all expando elements
	$expandos.click( function( evt ) {
		var theTarget = evt.target;
		if ( theTarget.tagName != "H4" ) {
			return;
		}
		var $target = ( theTarget.tagName != "LI" )? $target = $(theTarget ).parents( "li" ) : $( theTarget );

		if ( $target.length == 0 ) {
			return;
		}
		$( "li", $expandos ).removeClass( "open" );
		$target.addClass( "open" );
	});
	
	// Then find any selectors and add mouseover events to those.
	$( "#selectors" ).click( function( evt ) {
		var $target = $( evt.target );
		if ( evt.target.tagName != "LI" ) {
			$target = $target.parents( "LI" );
		}
		if ( $target.length == 0 ) {
			return;
		}
		newBio = "#" + $target.attr( "id" ) + "-bio";
		if ( newBio == "#undefined-bio" ) {
			return;
		}
		$( ".bio" ).hide( 0 );
		$( newBio ).show( 0 );
		
		$( "li", "#selectors" ).removeClass( "sel" );
		$target.addClass( "sel" );
	});
});
