/* setMenu()
**
** 1) Find the <a> tag that matches the current page's url and store its
**    parent <li> tag in $parentLi.  Note the call to stripLocation()
**    to get a clean match on the <a> tag's href attribute.
** 2) Using the parent <li> (of the active <a> tag), do the following...
**    a) make all of its child (nested) <ul> tags visible
**    b) find any <a> tags within the <li> and add the 'selected' css class
**    c) now we need to move up a level so...
**          i) get the parent <ul> tag of the current <li> tag ($parentLi)
**         ii) find its parent <li> and re-assign it to the $parentLi variable
**        iii) try the iteration again and repeat for the next level 'up
**             the tree'
** 3) Job done, every <a> tag above, and including, the currently active <a>
**    tag will have the 'selected' css class assigned to it, further more, the
**    active branch of the tree will be visible (second-level <ul> tags
**    are set to 'display: none;' in the css - these are now set visible).
**
** To ininitialise the menu, you must...
**
** 1) Include this script.
** 2) Call the setMenu() function with either no parameter to sync to the
** current page, or the target url of the menu item to be selected, e.g.
**
** // Syncs to the current page
** $(function() {
**    setMenu();	
** });
**
** // Syncs to the '/registrars-launch-sunrise.html' menu item
** $(function() {
**    setMenu('/registrars-launch-sunrise.html');
** });
*/


// Helper function to get clean filename
var stripLocation = function(href) {
		if (typeof href !== "string") {
			href = window.location.href;		
		}

		var domain = window.location.protocol + '//' + window.location.hostname;
		if ((window.location.port) && (window.location.port.length > 0)) {
			domain += ":" + window.location.port;
		}

		if (href.indexOf(domain) === 0) {
			return href.substr(domain.length);
		} else {
			return href;
		}
};


var setMenu = function(target)
{
	var currentUrl = stripLocation(target).toLowerCase();
	$("ul.menu a").each(function() {
		var href = stripLocation(this.href).toLowerCase();
		if (href === currentUrl) {
			var $parentLi = $(this).parent("li");
			while (($parentLi) && ($parentLi.length > 0))
			{
				$parentLi.children("ul").show();
				var $activeLink = $parentLi.children("a");
				$activeLink.addClass("selected");
				$parentLi = $parentLi.parent("ul").parent("li");
			}
			return;	// There can only be one current page!
		}
	});
};

// Call the default setMenu() nethod to sync to the current page.
// Remove this call after ALL the pages have been updated to include
// this block of script.
//$(function() {
//	setMenu();	// Sync menu to current page
//});
