// BRS Drop Menu (12.14.09)
// Copyright Blue Ridge Solutions, Inc.  www.blueridges.com

// INSTRUCTIONS
// All main items must have a class of main_menu and be assigned an id of choice. (ex. <a class="main_menu" id="nav_main">)
// All drop menus must have a class of drop_menu and be assigned the same id as the main item id prepended with sub_.  (ex. <div class="drop_menu" id="sub_nav_main">)
// Not all main menu items require a drop menu

// Setup Variables
var theSpeed = 200; 			// animation speed for showing menus [300]
var closeDropMenuDelay = 400;	// delay to close the current open menu after the mouse leaves it [400]
var openDropMenuDelay = 200;	// delay to open the drop menu after the mouse goes over the main menu item [200]

var dropMenuActive = '';		// the currently active drop menu
var dropMenuRequested = '';


function onOverMenu() {
	var itemId = $(this).attr('id');
	var targetId = "sub_" + itemId;

	// stop any pending events for this menu item
	var theTimer = $(this).attr('timerid');
	if(theTimer) {
		clearTimeout(theTimer);
	}
	
	// request this submenu to open
	dropMenuRequested = targetId;
	$(this).attr('timerid', setTimeout(updateMenus, openDropMenuDelay) );
}


function onOutMenu() {
	// stop any pending events for this menu item
	dropMenuRequested = '';
	var theTimer = $(this).attr('timerid');

	if(theTimer) {
		clearTimeout(theTimer);
	}

	// schedule to close the presently active sub menu
	$(this).attr('timerid', setTimeout(updateMenus, closeDropMenuDelay) );
}

function onOverDropMenu() {
	var targetId = $(this).attr('id');

	// override the menu requested to the sub menu entered
	dropMenuRequested = targetId;
}

function onOutDropMenu() {
	// the submenu has been exited, start the timer to close the sub menu
	dropMenuRequested = '';
	
	var theTimer = $(this).attr('timerid');
	if(theTimer) {
		clearTimeout(theTimer);
	}

	// schedule to close the presently active sub menu
	$(this).attr('timerid', setTimeout(updateMenus, closeDropMenuDelay) );
}

// called via timeout to control the sub menu display
function updateMenus() {
	if(dropMenuActive == dropMenuRequested) return;  // don't do anything if the menu to display is current
	dropMenuActive = dropMenuRequested;

	// show the requested menu
	if(dropMenuActive != '')
		$('#' + dropMenuActive).addClass('active').stop(true,true).fadeIn(theSpeed);
		
	// hide all others
	$('.drop_menu').each(function(i) {
			if($(this).hasClass('active') && $(this).attr('id') != dropMenuActive)
				$(this).removeClass('active').stop(true,true).fadeOut(theSpeed);
	});
}


$(function(){	
	$('.drop_menu').hide();
	$('.main_menu').children('.menu_item').hover(onOverMenu, onOutMenu);
	$('.drop_menu').hover(onOverDropMenu, onOutDropMenu);
	$('.main_menu').children('.menu_item').click(function(e) {
		if($(e.target).attr('href') == '#')
			e.preventDefault();
		});
});

