var navFadeSpeed = 200;
var navTimeout;

function navInit()
{
	// Add mouse over behaviour to primary tabs
	$("#nav .tab").each( function(i) {
		var channelId = this.id.replace("tab-", "channel-");
		$("#nav #"+channelId+" h2").wrap("<a href=\""+this.href+"\"></a>");
		$("#nav #"+channelId+" h2").bind("mouseenter", navClearTimeout);
		$("#nav #"+channelId+" h2").bind("mouseleave", navStartTimeout);
		$(this).bind("mouseenter", navShowChannel);
	});
	
	// Add mouse over behaviour to secondary tabs
	$("#nav .channel li a").each( function(i) {
		this.id = "chTab" + i;
		$(this).before("<div id=\"chTab" + i + "Hover\" class=\"tab-hover\"><div class=\"tab-hover-left\"></div></div>");
		$(this).bind("mouseenter", navShowTab);
		$(this).bind("mouseleave", navHideTab);
	});
	
	// Mousing over the channel bar clears timer
	$("#nav .channel ul").each( function(i) {
		$(this).bind("mouseover", navClearTimeout);
		$(this).bind("mouseleave", navStartTimeout);
	});
	
	// Show current tab
	var tabId =	$("#nav .channel li a.current").attr("id");
	if (tabId) {
		$("#nav #"+tabId+"Hover").addClass("current");
		$("#nav #"+tabId+"Hover").css("left", $("#nav #"+tabId).position().left);
		$("#nav #"+tabId+"Hover").css("top", $("#nav #"+tabId).position().top);
		$("#nav #"+tabId+"Hover").width($("#nav #"+tabId).width()+30);
		$("#nav #"+tabId+"Hover").show();
	}
}

function navStartTimeout()
{
	// Revert to default state
	navTimeout = setTimeout(navRevert, 500);	
}

function navClearTimeout()
{
	clearTimeout(navTimeout);
}

function navShowChannel() 
{	
	navClearTimeout();
	
	// Hide all channels
	$("#nav .channel").hide();
	
	// Fade in specified channel
	var channelId = this.id.replace("tab-", "channel-");
	if (!$.browser.msie) {
		$("#nav #"+channelId).fadeIn(navFadeSpeed);
	} else {
		$("#nav #"+channelId).show();
	}
}

function navShowTab() 
{	
	navClearTimeout();

	// Size and position mouse over
	$("#nav #"+this.id+"Hover").css("left", $(this).position().left);
	$("#nav #"+this.id+"Hover").css("top", $(this).position().top);
	$("#nav #"+this.id+"Hover").width($(this).width()+30);

	// Hide current tab
	if (!$("#nav #"+this.id+"Hover").hasClass("current")) $("#nav .channel div.current").hide();	

	// Fade in tab
	if (!$.browser.msie) {
		$("#nav #"+this.id+"Hover").fadeIn(navFadeSpeed);
	} else {
		$("#nav #"+this.id+"Hover").show();
	}
}

function navHideTab()
{
	// Hide tab
	if (!$("#nav #"+this.id+"Hover").hasClass("current")) $("#nav #"+this.id+"Hover").hide();
}

function navRevert()
{
	if (!$.browser.msie) {
		$("#nav .channel:not(.current)").fadeOut(navFadeSpeed);	
		$("#nav .channel.current").fadeIn(navFadeSpeed);
		$("#nav .channel div.current").fadeIn(navFadeSpeed);
	} else {
		$("#nav .channel:not(.current)").hide();
		$("#nav .channel.current").show();
		$("#nav .channel div.current").show();
	}
}