// Main Navigation Script
// Also requires jquery-1.4.1.min.js

$(document).ready(function(){
	$(".simplenav>ul>li").each(function(){
		initialiseNav(this);
	});

	$(".simplenav>ul>li>a").bind("mouseenter",function(){
		hideAllNav();
		showChildNav(this);
	});

	$(".simplenav").bind("mouseleave",function(){
		hideAllNav();
		showCurrentNav();
	});

});



function initialiseNav(navitem){
	//centre of this button
	var widthone = 0;
	widthone = $(navitem).outerWidth();
	widthone = widthone/2;

	$(navitem).prevUntil('ul').each(function() {
		widthone = widthone + ($(this).outerWidth());
	});

	//width of subnav
	var widthtwo = 0;
	$(navitem).find("li").each(function() {
		widthtwo = widthtwo + ($(this).outerWidth());
	});
	widthtwo = widthtwo/2;

	//calculate margin
	var marginvalue = 0;
	marginvalue = widthone - widthtwo;

	if(marginvalue>0){
		//set left margin of first subnav item only if it isn't negative
		//$(navitem).children("ul").find("li").first().css("margin-left", marginvalue);
	}
}

function hideAllNav(menu){
	$(".simplenav ul ul").removeClass("on fix");
	$(".simplenav ul ul").addClass("off");
}

function showChildNav(actOnMe){
	$(".simplenav li").removeClass("MenuVisible");
	$(actOnMe).parent("li").find("ul").removeClass("off");
	$(actOnMe).parent("li").find("ul").addClass("on fix");
	$(actOnMe).parent("li").not($("li.here")).find("ul").bind("mouseenter",function(){
		$(this).parent("li").addClass("MenuVisible");

	}).bind("mouseleave",function(){
		$(this).parent("li").removeClass("MenuVisible");
	});
}

function showCurrentNav(){
	//only do this if it is currently hidden
	if($(".simplenav li.here ul").hasClass("off")){
		$(".simplenav li.here ul").removeClass("off");
		$(".simplenav li.here ul").addClass("on fix");
	}
}


// Directs all rel="external" links to open in new window
function externalLinks()
	{
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++)
		{
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external nofollow")
		anchor.target = "_blank";
		else if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
		}
	}
window.onload = externalLinks;


// Email scrambler
function sendToMe(one, two, three, four, five){
	// 'two' and 'four' are ignored - just junk.
	window.location = 'mailto:'+ one + three + five;
}

