/**
* Global JavaScript Definitions
*
* @author				Matt Gifford
* @copyright			2009 Timeshifting Interactive Limited
* @version			1.7
*/

var viewHandler = WebPage;

// Include dependencies
dojo.require("dijit.dijit");
dojo.require("dijit.Tooltip");

// Queue on load handler
dojo.addOnLoad( 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();
		}
	);



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

	var _instance = this;
	this.log = function(msg) { if (typeof(console) != 'undefined') { console.log(msg); } };



	// Step 2. Define Public Methods

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


	/**
	* 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. Set the active class on links to the current page
			if ((links[x].href == window.location.href || links[x].href == window.location.href + '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
	*/
	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;
				}
			}
		}


	/**
	* Displays the share this dialog
	*
	* @param		obj		The title and url to use (optional) ex. {title: "string", url: "string"}
	*/
	this.shareOpen = function(obj)
		{
		if (!!document.getElementById('share') == false)
			{
			xhtml.shareBuildHtml();
			}

		// Set the default title and url
		this.shareUrl = window.location.href.replace(window.location.hash, '');
		this.shareTitle = document.title;

		// Save the url and title
		if (arguments.length)
			{
			this.shareUrl = obj.url;
			this.shareTitle = obj.title;
			}

		// Display the share dialog
		this.shareUpdateOverlay();
		document.getElementById('share').className = '';
		document.getElementById('shareBackground').className = '';
		document.getElementById('shareDialog').className = '';

		// Center the dialog
		this.centerDiv( document.getElementById('shareDialog') );
		}


	/**
	* Closes the share dialog
	*/
	this.shareClose = function()
		{
		// Reset the email form
		document.getElementById('formShareEmail').getElementsByTagName('label')[0].className = 'hidden';
		document.getElementById('formShareEmail').getElementsByTagName('label')[1].className = 'hidden';
		document.getElementById('formShareEmail').getElementsByTagName('input')[0].value = '';
		document.getElementById('formShareEmail').getElementsByTagName('fieldset')[0].className = 'hidden';
		document.getElementById('formShareEmail').getElementsByTagName('fieldset')[1].className = '';

		// Hide the share
		document.getElementById('share').className = 'invisible';
		document.getElementById('shareBackground').className = 'invisible';
		document.getElementById('shareDialog').className = 'invisible';
		}


	/**
	* Shares the current page on facebook
	*/
	this.shareFacebook = function()
		{
		if (confirm('Would you like to post this item to your Facebook?') == true)
			{
			var url = 'http://www.facebook.com/sharer.php?u=%url%&t=%title%';
			url = url.replace('%url%', this.shareUrl).replace(/[\u0080-\uFFFF]+/g, '');
			url = url.replace('%title%', encodeURIComponent(this.shareTitle.replace(/<([^>]+)>/ig, '').replace(/[\u0080-\uFFFF]+/g, '')).replace('%20', '+', 'g').replace('%2520', '+', 'g') );

			// Throw the url
			window.open(url, '_blank');
			}
		}


	/**
	* Shares the current page via social networking
	*
	* @param		network		The social media network
	*/
	this.shareSocial = function(network)
		{
		// Select the correct url to throw
		switch (network)
			{
			case 'bebo':
				var url = 'http://www.bebo.com/c/share?Url=%url%&t=%title%';
				break;

			case 'delicious':
				var url = 'http://del.icio.us/post?url=%url%&title=%title%';
				break;

			case 'digg':
				var url = 'http://digg.com/submit?phase=2&url=%url%&title=%title%&bodytext=%desc%';
				break;

			case 'facebook':
				var url = 'http://www.facebook.com/sharer.php?u=%url%&t=%title%';
				break;

			case 'google':
				var url = 'http://www.google.com/bookmarks/mark?op=edit&bkmk=%url%&title=%title%';
				break;

			case 'myspace':
				var url = 'http://www.myspace.com/Modules/PostTo/Pages/?u=%url%&t=%title%';
				break;

			case 'technorati':
				var url = 'http://www.technorati.com/faves?add=%url%';
				break;

			case 'windowslive':
				var url = 'https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=%url%&title=%title%&top=1';
				break;

			case 'yahoomyweb':
				var url = 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=%url%&t=%title%';
				break;

			default:
				this.shareClose();
				return;
			}

		// Configure the url
		url = url.replace('%url%', this.shareUrl).replace(/[\u0080-\uFFFF]+/g, '');
		url = url.replace('%title%', encodeURIComponent(this.shareTitle.replace(/<([^>]+)>/ig, '').replace(/[\u0080-\uFFFF]+/g, '')).replace('%20', '+', 'g').replace('%2520', '+', 'g') );
		url = url.replace('%desc%', '');

		// Throw the url
		window.open(url, '_blank');

		// Close the share box
		this.shareClose();
		}


	/**
	* Shares the current page via email
	*/
	this.shareEmail = function()
		{
		// Check for blank input
		var obj = document.getElementById('formShareEmail');
		var inputs = obj.getElementsByTagName('input');
		for (var x = 0; x < 3; x++)
			{
			if (inputs[x].value == '')
				{
				obj.getElementsByTagName('fieldset')[0].className = '';
				obj.getElementsByTagName('label')[0].className = 'missing';
				return;
				}
			}

		// Check for valid email addresses
		var regex = /^[a-z0-9_+-.]+@[a-z0-9_-]*\.?[a-z0-9_-]*\.?[a-z0-9_-]*\.[a-z]+$/i;
		if (regex.test(inputs[0].value) == false || regex.test(inputs[2].value) == false)
			{
			obj.getElementsByTagName('fieldset')[0].className = '';
			obj.getElementsByTagName('label')[0].className = 'missing';
			return;
			}

		// Inject the page details
		document.getElementById('formShareEmailUrl').value = this.shareUrl;
		document.getElementById('formShareEmailTitle').value = this.shareTitle;

		// Send the request
//		YAHOO.util.Connect.setForm('');
//		YAHOO.util.Connect.asyncRequest("POST", "", { success: function() {  }, failure: function() {  } } );

		// post some data, ignore the response:
		dojo.xhrPost({
			url: '/news/share/',
			form: "formShareEmail",
			handleAs: "text",
			load: function(data)
				{
				xhtml.shareEmailSent();
				},
			error: function(error)
				{
				alert('There was a problem sending your message, please try again.');
				}
			});

		// Update the share box
		obj.getElementsByTagName('fieldset')[0].className = '';
		obj.getElementsByTagName('label')[0].className = 'hidden';
		obj.getElementsByTagName('label')[1].className = 'sending';
		}


	/**
	* Displays the message send message, and closes the share dialog
	*/
	this.shareEmailSent = function()
		{
		// Update the share box message
		document.getElementById('formShareEmail').getElementsByTagName('fieldset')[0].className = '';
		document.getElementById('formShareEmail').getElementsByTagName('label')[0].className = 'hidden';
		document.getElementById('formShareEmail').getElementsByTagName('label')[1].className = 'sending';
		document.getElementById('formShareEmail').getElementsByTagName('label')[1].innerHTML = '<b>Message Sent!</b>';
		document.getElementById('formShareEmail').getElementsByTagName('fieldset')[1].className = 'hidden';

		// Close the share box
		setTimeout("xhtml.shareClose();", 1750);
		}


	/**
	* Updates the display of the background overlay
	*/
	this.shareUpdateOverlay = function()
		{
		if (!!document.getElementById('share') == false)
			{
			xhtml.shareBuildHtml();
			}

		var overlay = document.getElementById('shareBackground');
		overlay.style.position = 'absolute';
		overlay.style.left = '0px';
		overlay.style.top = '0px';
		overlay.style.background = '#000';
		overlay.style.opacity = 0.6;
		overlay.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=60)';
		overlay.style.width = document.body.offsetWidth + 'px';

		var height = (document.getElementById('page').offsetHeight < document.documentElement.clientHeight ? document.documentElement.clientHeight : document.getElementById('page').offsetHeight);
		var shareDialogHeight = 280;
		height = ((shareDialogHeight + 40) < height ? height : (shareDialogHeight + 40));
		overlay.style.height = height + 'px';
		overlay.className = '';
		}


