
// utility function to allow java to sleep for specified amount of milliseconds
function sleep(timeout)
{
	var tStart = new Date();
	
	while(true)
	{
		var tCurr = new Date();
		var tDiff = tCurr.getTime() - tStart.getTime();
			
		if(tDiff > timeout)
		{
			return true;
		}
	}
}

// make sure the LHN is completely initialized
function LHNIsInitialized(timeout)
{
	var lhn = window.top.frames["leftFrame"];
	
	if(	lhn.selectMenuItemWithPath != null &&
		lhn.gbInitComplete != null &&
		lhn.gbInitComplete == true)
	{
		return true;
	}
	else
	{
		return false;
	}
				
	/*
	if(lhn != null)
	{
		
		for(var i = 0; i < timeout; i++)
		{
			if(	lhn.selectMenuItemWithPath != null &&
				lhn.gbInitComplete != null &&
				lhn.gbInitComplete == true)
			{
				return true;
			}
			
			sleep(1000);
		}
	
		var mesg =	"It appears that the Left Hand Navigation Menu is taking a long time to load.\n" +
					"The current page will continue to load without it, but the web sites functionality will be limited.\n\n" +
					"If this problem persists, please contact Defence Honours and Awards and report the problem.";
		alert(mesg);
		return false;
	}
	else
	{
		return false;
	}
	*/
}

// update the LHN to make sure currect menu item is selected
// doing this during the onload event means that regardless of how the page is navigated
// to (LHN selection, or using the browser back/forward buttons) the LHN will always
// be updated.
// the path value is optional 
//	if provided then the LHN is initialized to the menu item with the provided path selectMenuItemWithPath.
//	if NOT provided then it is assumed that the LHN initialization path is the current "mainFram" document path
function initLeftHandNav(path)
{	
	if	(
			window.top.frames["leftFrame"] != null &&
			window.top.frames["mainFrame"] != null &&
			LHNIsInitialized(10)
		)
	{					
		// tell the LHN to update the currently selected menu item
		var sCurrPath = path != null ? path : window.top.frames["mainFrame"].location.pathname.substr(0, 1) == '/' ? window.top.frames["mainFrame"].location.pathname : "/" + window.top.frames["mainFrame"].location.pathname;
		
		// split the path into it's directory/file parts
		var dirs = sCurrPath.split('/');
		
		// loop until menu item selected or sCurrPath is empty
		while(dirs.length > 0)
		{
			var sPath = dirs.join('/');
			if(window.top.frames["leftFrame"].selectMenuItemWithPath(sPath, false))
			{
				return true;
			}
			else
			{
				dirs.pop();
			}
		}
		
		return false;
	}
	else
	{
		return false;
	}
}
	
// initialize the warning message
function initWarningMessage()
{
	var bTopFrame = window.top.frames["topFrame"] != null;
	var bLeftFrame = window.top.frames["leftFrame"] != null;
	var bMainFrame = window.top.frames["mainFrame"] != null;
	var elem = document.getElementById("hidden_content_header");
	
	if(elem != null)
	{
		elem.style.display = bTopFrame && bLeftFrame && bMainFrame ? "none" : "block";
	}
}

// initialize the content path
function initContentPath()
{
	// insert the content path
	var elem = document.getElementById("hidden_content_header");
	if(elem != null)
	{
		var elemDIV = document.createElement("div");
		elemDIV.setAttribute("id", "content_path");
			
		var path = unescape(document.location);
		//path = path.replace(/\//g, " > ");
		//path = path.replace(/.htm/g, "");
		//path = path.replace(/.htm/g, "");
		
		elemDIV.innerHTML = "<p>Path: <a href=\"" + document.location + "\">" + path + "</a></p>";
		
		insertBefore(document.body, elemDIV, elem);
	}
}

// return the parent folder path
function getParentFolder(path, upCount)
{
	// split the path into it's directory/file parts
	var dirs = path.split('/');
	
	// pop as many as required
	for(var i = 0; i <= upCount; i++)
	{
		if(dirs.length == 0)
		{
			return "/";
		}
		else
		{
			dirs.pop();
		}
	}

	return dirs.join("/") + "/";
}

