

menu_flag_main = 0;
menu_flag_sub = 0;

checkClosing = function () {
	if (menu_flag_main==0 && menu_flag_sub==0) {
		$('#sub-nav').slideUp(100);
	}
}

$(document).ready(function(){
	$('#main-nav ul li').each (function (index, element) {
		$(element).data ('pos', index+1);
		$(element).hoverIntent ({
			over: function (event) {
				var parent = $(this).parent();
				var last = parent.data('last');
							
				// hide last one if any
				if (last > 0) {
					var classname = '.sub-nav-'+last;
					$(classname).hide();
				} 
				
				// show the wanted one (if any)
				var classname = '.sub-nav-'+$(this).data('pos');
				if ($(classname).length > 0) {
					// show bar if not visible
					if (! $('#sub-nav').is(':visible')) {
						$('#sub-nav').slideDown(100);
					}

					// place arrow
					$('#sub-nav img.arrow').css({left: ($(this).position().left + $(this).width()/2 - 12) + 'px'});
					
					// show menu
					parent.data ('last', $(this).data('pos'));
					$(classname).fadeIn(100);
					
					menu_flag_main++;
				}
			},
			out: function (event) {
				menu_flag_main--;
				if (menu_flag_main<0) menu_flag_main=0;
				checkClosing();
			},
			timeout: 500
		});
	});
	
	$('#sub-nav').hoverIntent ({
		over: function (event) {
			menu_flag_sub++;
		},
		out: function (event) {
			menu_flag_sub--;
			if (menu_flag_sub<0) menu_flag_sub=0;
			checkClosing();
		},
		timeout: 500
	});	
});

