var selectedNavId = null;
var selectedSubNavId = null;

$( document ).ready( function()
{
    //  Select the currentMainSection menu nav
    if ( currentMainSection != "" && currentMainSection != undefined )
    {
	if ( currentMainSection != undefined )
	{
	    selectedNavId = "nav_" + currentMainSection;
	    
	    // Switch the image to the rollover state
	    if ( currentSection == '' )
	    {
		var img = $( "#" + selectedNavId );
		
	        img.attr( 'src', rollOn( img.attr( 'src' ) ) );
	    }
        
	    // Open the li
	    $( "#li_" + currentMainSection ).find("ul.subnav").css("display","block");
	    $( "#li_" + currentMainSection ).addClass( "selectedSection" );
	}
	
	if ( currentSection != undefined )
	{
	    selectedSubNavId = "sn_" + currentSection;
	    
	    img = $( "#" + selectedSubNavId );
	    img.attr( 'src', rollOn( img.attr( 'src' ) ) );
	}
    }
    
    /**
     * Handle img mouseovers on the page
     */
    $( "img" ).mouseover( function( event )
    {
	if ( isMenuImage( event.target ) )
	{
	    event.target.src = rollOn( event.target.src );
	}
    } );

    /**
     * Handle img mouseouts on the page
     */
    $( "img" ).mouseout( function( event )
    {
	if ( isMenuImage( event.target ) && event.target.id != selectedNavId &&
	      event.target.id != selectedSubNavId )
	{
	    event.target.src = rollOff( event.target.src );
	}
    } );
    
    /**
     * Handle open on rollover
     */
    $("ul.topnav li").not(".selectedSection").hover(
	    function() {
		    $(this).find("ul.subnav").css("display","block");
	    },
	    function() {
		    $(this).find("ul.subnav").css("display","none");
	    }
    );

    
    /**
     * Convert the img src to a rollover src
     */
    function rollOn( src )
    {
	if ( src != undefined && src.indexOf( "_roll.gif" ) == -1 )
	    return src.replace( ".gif", "_roll.gif" );
	else
	    return src;
    }
    
    /**
     * Convert the img src to a non-rollover src
     */
    function rollOff( src )
    {
	if ( src != undefined && src.indexOf( "_roll.gif" ) != -1 )
	    return src.replace( "_roll.gif", ".gif" );
	else
	    return src;
    }
    
    /**
     * Returns true for imgs that are part of the header menu
     */
    function isMenuImage( img )
    {
	return img.src.indexOf( "nav_" ) != -1 &&
	       img.id != "nav_" + currentMainSection;
    }
} );
