/**
* Global JavaScript Definitions
*
* @author				Matt Gifford
* @copyright			2008 Timeshifting Interactive Limited
* @version			1.5.9
*/

var viewHandler = WebPage;
var onLoadTasks = [];
var onUnloadTasks = [];


// Execute on load handler
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();
		}

	// Main page initialization
	xhtml.init();

	// Execute secondary on load tasks
	for (var x = 0; x < onLoadTasks.length; x++)
		{
		onLoadTasks[x]();
		}
	}


// Execute on unload handler
window.onunload = function()
	{
	// Execute on unload tasks
	for (var x = 0; x < onUnloadTasks.length; x++)
		{
		onUnloadTasks[x]();
		}
	}



/**
* Creates a new WebPage object with methods used by all pages, can be extended to add page specific methods.
*
* @author				Matt Gifford
* @copyright			2008 Timeshifting Interactive Limited
*/
function WebPage()
	{
	// Step 1. Define Properties

	var _instance = this;
	this.initialized = false;
	this.debug = false;
	this.emptyFunction = function() {};



	// Step 2. Define Public Methods

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

		// Inital Trident Rollovers
		if (!!(window.attachEvent && !window.opera))
			{
			if (document.getElementById('globalContentHeader'))
				{
				var lis = document.getElementById('globalContentHeader').getElementsByTagName('li');
				for (var x = 0; x < lis.length; x++)
					{
					lis[x].onmouseover = __eventHandlerAddHover;
					lis[x].onmouseout = __eventHandlerRemoveHover;
					}
				}
			}

		// 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.length;
				var target = url.substring(startPos, endPos);
				links[x].onclick = new Function('xhtml.smoothScroll("' + target + '");');
				links[x].href = 'javascript:void(1);';
				}
/*
			// 3. Set the active class on links to the current page
			if (links[x].href == window.location.toString())
				{
				if (links[x].className.indexOf('active') == -1)
					{
					links[x].className += ' active';
					}
				}
*/
			}
		}


	/**
	* 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;
				}
			}
		}


	/**
	* 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);
			}
		}


	/**
	* 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
	*/
	this.findParent = function(element, parentTagName)
		{
		if (element == null)
			{
			return null;
			}
		else
			{
			if ( element.nodeType == 1 && element.tagName.toLowerCase() == parentTagName.toLowerCase() )
				{
				return element;
				}
			else
				{
				return this.findParent(element.parentNode, parentTagName);
				}
			}
		}
	


	/**
	* Event Handler: Adds hover class
	*/
	function __eventHandlerAddHover()
		{
		this.className += ' hover';
		}
	

	/**
	* Event Handler: Removes hover class
	*/
	function __eventHandlerRemoveHover()
		{
		this.className = this.className.replace(/\s?hover/g, '');
		}
	}



/**
* 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;
	}
	
/* email function */
function sendMail(domain, account, subject, cc) {
	var add = "";
	if (cc)
		add = "&cc=" + cc + domain;

        var a = "mailto:" + account + domain + "?" + "subject=" + subject + add;
        location.href = a;
}

function validateForm(){
	var valid = true;
	var nameError = "", emailError = "", questionError = "";

	if( document.getElementById("name").value.length == 0 ){
		nameError = "Please enter your name.";
		valid = false;
	}
	if( !validateEmail(document.getElementById("email").value)){
		emailError = "Please enter a valid email address.";
		valid = false;
	}
	if( document.getElementById("question").value.length == 0 ){
		questionError = "Please enter a question before sending the email.";
		valid = false;
	}

	document.getElementById("nameError").innerHTML = nameError;
	document.getElementById("emailError").innerHTML = emailError;
	document.getElementById("questionError").innerHTML = questionError;

	if( valid )
		document.getElementById("emailForm").submit();
}

function validateEmail(email) {
	var reg = /^([A-Za-z0-9_\-\.\’])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(email)
}
