var timeout;
var loginFocus = false;
var fadeSpeed = 400;

$j( document ).ready( function() {
    // Tour America Websites Menu
    $j( '#togglesites' ).hover( function() {
        hideAll();
    	$j( 'div.showhide,div#sites' ).fadeIn( fadeSpeed );
    }, function () {
        timeout = setTimeout( "hideAll();", 1000 );
    } );
    $j( 'div.showhide,div#sites' ).hover( function() {
        clearTimeout( timeout );
    }, function () {
    	timeout = setTimeout( "hideAll();", 1000 );
    } );

    // Quick Links Menu
    $j( '#togglelinks' ).hover( function() {
        hideAll();
        $j( 'div.showhide,div#links' ).fadeIn( fadeSpeed );
    }, function () {
        timeout = setTimeout( "hideAll();", 1000 );
    } );
    $j( 'div.showhide,div#links' ).hover( function() {
        clearTimeout( timeout );
    }, function () {
        timeout = setTimeout( "hideAll();", 1000 );
    } );

    // Customer Login
    $j( '#togglelogin' ).hover( function() {
        hideAll();
        $j( 'div.showhide,div#login' ).fadeIn( fadeSpeed );
    }, function () {
        timeout = setTimeout( "hideAll();", 1000 );
    } );
    $j( 'div.showhide,div#login' ).hover( function() {
        clearTimeout( timeout );
    }, function () {
        if( !loginFocus )
        {
            timeout = setTimeout( "hideAll();", 1000 );
        }
    } );

    // If login fields have focus don't hide form
    $j( 'div#login input#clientid, div#login input#password' ).blur( function() {
        loginFocus = false;
        timeout = setTimeout( "hideAll();", 1000 );
    } );
    $j( 'div#login input#clientid, div#login input#password' ).focus( function() {
        clearTimeout( timeout );
        loginFocus = true;
    } );
    
    // show error message if user tries to enter a login code that is too long.
    var backspaceCode = 8;
    var tabCode = 9;
	$j('input.clientid-check').keydown(function(e){
		if( $j(this).val().length == 5  && e.which != backspaceCode && e.keyCode != backspaceCode && e.which != tabCode && e.keyCode != tabCode ){
			$j('.client-id-error').fadeIn( fadeSpeed );
			setTimeout(function(){
				$j('.client-id-error').fadeOut( fadeSpeed );
			}, 5000);
		}
		else{
			$j('.client-id-error').fadeOut( fadeSpeed );
		}
			
	});
});

/**
 * Hide all menus
 * 
 * @return
 */
function hideAll()
{
	clearTimeout( timeout );
	$j( 'div.showhide,div#links' ).fadeOut( fadeSpeed );
    $j( 'div.showhide,div#sites' ).fadeOut( fadeSpeed );
    $j( 'div.showhide,div#login' ).fadeOut( fadeSpeed );
}