var hover = {
	id: false,
	$id: false,
	subid: false,
	$subid: false
};

var set_hover = function(t, is_sub) {
	if(t === false) {
		for (var n in hover) {
			hover[n] = false;	
		}
	}
	else {
		if(is_sub) {
			var idx = t.id.substr(3, t.id.length - 3);
		}
		else {
			var idx = t.id;
		}
		
		hover.id = idx;
		hover.subid = 'sub' + idx;
		hover.$id = '#' + hover.id;
		hover.$subid = '#' + hover.subid;
	}
	
};

var leave_menu = function() {
	if(hover.id === false) {
		$('.submenu').fadeOut('fast');
		$('#nav-menu').find('img.hover').fadeOut('medium');
	}
	else {
		$('.submenu').not(hover.$subid).fadeOut('medium');
		$('.nav-selection').not(hover.$id).find('img.hover').fadeOut('medium');
		setTimeout(leave_menu, 100);
	}
}

$(function() {
/*
$('.nav-selection').hover(function() {
		var $img = $(this).find('img');
		var src = $img.attr('src').replace(/\_normal/, '_highlight');
		
		$img.attr('src', src);
	}, function() {
		var $img = $(this).find('img');
		var src = $img.attr('src').replace(/\_highlight/, '_normal');
		
		$img.attr('src', src);
	});
*/	
	$('.nav-selection').hover(function() {
//									   alert(hover.id);
		if(hover.id != this.id) {
			set_hover(this);
			$(hover.$subid).slideDown('medium');
			$(this).find('img.hover').fadeIn('medium', leave_menu);
		}
	}, function() {
		set_hover(false);
	});
	
	$('.submenu').hover(function() {
		set_hover(this, true);
	}, function() {
		set_hover(false, true);
	});
	
	$('.nav-selection').each(function(i, el) {
		var $subel = $('#sub' + this.id);
		
		if($subel.length) {
			var pos = $(el).offset();
			var pos_table = $('#nav-menu').offset();
			var wid_el = $(el).width();
			var wid_sub = $subel.width();
			var left_adjust = (wid_el - wid_sub - 2) / 2; 
			// The minus 2 is for the border
	//		alert(pos.left + '/' + pos_table.left + '/' + left_adjust);
			$subel.css('margin-left', pos.left - pos_table.left + left_adjust);
		}
	});
});

