var menuTimeout;

$(function() {
	$('#nav a').mousemove(function() {
		showSubMenu($(this).attr('id'));
	}).mouseout(function() {
		timeToHide($(this).attr('id'));
	});
	$('.submenu').mousemove(function() {
		showSubMenu($(this).attr('id').replace("sub_", ""));
	}).mouseout(function() {
		timeToHide($(this).attr('id').replace("sub_", ""));
	});
});

function timeToHide(id) {
	clearTimeout(menuTimeout);
	menuTimeout = setTimeout('hideMenu("' + id + '")', 500);
};

function hideMenu(id) {	
	$('#sub_' + id).fadeOut();
}

function showSubMenu(id) {
	var menuParent = $('#' + id);
	var menu = $('#sub_' + id);
	var coords = menuParent.offset();
	$('.submenu').each(function() {
		if ($(this).attr('id').replace("sub_", "") != id) {
			$(this).hide();
		}
	});
	if (menu.css('display') == "none") {
		
		var s_top = coords.top + menuParent.height();
		var s_left;
		if (menuParent.width() > menu.width()) {
			s_left = coords.left + ((menuParent.width() - menu.width()) / 2);
		}
		else if (menuParent.width() < menu.width()) {
			s_left = coords.left - ((menu.width() - menuParent.width()) / 2);
		}
		else {
			s_left = coords.left;
		}
		menu.css({
			'top':			s_top + 6,
			'left':			s_left,
			'opacity':	0
		});
		menu.show().animate({
			'top':			s_top,
			'opacity':	1
		}, 175);
	}
	clearTimeout(menuTimeout);
}