this.shareBuildHtml = function()
	{
	var share = document.createElement('div');
	share.id = 'share';
	share.className = 'invisible';

	// Build the html
	var shareHTML = [];
	shareHTML.push('<div id="shareBackground" onclick="xhtml.shareClose();" class="invisible"></div>');
	shareHTML.push('<div id="shareDialog" class="invisible">');
	shareHTML.push('<div id="shareDialogSocial" class="social">');
	shareHTML.push('<h3>Share via social networking</h3>');
	shareHTML.push('<ul class="list1">');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'facebook\');" href="javascript:;" class="facebook">Facebook</a></li>');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'bebo\');" href="javascript:;" class="bebo">Bebo</a></li>');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'delicious\');" href="javascript:;" class="delicious">Delicious</a></li>');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'digg\');" href="javascript:;" class="digg">Digg</a></li>');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'google\');" href="javascript:;" class="google">Google Bookmarks</a></li>');
	shareHTML.push('</ul>');
	shareHTML.push('<ul class="list2">');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'myspace\');" href="javascript:;" class="myspace">MySpace</a></li>');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'technorati\');" href="javascript:;" class="technorati">Technorati</a></li>');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'windowslive\');" href="javascript:;" class="windowslive">Windows Live</a></li>');
	shareHTML.push('<li><a onclick="xhtml.shareSocial(\'yahoomyweb\');" href="javascript:;" class="yahoomyweb">Yahoo! My Web</a></li>');
	shareHTML.push('</ul>');
	shareHTML.push('</div>');
	shareHTML.push('<div class="email">');
	shareHTML.push('<h3>Email to a Friend</h3>');
	shareHTML.push('<form id="formShareEmail" onsubmit="return false" method="post" action="">');
	shareHTML.push('<fieldset>');
	shareHTML.push('<label class="hidden"><b>Missing Information</b><br/>Please complete the name &amp; email addresses fields and ensure the email addresses are valid.</label>');
	shareHTML.push('<label class="hidden"><b>Sending Message</b><br/>Please wait...</label>');
	shareHTML.push('</fieldset>');
	shareHTML.push('<fieldset>');
	shareHTML.push('<label>Friend\'s Email</label>');
	shareHTML.push('<input type="text" value="" name="toAddress" class="text"/>');
	shareHTML.push('<label>Your Name</label>');
	shareHTML.push('<input type="text" value="" name="fromName" class="text"/>');
	shareHTML.push('<label>Your Email</label>');
	shareHTML.push('<input type="text" value="" name="fromAddress" class="text"/>');
	shareHTML.push('<label>Message</label>');
	shareHTML.push('<textarea name="message"></textarea>');
	shareHTML.push('<input id="formShareEmailUrl" type="hidden" name="url" value=""/>');
	shareHTML.push('<input id="formShareEmailTitle" type="hidden" name="title" value=""/>');
	shareHTML.push('<input type="button" name="submit" value="Send Message" onclick="xhtml.shareEmail();"/>');
	shareHTML.push('</fieldset>');
	shareHTML.push('</form>');
	shareHTML.push('</div>');
	shareHTML.push('<br class="clear"/>');
	shareHTML.push('<a class="close" href="javascript:;" onclick="xhtml.shareClose();"></a>');
	shareHTML.push('</div>');

	// Inject the html
	share.innerHTML = shareHTML.join('\n');

	// Add node to document
	document.body.appendChild(share);
	}


	/**
	* Centers the div object on the page
	*
	* @param		obj					The node to center on the page
	*/
	this.centerDiv = function(obj)
		{
		// Get the window size and scroll position
		if (!!(window.attachEvent && !window.opera)) // IE
			{
			// 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;
			}
		else
			{
			// Calculate the current scroll position
			var scrollPositionY = window.scrollY;

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

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