// can we show the up hyperlink?
function canShowUpHyperLink()
{
	if	(
			window.top.frames["leftFrame"] != null &&
			window.top.frames["mainFrame"] != null
		)
	{	
		var sTopPath = getParentFolder(unescape(window.top.location.pathname), 0);
		var sContentPath = getParentFolder(unescape(window.top.frames["mainFrame"].location.pathname), 1);
		
		return (sTopPath + "Content/").toUpperCase() != sContentPath.toUpperCase();
	}
	else
	{
		return false;
	}
}

// add a query string key/value pair to the specified href
function addQStoHref(href, key, value)
{
	// update the href so the hyperlink is loaded with the left hand nav				
	var qs = href.split('?').length > 1 ? href.split('?')[1] : null;
				
	if(qs != null)
	{
		// query string exists, look for specified key.
		if(qs.search(key + "=") > -1)
		{			
			// current query string key DOES exist, update the value
			var keyValuePairs = qs.split("&");
			var sRetValue = href.split('?')[0] + "?";
			
			for(var i = 0; i < keyValuePairs.length; i++)
			{
				var keyValuePair = keyValuePairs[i].split("=");
				if(keyValuePair[0] == key)
				{
					sRetValue += keyValuePair[0] + "=" + value + "&";
				}
				else
				{
					sRetValue += keyValuePair[0] + "=" + keyValuePair.length > 1 ? keyValuePair[1] : "" + "&";
				}
			}
			
			if(	sRetValue.substr(sRetValue.length - 1) == "?" ||
				sRetValue.substr(sRetValue.length - 1) == "&")
			{
				sRetValue = sRetValue.substr(0, sRetValue.length - 1);
			}
			
			return sRetValue;
		}
		else
		{
			// current query string key does NOT exist, append it to the end
			return href + "&" + key + "=" + value;
		}
		
	}
	else
	{
		return href + "?" + key + "=" + value;
	}
}

// bookmark the current content page
function bookMarkThisArticle()
{
	if(	window.top.frames["leftFrame"] != null &&
		window.top.frames["mainFrame"] != null)
	{
		var sLocation = unescape(window.top.location.href.substr(0, window.top.location.href.length - window.top.location.search.length)) + "?mi=" + unescape(window.location.pathname); //addQStoHref(document.location.toString(), "lhn", "1");
		window.external.AddFavorite(sLocation.toString(), document.title);
	}
	else
	{
		var sLocation = unescape(window.top.location.href.substr(0, window.top.location.href.length - window.top.location.search.length)) + "?lhn=1"
		window.external.AddFavorite(sLocation.toString(), document.title);
	}

	return true;
}

// can user add to favorites via javascript?
function canAddToFavorites()
{	
	return	navigator.appName == "Microsoft Internet Explorer" &&
			parseInt(navigator.appVersion) >= 4;		
}

