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

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() {};
	this.log = function(msg) { if (typeof(console) != 'undefined') { console.log(msg); } };

	this.timeoutTrident6Menus = null;



	// Step 2. Define Public Methods

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

		// Internet Explorer 6 Fixes
		if (xhtml.isTrident6 == true)
			{
			// Add menu event handlers for internet explorer 6
			this.initMenusTrident6();

			// Help stop css background image flicker
			try
				{
				document.execCommand("BackgroundImageCache", false, true);
				}
			catch(err) {}
			}

		// Add rollovers to footer images
		this.footerImageCache = [];
		var imgs = document.getElementById('globalFooter').getElementsByTagName('img');
		for (var x = 0; x < imgs.length; x++)
			{
			this.footerImageCache[x] = new Image();
			this.footerImageCache[x].src = imgs[x].src.replace('.png', '-over.png');
			imgs[x].onmouseover = function()
				{
				this.src = this.src.replace('.png', '-over.png');
				}
			imgs[x].onmouseout = function()
				{
				this.src = this.src.replace('-over.png', '.png');
				}
			}
	
		// Set class as initialized
		this.initialized = true;
		}


	/**
	* Sets up user agent booleans
	*/
	this.initUserAgentBooleans = function()
		{
		var ua = navigator.userAgent.toLowerCase();
		var vendor = !!navigator.vendor ? navigator.vendor.toLowerCase() : '';
		var regexTrident = /msie (\d+\.\d+)/i;
		var regexFirefox = /firefox\/(\d+\.\d+)/i;
		var regexSafari = /version\/(\d+\.\d+)/i;
		var regexChrome = /chrome\/(\d+\.\d+)/i;

		// Define properties
		this.renderingEngine = '';
		this.isTrident = 0;
		this.isFirefox = 0;
		this.isSafari = 0;
		this.isChrome = 0;
		this.isMobile = ua.indexOf('mobile') != -1 ? true : false;
		this.isDownloadableFonts = false;

		this.isTrident6 = false;
		this.isTrident7 = false;
		this.isTrident8 = false;
		this.isFirefox2 = false;
		this.isFirefox3 = false;
		this.isSafari2 = false;
		this.isSafari3 = false;

		// 1. Detect the Rendering engine
		// Gecko
		if (ua.indexOf('gecko') != -1 || vendor.indexOf('camino') != -1)
			{
			this.renderingEngine = 'gecko';
			}
		// WebKit
		if (ua.indexOf('webkit') != -1 || vendor.indexOf('apple') != -1 || vendor.indexOf('google') != -1 || vendor.indexOf('icab') != -1 || vendor.indexOf('kde') != -1)
			{
			this.renderingEngine = 'webkit';
			}
		// Presto
		if (!!window.opera)
			{
			this.renderingEngine = 'presto';
			}
		// Trident
		if (!!(window.attachEvent && !window.opera))
			{
			this.renderingEngine = 'trident';
			}

		// 2. Detect browser version
		var matches = [];
		switch (this.renderingEngine)
			{
			case 'trident':
				matches = ua.match(regexTrident);
				if (matches && 1 < matches.length)
					{
					this.isTrident = parseFloat(matches[1]);
					}
				this.isTrident6 = (this.isTrident == 6);
				this.isTrident7 = (this.isTrident == 7);
				this.isTrident8 = (this.isTrident == 8);
				break;

			case 'gecko':
				matches = ua.match(regexFirefox);
				if (matches && 1 < matches.length)
					{
					this.isFirefox = parseFloat(matches[1]);
					}
				this.isFirefox2 = (this.isFirefox == 2);
				this.isFirefox3 = (this.isFirefox == 3);
				break;

			case 'webkit':
				// Safari
				matches = ua.match(regexSafari);
				if (matches && 1 < matches.length && vendor.indexOf('apple') != -1)
					{
					this.isSafari = parseFloat(matches[1]);
					}
				this.isSafari2 = (this.isSafari == 2);
				this.isSafari3 = (this.isSafari == 3);
				// Chrome
				matches = ua.match(regexChrome);
				if (matches && 1 < matches.length && vendor.indexOf('google') != -1)
					{
					this.isChrome = parseFloat(matches[1]);
					}
				break;
			}

		// 3. Set font downloading support
		this.isDownloadableFonts = (this.isTrident || 3.1 <= this.isFirefox || 3.1 <= this.isSafari);
		}


	/**
	* 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() || links[x].href == window.location.toString() + 'index.html') && links[x].href.indexOf('#') == -1)
				{
				if (links[x].className.indexOf('active') == -1)
					{
					links[x].className += ' active';
					}
				}
			}
		}



	/**
	* Adds rollover support to input[type=image] elements and background swapping for text fields
	*/
	this.initInputs = function()
		{
		// 1. Button rollovers
		var rolloverCache = [];
		var inputs = YAHOO.util.Dom.getElementsByClassName('hasRollover', 'input');
		for (var x = 0; x < inputs.length; x++)
			{
			// 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');
				}

			// Pre-cache the rollover image
			this._precacheImages( [inputs[x].src.replace(/\.(gif|jpg|png)/i, '-over.$1')] );
			}

		// 2. Input background swapping
		var inputs = YAHOO.util.Dom.getElementsByClassName('hasBackground', 'input');
		for (var x = 0; x < inputs.length; x++)
			{
			// Remove the hasBackground class
			inputs[x].className = inputs[x].className.replace(' hasBackground', '');

			// Check initial content
			if (inputs[x].value != '')
				{
				var parts = inputs[x].className.split(' ');
				inputs[x].className = parts[0] + ' ' + parts[0] + 'Active';
				}

			// Add event handlers to swap the backgrounds
			inputs[x].onfocus = function()
				{
				var parts = this.className.split(' ');
				this.className = parts[0] + ' ' + parts[0] + 'Active';
				}
			inputs[x].onblur = function()
				{
				var parts = this.className.split(' ');
				if (this.value != '')
					{
					this.className = parts[0] + ' ' + parts[0] + 'Active';
					}
				else
					{
					this.className = parts[0];
					}
				}
			}
		}


	/**
	* Adds event handlers to the global nav menus for Internet Explorer 6
	*/
	this.initMenusTrident6 = function()
		{
		var headings = ['globalHeaderNavFurniture', 'globalHeaderNavShowrooms', 'globalHeaderNavCompany'];
		for (var x = 0; x < headings.length; x++)
			{
			if (!!document.getElementById(headings[x] + 'Menu') == true)
				{
				document.getElementById(headings[x]).onmouseover = function()
					{
					try
						{
						clearTimeout(xhtml.timeoutTrident6Menus);
						if (!!document.getElementById('globalHeaderNavFurniture') == true)
							{
							document.getElementById('globalHeaderNavFurniture').className = document.getElementById('globalHeaderNavFurniture').className.replace(/\s?hover/g, '');
							}
						if (!!document.getElementById('globalHeaderNavShowrooms') == true)
							{
							document.getElementById('globalHeaderNavShowrooms').className = document.getElementById('globalHeaderNavShowrooms').className.replace(/\s?hover/g, '');
							}
						if (!!document.getElementById('globalHeaderNavCompany') == true)
							{
							document.getElementById('globalHeaderNavCompany').className = document.getElementById('globalHeaderNavCompany').className.replace(/\s?hover/g, '');
							}
						this.className += ' hover';
						}
					catch (err)
						{
						}
					}
				document.getElementById(headings[x]).onmouseout = function()
					{
					try
						{
						xhtml.timeoutTrident6Menus = setTimeout("document.getElementById('" + this.id + "').className = document.getElementById('" + this.id + "').className.replace(/\s?hover/g, '');", 250);
						}
					catch (err)
						{
						}
					}
				document.getElementById(headings[x] + 'Menu').onmouseover = function()
					{
					clearTimeout(xhtml.timeoutTrident6Menus);
					}
				document.getElementById(headings[x] + 'Menu').onmouseout = function()
					{
					try
						{
						xhtml.timeoutTrident6Menus = setTimeout("document.getElementById('" + this.id + "').className = document.getElementById('" + this.id + "').className.replace(/\s?hover/g, '');", 250);
						}
					catch (err)
						{
						}
					}
				}
			}
		}


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


	/**
	* Centers the div object on the page
	*
	* @param		obj					The node to center on the page
	* @param		fixed					Whether the node is fixed position
	*/
	this._centerDiv = function(obj, fixed)
		{
		var fixed = !!fixed ? fixed : false;

		// Get the window size and scroll position
		switch (xhtml.renderingEngine)
			{
			case 'trident':
				// Calculate the current scroll position
				var scrollPositionY = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;

				// Find the window width and height
				var windowWidth = document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
				var windowHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
				break;

			default:
				// Calculate the current scroll position
				var scrollPositionY = window.scrollY;

				// Find the window width and height
				var windowWidth = window.innerWidth;
				var windowHeight = window.innerHeight;
				break;
			}

		var width = 0;
		var height = 0;

		// Get the current size
		try
			{
			var width = obj.offsetWidth;
			var height = obj.offsetHeight;
			}
		catch (err)
			{
			return;
			}

		// Calculate the position
		var left = Math.floor((windowWidth / 2) - (width / 2));
		if (fixed == true)
			{
			// Fixed position, ignore the scroll position
			var top = Math.floor(((windowHeight / 2) - (height / 2)));
			}
		else
			{
			// Absolute position, take into account the current scroll position
			var top = Math.floor(((windowHeight / 2) - (height / 2)) + scrollPositionY);
			}

		// Range check the values
		if (left < 10)
			{
			left = 10;
			}
		if (top < 10)
			{
			top = 10;
			}

		// Position the div
		obj.style.left = left + 'px';
		obj.style.top = top + 'px';
		}
	}



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