// by matthieu baudoux - hypernovae, 27 August 2010
// http://www.hypernovae.be

$(document).ready(function(){
	
	// at first we want to hide all submenus
	// if the page loads slowly users will see the menus
	// no problem as they will appear again
	// keep the active one visible at all time
	slideAllUp();

	// same goes if the mouse leaves the navigation div
	$('.nav').mouseleave( function(e) {
		slideAllUp();	
	});

	// when a mouse enters a submenu, display it
	$('.nav ul li').live('mouseenter', function(e){
		$(this).find('ul').slideDown();
	});
	
	// when a mouse leaves a submenu *by the top*, hide it
	$('.nav ul li:not(.active)').live('mouseleave', function(e){
		
		var $mayLeaveBy = 'top'; // either 'top', 'tophalfsides', 'sides' or 'all'
		
		// where is our element positioned ? 
		var $elementY = $(this).offset().top;
		var $elementHeight = $(this).height();

		// where is the mouse positioned ? 
		// wait a bit before checking
		var $mouseY = e.pageY;
				
		// if mouse went out by an allowed direction
		// it will have an equal or smaller Y position
		switch ($mayLeaveBy) {
			case 'top':
				$hide_f = ( $mouseY <= $elementY );
				break;
			
			case 'tophalfsides':
				$hide_f = ( $mouseY <= $elementY+($elementHeight/2) );
				break;
			
			case 'sides':
				$hide_f = ( $mouseY <= $elementY+$elementHeight-1 );
				break;
			
			default:
				$hide_f = true;
		}
		
		if ( $hide_f ) {
			// we may hide this element
			$(this).find('ul').slideUp();
		} 
		// else leave the element open
		
	});
	
	function slideAllUp() {
	
		// only if at least one will stay down
		if ( $('.nav ul ul li.active').size() > 0 ) {
			$('.nav ul ul:not(:has(li.active))').slideUp(); 
		} 

	}
	
});