// initialize the mini toolbar
function initMiniToolBar()
{
	// inject print href and banner for printing
	/*
	<div class="mini_toolbar">
		<a id="up_one_button" title="Return up to the parent section" href="XXX">Up</a>
		<a id="bookmark_button" onclick="return bookMarkThisArticle();" title="Bookmark the current article" href="#">Bookmark</a>
		<a id="email_button" onclick="onEmail(); return false;" title="Email to a friend" href="">Email</a>
		<a id="print_button" title="Print the current article" href="mailto:?">Print</a>
	</div>
	*/
	
	var elem = document.getElementById("hidden_content_header");
	if(elem != null)
	{
		var mailSubject = "Link to Defence Honours and Awards - " + document.title + " page";
		var mailBody =	window.top.frames["leftFrame"] != null &&
						window.top.frames["mainFrame"] != null ?
							escape(window.top.location.href.substr(0, window.top.location.href.length - window.top.location.search.length)) + "?mi=" + escape(window.location.pathname) :
							escape(window.top.location.href.substr(0, window.top.location.href.length - window.top.location.search.length)) + "?lhn=1";
		
		var elemDIV = document.createElement("div");
		elemDIV.setAttribute("id", "mini_toolbar");
		//elemDIV.setAttribute("align", "right");
		
		elemDIV.innerHTML =
			(canShowUpHyperLink() == true ? "<a id=\"up_one_button\" title=\"Return up to the parent section\" href=\"..\">Up</a>" : "") +
			(canAddToFavorites() == true ? "<a id=\"bookmark_button\" onclick=\"return bookMarkThisArticle();\" title=\"Add to Favourites\" href=\"#\">Bookmark</a>" : "") +
			"<a id=\"email_button\" title=\"Email to a friend\" href=\"mailto:?subject=" + mailSubject + "&body=" + mailBody + "\">Email</a>" +
			"<a id=\"print_button\" onclick=\"window.print(); return false;\" title=\"Print the current article\" href=\"\">Print</a>";
		
		insertAfter(document.body, elemDIV, elem);
	}	
}

// initialize the print banner
function initPrintBanner()
{
	var elem = document.getElementById("hidden_content_header");
	if(elem != null)
	{
		var elemPrintBanner = document.createElement("p");
		elemPrintBanner.setAttribute("id", "print_banner");
		elemPrintBanner.innerHTML = "Defence Honours and Awards";
		
		insertAfter(document.body, elemPrintBanner, elem);
	}
}

// initialize the content title
function initContentPageTitle()
{
	// prefix document title
	document.title = "Department of Defence - Defence Honours and Awards - " + document.title;
}

// event to fire when hyperlink is clicked
function onGoToLinkAndUpdateLHN(evt)
{
	if(evt == null)
	{
		return true;
	}
	
	// get element that fired the event	
	var elem = (evt.srcElement != null) ? evt.srcElement : evt.originalTarget;

	if(	
			(elem != null) &&
			(window.top.frames["leftFrame"] != null) &&
			(elem.protocol == "http:" || elem.protocol == "https:") &&
			(elem.target == "" || elem.target == "_self")
		)
	{		
		// tell the LHN to update the currently selected menu item
		// this is done even though content files can initialize it during
		// their onload event because not all hyperlinks are links to htm content
		initLeftHandNav(elem.pathname);
	}
	
	return true;
}

// initialize hyperlinks
function initHyperLinks()
{
	var elems = document.links;
	if(elems != null)
	{
		for(var i = 0; i < elems.length; i++)
		{		
			// add event handler to the <a> tags
			addEvent(elems[i],'click',onGoToLinkAndUpdateLHN);			
		}
	}
}

// initialize the content page
function initContentPage()
{
	initWarningMessage();
	initContentPath();
	initMiniToolBar();
	initPrintBanner();	
	initHyperLinks();
	initContentPageTitle();
	initLeftHandNav();
}

// utility function to return all elements of the specified class
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// utility function to insert node after referenceNode which is a child of parent
function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode != null ? referenceNode.nextSibling : null);
}

// utility function to insert node before referenceNode which is a child of parent
function insertBefore(parent, node, referenceNode)
{
	parent.insertBefore(node, referenceNode);
}

// utility function to add event handler to specified object
function addEvent(	obj,	// objet to attache event to
					type,	// event to be handled ie. load, click, unload etc
					fn )	// function to fire when event happens
{
	if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function()
						{
							if (obj["e"+type+fn] != null)
							{
								obj["e"+type+fn]( window.event );
							}
						}
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else if (obj.addEventListener)
	{
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else
	{
		obj["on"+type] = obj["e"+type+fn];
	}
}

// special event cache that is used to help release memory when
// the document unloads. fixes memory leak in IE 6.
var EventCache = function()
{
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();

// add onload and onunload event handlers
addEvent(window,'load',initContentPage);
addEvent(window,'unload',EventCache.flush);