/*
	This script:
	- finds the first anchor on the page to point to this page (unless current page is 'Home')
	- assigns the chosen class name
	- if required, assigns the class to the anchor's senior menu items in the hierarchy

	- constructs a breadcrumb with links if required
	- inserts the breadcrumb before the first H1 title


	Potential improvements:
	* addToBreadcrumb should used objects, not text link construction.
	- breadcrumb intro text?
	- breadcrumb separator icon
*/

// constants:
var RECURSE = true;
var NO_RECURSE = false;
var CREATE_BREADCRUMB = true;
var NO_BREADCRUMB = false;

// USER-CONTROLLABLE VARIABLES:
// site-specific variables:
var applicableContainers = new Array(
								new Array("services-menu", RECURSE, CREATE_BREADCRUMB, false),
								new Array("utilities-menu", NO_RECURSE, NO_BREADCRUMB, false));

// behaviour variables:
var typeOfNodeToStyle = 'LI';
var classToAssignMain = 'selected';
var classToAssignParent = 'selectedparent';
var useDifferentParentAndChildStyles = false;
var excludeHomeLinksInRemainderContainers = true;

// breadcrumb variables:
var showBreadcrumb = false;


// NOT user-controllable:
// other program variables:
var isLayers = 0;
var isAll = 0;
var isID = 0;
var currentClassToAssign;
var breadcrumbElements = new Array();
var breadcrumb = document.createElement('p');

// add an event listener to be called when the page loads:
if( window.addEventListener ) {
  window.addEventListener('load',highlight,false);
} else if( document.addEventListener ) {
  document.addEventListener('load',highlight,false);
} else if( window.attachEvent ) {
  window.attachEvent('onload',highlight);
}

// overall management function
function highlight() {
	for (x in applicableContainers)
	{
		currentClassToAssign = classToAssignMain;
		var linkFound = highlightInsideContainer(applicableContainers[x][0], applicableContainers[x][1], applicableContainers[x][2]);
		if (linkFound)
			applicableContainers[x][3] = true;
	}

	highlightInRemainingContainers();
}

function highlightInRemainingContainers() {
	// loop through breadcrumb elements
	for (x=breadcrumbElements.length-1; x>=0; x--)
	{
		// for each container ...
		for (y in applicableContainers)
		{
			// ... with no links already selected
			if (applicableContainers[y][3])
				continue;
			
			containingElement = getContainer(applicableContainers[y][0]);
			allAnchorsInContainer = containingElement.getElementsByTagName('A');

			// for each a tag
			for (z=0; z<allAnchorsInContainer.length && !found; z++)
			{
				var found = false;
				// if breadcrumb element.href == a.href
				if (breadcrumbElements[x].getAttribute('href') == allAnchorsInContainer[z].getAttribute('href'))
				{
					if (useDifferentParentAndChildStyles)
						currentClassToAssign = classToAssignParent;
					else
						currentClassToAssign = classToAssignMain;

					// stop 'home' being selected if there is no link to any parents in current container
					if(excludeHomeLinksInRemainderContainers && breadcrumbElements[x].getAttribute('href') == './' && getThisPageName() != './')
						break;

					// assign style
					doHighlight(allAnchorsInContainer[z], false, false);

					found = true;
				}
			}

		}
	}
}

// manager function for finding elements to highlight, and highlighting them
function highlightInsideContainer(container, highlightParents, makeBreadcrumbForContainer) {

	containingElement = getContainer(container);

	e = getRelevantAnchor(containingElement);		// find relevant element (in this case an anchor)

	doHighlight(e, highlightParents, makeBreadcrumbForContainer);		// apply style right up the hierarchy

	if (makeBreadcrumbForContainer)
	{
		addHomeToBreadcrumb();
		constructBreadcrumb();
		displayBreadcrumb();
	}

	if (e == null)
		return false;
	return true;
}

// get containing element, cross-browser compatible:
function getContainer(container) {
	if (document.getElementById) {
		isID = 1; isDHTML = 1;
	}
	else {
		if (document.all) {
			isAll = 1; isDHTML = 1;
		}
		else {
			browserVersion = parseInt(navigator.appVersion);
			if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {
				isLayers = 1; isDHTML = 1;
			}
		}
	}
	var isIE = 0;

	if (navigator.appName.indexOf('Microsoft Internet Explorer') != -1) {isIE = 1;}
	
	return findDOM(container, 0);
}

