/**
* Global JavaScript Definitions
*/


var viewHandler = WebPage;
window.onload = function()
	{
	if (viewHandler !== WebPage)
		{
		// Extend the base page class and create the xhtml object
		viewHandler.inheritsFrom( WebPage );
		xhtml = new viewHandler();
		}
	else
		{
		// Create a generic page xhtml object
		xhtml = new WebPage();
		}
	// Initialize the page
	xhtml.init();
	}



/**
* Creates a new WebPage object with methods used by all pages, can be extended to add page specific methods.
*/
function WebPage()
	{
	// Step 1. Define Properties

	var _instance = this;
	this.initialized = false;
	this.debug = false;


	// Scrolling branding image properties
	this.brandingDiv = null;
	this.brandingTimer = null;
	this.brandingWidth = 0;
	this.brandingPos = 0;
	this.brandingPaused = false;
	this.brandingSet = '001';



	// Step 2. Define Public Methods

	/**
	* Sets up the initial page state and event handlers
	*/
	this.init = function()
		{
		this.initAnchors();
		this.initInputButtons();
		this.initSidebar();

		// Add virtual scrollbars to document
		var scrollbars = new Scrollbars();

		// Start the branding scroller
		this.initBranding();

		// Set class as initialized
		this.initialized = true;
		}


	/**
	* Adds standard event handlers to process in-page links and offsite links
	*/
	this.initAnchors = function()
		{
		var links = document.getElementsByTagName('a');
		for (var x = 0; x < links.length; x++)
			{
			// 1. Make offsite links and pdfs open in a new tab/window
			if (/\b(offsite|pdf)\b/.exec(links[x].className))
				{
				links[x].onclick = function()
					{
					window.open(this.href,'_blank');
					return false;
					}
				}

			// 2. Make inpage links smooth scroll
			if (/\binpage\b/.exec(links[x].className))
				{
				var url = links[x].href;
				var startPos = url.indexOf('#')+1;
				var endPos = (url.indexOf('?') != -1 ? url.indexOf('?')+1 : url.length);
				var target = url.substring(startPos, endPos);
				links[x].onclick = new Function('xhtml.smoothScroll("' + target + '");');
				links[x].href = 'javascript:void(1);';
				}
			}
		}



	/**
	* Adds rollover support to input[type=image] elements
	*/
	this.initInputButtons = function()
		{
		var rolloverCache = [];
		var inputs = document.getElementsByTagName('input');
		for (var x = 0; x < inputs.length; x++)
			{
			// Check if it's an image button with a roll over
			if (inputs[x].type == 'image' && inputs[x].className.indexOf('hasRollover') != -1)
				{
				// 1. Add event handlers to swap the images
				inputs[x].onmouseover = function()
					{
					this.src = this.src.replace(/\.(gif|jpg|png)/, '-over.$1');
					}
				inputs[x].onmouseout = function()
					{
					this.src = this.src.replace(/-over\.(gif|jpg|png)/, '.$1');
					}

				// 2. Pre-cache the rollover image
				var newImage = new Image();
				newImage.src = inputs[x].src.replace(/\.(gif|jpg|png)/i, '-over.$1');
				rolloverCache[rolloverCache.length] = newImage;
				}
			}
		}


	/**
	* Adds expand/collapse event handlers to sidebar menu headings
	*/
	this.initSidebar = function()
		{
		if (document.getElementById('globalContentSidebar') && document.getElementById('globalContentSidebar').className.indexOf('expandable') !== -1)
			{
			var headings = document.getElementById('globalContentSidebar').getElementsByTagName('h3');
			for (var x = 0; x < headings.length; x++)
				{
				headings[x].firstChild.onclick = __eventHandlerToggleMenu;
				}
			}
		}


	/**
	* Scrolls the page to the specified element
	*
	* @param			elementId			The ID of the element to scroll to
	* @param			elementY			The Y position of element (optional, will be calculated if not specified)
	*/
	this.smoothScroll = function(elementId, elementY)
		{
		// If the elements vertical location hasn't been specificed, calculate it
		if (arguments.length != 2)
			{
			// Get it's offset
			obj = document.getElementById(elementId);
			obj.style.display = 'block';	// Make sure it's visible, otherwise we can't get it's location
			elementY = obj.offsetTop;

			// If its parent is relative or absolutely positioned, find it's offset and add it to the total
			while (obj.offsetParent)
				{
				obj = obj.offsetParent;
				elementY += obj.offsetTop;
				}

			// Make the scroll stop just above the target (looks nicer)
			elementY -= 15;
			if (elementY < 0)
				{
				elementY = 0;
				}

			// Check to see we're not trying to scroll off the end of the page
			var contentHeight = document.getElementById('page').offsetHeight;
			var windowHeight = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight));
			if ( (contentHeight - windowHeight) < elementY)
				{
				elementY = (contentHeight - windowHeight);
				}
			}

		// Get the current window scroll position
		var yPos = window.scrollY ? window.scrollY : (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

		// Calculate the pixels remaining to scroll and the scroll step size
		var distanceLeft = Math.abs(yPos - elementY);
		var stepSize = 100;
		if (distanceLeft < 400)
			{
			stepSize = 60;
			}
		if (distanceLeft < 200)
			{
			stepSize = 20;
			}
		if (distanceLeft < 50)
			{
			stepSize = 10;
			}

		// Calculate the scroll
		if (yPos < elementY)
			{
			// Scroll down
			yPos += stepSize;

			// Check if we're scrolled past the target
			if (elementY < yPos)
				{
				yPos = elementY;
				}
			}
		else if (elementY < yPos)
			{
			// Scroll Up
			yPos -= stepSize;

			// Check if we're scrolled past the target
			if (yPos < elementY)
				{
				yPos = elementY;
				}
			}

		// Check for less than zero
		if (yPos < 0)
			{
			yPos = 0;
			}
		if (elementY < 0)
			{
			elementY = 0;
			}

		// Scroll window
		window.scrollTo(0, yPos);

		// If we haven't reached the target, run the another scroll step
		if (yPos != elementY)
			{
			setTimeout("xhtml.smoothScroll('"+elementId+"',"+elementY+");", 10);
			}
		}


	/**
	* Sets the current view in a XHTML document
	*
	* Displays and Hides elements and once complete, can optionally scroll to specified element.
	*
	* @param		toDisplay			An array of element ID's to display
	* @param		toHide				An array of element ID's to hide
	* @param		scrollTo			The element ID to scroll to once the view has been set (optional)
	*/
	this.setView = function(toDisplay, toHide, scrollTo)
		{
		// 1. Check if we've been passed an arrays or a strings for display param
		if (typeof(toDisplay) != 'array' && typeof(toDisplay) != 'object')
			{
			var toDisplay = new Array(typeof(toDisplay) != 'undefined' ? toDisplay : '');
			}

		// 2. Check if we've been passed an arrays or a strings for hide param
		if (typeof(toHide) != 'array' && typeof(toHide) != 'object')
			{
			var toHide = new Array(typeof(toHide) != 'undefined' ? toHide : '');
			}

		// 3. Display elements
		for (var x = 0; x < toDisplay.length; x++)
			{
			if (document.getElementById(toDisplay[x]))
				{
				document.getElementById(toDisplay[x]).style.display = 'block';
				}
			}

		// 4. Hide elements
		for (var x = 0; x < toHide.length; x++)
			{
			if (document.getElementById(toHide[x]))
				{
				document.getElementById(toHide[x]).style.display = 'none';
				}
			}

		// 5. Scroll to specified element, if supplied
		if (arguments.length == 3)
			{
			if (document.getElementById(scrollTo))
				{
				xhtml.smoothScroll(scrollTo);
				}
			}
		}


	/**
	* Initializes the scrolling of branding image
	*/
	this.initBranding = function()
		{

		if (!!document.getElementById('globalBranding') == false)
			{
			return;
			}

		// Make imagebar anchors without a link target, appear as non-clickable
		var anchors = document.getElementById('globalBranding').getElementsByTagName('a');
		for (var x = 0; x < anchors.length; x++)
			{
			if (anchors[x].href == window.location + '#')
				{
				anchors[x].href = 'javascript:;';
				anchors[x].className = 'active';
				}
			}

		// Calculate the number times we need to repeat the images to fill the screen twice
		var images = document.getElementById('globalBranding').getElementsByTagName('span')[0].getElementsByTagName('img');
		var contentWidth = 0;
		for (x = 0; x < images.length; x++)
			{
			contentWidth += parseInt(images[x].offsetWidth);
			}
		var duplicates = Math.ceil(document.getElementById('globalBranding').offsetWidth / contentWidth) * 2;
		if (duplicates < 2)
			{
			// duplicates must be an even number greater than zero
			duplicates = 2;
			}

		// Move the images into the container div
		this.brandingDiv = document.createElement('div');
		var anchors = document.getElementById('globalBranding').getElementsByTagName('span')[0].getElementsByTagName('a');
		for (var x = 0; x < duplicates; x++)
			{
			for (var y = 0; y < anchors.length; y++)
				{
				// Copy the anchor wrapped image in to the branding div
				this.brandingDiv.appendChild( anchors[y].cloneNode(true) );
				}
			}

		// Add the container div to the document
		document.getElementById('globalBranding').appendChild( this.brandingDiv );

		// Add event handlers to container div
		this.brandingDiv.onmouseover = __eventHandlerBrandingOver;
		this.brandingDiv.onmouseout = __eventHandlerBrandingOut;

		// Store the image width, and current set (the 3 digit suffix before the file extension)
		this.brandingWidth = contentWidth * duplicates / 2;
		this.brandingSet = document.getElementById('globalBranding').getElementsByTagName('span')[0].className;

		// Enable the change image links
		var links = document.getElementById('globalHeaderBrandingLinks').getElementsByTagName('a');
		for (var x = 0; x < links.length; x++)
			{
			links[x].onclick = __eventHandlerBrandingChange;
			}

		// Start the animation
		this.brandingTimer = setInterval("xhtml.scrollBranding();", 50);
		}


	/**
	* Scrolls the branding image
	*/
	this.scrollBranding = function()
		{
		// Check if the scrolling has been paused, due to mouse over the image
		if (xhtml.brandingPaused === true)
			{
			return;
			}

		// Calculate the new scroll position
		xhtml.brandingPos+=1;
		if (xhtml.brandingWidth < xhtml.brandingPos)
			{
			xhtml.brandingPos = 0;
			}

		// Scroll the image
		xhtml.brandingDiv.style.left = (xhtml.brandingPos*-1) + 'px';
		}


	/**
	* Changes the current branding image
	*
	* @param			newSet			The three digit suffix for the new set, e.g. '002'
	*/
	this.changeBranding = function(newSet)
		{
		// Pause the scroll
		xhtml.brandingPaused = true;

		// Calculate the number times we need to repeat the images to fill the screen twice
		var images = document.getElementById('imagebar' + newSet).getElementsByTagName('img');
		var contentWidth = 0;
		for (x = 0; x < images.length; x++)
			{
			contentWidth += parseInt(images[x].offsetWidth);
			}
		var duplicates = Math.ceil(document.getElementById('globalBranding').offsetWidth / contentWidth) * 2;
		if (duplicates < 2)
			{
			// duplicates must be an even number greater than zero
			duplicates = 2;
			}

		// Move the images into the container div
		xhtml.brandingDiv = document.createElement('div');
		var anchors = document.getElementById('imagebar' + newSet).getElementsByTagName('a');
		for (var x = 0; x < duplicates; x++)
			{
			for (var y = 0; y < anchors.length; y++)
				{
				// Copy the anchor wrapped image in to the branding div
				xhtml.brandingDiv.appendChild( anchors[y].cloneNode(true) );
				}
			}

		// Replace the existing container div
		document.getElementById('globalBranding').replaceChild( xhtml.brandingDiv, document.getElementById('globalBranding').getElementsByTagName('div')[0] );

		// Add event handlers to container div
		xhtml.brandingDiv.onmouseover = __eventHandlerBrandingOver;
		xhtml.brandingDiv.onmouseout = __eventHandlerBrandingOut;

		// Store the image width, and current set
		xhtml.brandingWidth = contentWidth * duplicates / 2;
		xhtml.brandingSet = newSet;

		// Resume the scroll
		xhtml.brandingPaused = false;
		}



	// Step 3. Define Private Methods

	/**
	* Finds the parent of the element with a node type of parentTagName
	*
	* @param		element					The element object to find the parent of
	* @param		parentTagName		The type of parent element to find
	*
	* @return		The element's parent object of the specified type, or null if no parent of that type could be found
	*/
	function findParent(element, parentTagName)
		{
		if (element == null)
			{
			return null;
			}
		else
			{
			if ( element.nodeType == 1 && element.tagName.toLowerCase() == parentTagName.toLowerCase() )
				{
				return element;
				}
			else
				{
				return findParent(element.parentNode, parentTagName);
				}
			}
		}


	/**
	* Event Handler: Mouse over branding image
	*/
	function __eventHandlerBrandingOver()
		{
		xhtml.brandingPaused = true;
		}


	/**
	* Event Handler: Mouse out of branding image
	*/
	function __eventHandlerBrandingOut()
		{
		xhtml.brandingPaused = false;
		}


	/**
	* Event Handler: Click on change branding image link
	*/
	function __eventHandlerBrandingChange()
		{
		// Set links as inactive
		var links = document.getElementById('globalHeaderBrandingLinks').getElementsByTagName('a');
		for (var x = 0; x < links.length; x++)
			{
			links[x].className = 'inactive';
			}

		// Set new link active
		this.className = 'active';

		// Change the image
		xhtml.changeBranding(this.id.replace('branding', ''));
		}


	/**
	* Event Handler: Toggles the submenu visible/hidden
	*/
	function __eventHandlerToggleMenu()
		{
		var uls = this.parentNode.parentNode.getElementsByTagName('ul');
		if (uls.length)
			{
			uls[0].className = (uls[0].className == 'hidden' ? '' : 'hidden');
			}
		}
	}



/**
* Inherts a prototype from the specified class, updates the constructor reference
*
* @param		parent		The parent class or object
* @return		The inherted object
*/
Function.prototype.inheritsFrom = function( baseClass )
	{
	// Inherit the base class
	this.prototype = new baseClass;
	this.prototype.constructor = this;

	// Add access to the base's methods
	this.prototype.base = {};
	for (method in this.prototype)
		{
		// hasOwnProperty test is a workaround for "for..in" bug, see: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
		if (typeof this.prototype[method] === 'function' && this.prototype.hasOwnProperty(method) && this.prototype[method] !== this.prototype.constructor)
			{
			this.prototype.base[method] = this.prototype[method];
			}
		}
	return this;
	}