var fade_out_intervals = Array();
var fade_in_intervals = Array();

// Menu timing (in ms)
var hover_on_delay_cold = 400;	// Time before showing a dropdown menu when a menu is not currently showing (a "cold" open)
var hover_on_delay_hot = 0;	// Time before showing a dropdown menu when one is currently showing (a "hot" open)
var hover_off_delay = 500;		// Time before hiding a dropdown menu
var fade_in_delay = 100;		// Length of fade in effect
var fade_out_delay = 100;		// Length of fade out effect

$(function() {
	$('#top_navigation li.root_menu').hover(
		function() {	// hover on
			id = $(this).attr('id').replace('root_menu_', '');
			clearTimeout(fade_out_intervals[id]); // Clear any fade out intervals for this nav
			if ($(this).find('ul.section.visible').length == 0) {
				$(this).find('ul.section').addClass('fade_in'); // Add fade_in class so following timeout function will fade appropriately.
			}
			
			// To determine how long we need to wait before showing the dropdown, we need to know if a dropdown is currently visible.
			if ($('#top_navigation .visible').length) {
				delay = hover_on_delay_hot;
			}
			else {
				delay = hover_on_delay_cold;
			}
			
			// Current class is one that is showing a menu -- active is just one that is highlighted. More than one can be highlighted at once.
			// Remove the current class from any others.
			$('#top_navigation .current').removeClass('current');
			// Remove active from any that are not current.
			$('#top_navigation .active').not('#top_navigation .current').removeClass('active');
			
			// Add current and active classes to this menu
			$(this).addClass('current active');
			$(this).find('.fade_out').removeClass('fade_out');
			fade_in_intervals[id] = setTimeout(function() {
				// Fade out any other menus
				$('#top_navigation ul.fade_out').removeClass('fade_out visible').hide();
				$('#top_navigation .active').not('#top_navigation .current').removeClass('active');
				
				// Fade in this menu
				$('#top_navigation ul.fade_in').removeClass('fade_in').fadeIn(fade_in_delay, function() {
					$(this).addClass('visible');
				});
			}, delay);
		},
		function() {	// hover off
			id = $(this).attr('id').replace('root_menu_', '');
			$(this).removeClass('current');
			clearTimeout(fade_in_intervals[id]);	// Clear any fade in interval for this nav
			$('#top_navigation ul.section.fade_in').removeClass('fade_in');	// Clear any fade_in classes
			$(this).find('ul.section').addClass('fade_out'); // Add fade_out class so following timeout function will fade appropriately.
			fade_out_intervals[id] = setTimeout(function() {
				$('#top_navigation ul.fade_out').removeClass('fade_out visible').fadeOut(fade_out_delay, function() {
					$('#top_navigation .active').removeClass('visible');
				});
				$('#top_navigation .active').not('#top_navigation .current').removeClass('active');
			}, hover_off_delay);
		}
	);
});