function getThisPageName() {
	full_href = document.location.href;
	if (full_href.indexOf('#') != -1)
		this_page = full_href.substring(full_href.lastIndexOf('/') + 1, full_href.indexOf('#'));
	else
		this_page = full_href.substring(full_href.lastIndexOf('/') + 1, full_href.length);
	return this_page;
}

// find first anchor pointing to this page:
function getRelevantAnchor(containingElement) {
	all_anchors = containingElement.getElementsByTagName('A');

	this_page = getThisPageName();

	for (i=0; i < all_anchors.length; i++)
	{
		full_anchor_href = all_anchors[i].href;
		short_anchor = full_anchor_href.substring(full_anchor_href.lastIndexOf('/') + 1, full_anchor_href.length);

		if (short_anchor == this_page)
		{
			return all_anchors[i];
		}
	}

	return null;
}

// highlight:
function doHighlight(e, precursive, addToCurrentBreadcrumb) {
	if (e == null)
		return;

	if (e.nodeName == typeOfNodeToStyle) {
		applyStyle(e, addToCurrentBreadcrumb);
		if (!precursive)
			return;
		if (useDifferentParentAndChildStyles)
			currentClassToAssign = classToAssignParent;
	}
	// if e has a parent, call the function on that parent
	if (e.parentNode != null)
		doHighlight(e.parentNode, precursive, addToCurrentBreadcrumb);
}

// apply the chosen style to the given element:
function applyStyle(e, addToCurrentBreadcrumb) {
	//alert ("Setting style on: " + e.innerHTML);
	if (e.className != '')
		e.className = e.className + " " + currentClassToAssign;
	else
		e.className = currentClassToAssign;

	if (addToCurrentBreadcrumb) {
		addToBreadcrumb(e);
	}
}

// add a new link to the breadcrumb:
function addToBreadcrumb(e) {
	e = e.getElementsByTagName('a')[0];

	//clone anchor
	anchor = e.cloneNode(true);
	
	//add to start of breadcrumb array
	breadcrumbElements.unshift(anchor);

//	text = e.innerHTML.replace('<BR>', ' ');	// IE - upper case tags
//	text = text.replace('<br>', ' ');			// Firefox - lower case tags
//	breadcrumb = '&raquo; <a href="' + e.href + '">' + text + '</a> ' + breadcrumb;		// &raquo;
}

// add 'Home' to breadcrumb
function addHomeToBreadcrumb() {
	homeLink = document.createElement('a');
	homeLink.setAttribute('href', './');
	homeLink.appendChild(document.createTextNode("Home"));
	breadcrumbElements.unshift(homeLink);
}

// add breadcrumb links to a 'p' tag, inserting separators and spaces between
function constructBreadcrumb() {
	for (a in breadcrumbElements)
	{
		breadcrumb.appendChild(document.createTextNode('\u00BB\u0020'));
		breadcrumb.appendChild(breadcrumbElements[a]);
		breadcrumb.appendChild(document.createTextNode('\u0020'));
	}
}

function displayBreadcrumb() {
	if (!showBreadcrumb)
	{
		breadcrumb.style['display'] = "none";
	}

	breadcrumb.id="breadcrumb";
	
	document.getElementsByTagName('H1')[0].parentNode.insertBefore(breadcrumb, document.getElementsByTagName('H1')[0]);
}

function findDOM(objectID, withStyle) {
	if (withStyle == 1) {
		if (isID) { return (document.getElementById(objectID).style) ; }
		else { 
			if (isAll) { return (document.all[objectID].style); }
		else {
			if (isLayers) { 
				if (objectID) { return (document.layers[objectID]); }
				else { return (document.layers[objectID]); }
			}
		};}
	}
	else {
		if (isID) { return (document.getElementById(objectID)) ; }
		else { 
			if (isAll) { return (document.all[objectID]); }
		else {
			if (isLayers) { 
				if (objectID) { return (document.layers[objectID]); }
				else { return (document.layers[objectID]); }
			}
		};}
	}
}