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

var viewHandler = WebPage;
var onloadHandler = 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();
	}

// Queue onload handler
if (typeof(dojo) != 'undefined') dojo.addOnLoad(onloadHandler);
else if (typeof(YAHOO) != 'undefined') YAHOO.util.Event.onDOMReady(onloadHandler);
else if (typeof(window.jQuery) != 'undefined') $(document).ready(onloadHandler);
else window.onload = onloadHandler;



/**
* 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.initialized = false;
	this.debug = false;
	this.emptyFunction = function() {};
	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();

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

	/**
	* Shares the current page on the specified network
	*
	* @param		network		The network to share on (optional, displays full share dialog if omitted)
	*/
	this.share = function(network)
		{
		// Update the share params
		this.shareUpdate();

		// Select the correct url to throw
		switch (network)
			{
			case 'Facebook':
				var url = 'http://www.facebook.com/sharer.php?u=%url%&t=%title%';
				break;

			case 'Twitter':
				var url = 'http://twitter.com/home?status=Currently+reading+%url%';
				break;

			case 'Digg':
				var url = 'http://digg.com/submit?url=%url%&title=%title%';
				break;

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

			default:
				// No network specified, so display share box
				xhtml.shareDialog();
				return;
			}

		// Confirm, add the content and throw
		if (confirm('Would you like to post this item to your ' + network + ' account?') == true)
			{
			url = url.replace('%url%', encodeURIComponent(document.getElementById('shareURL').getAttribute('content')));
			url = url.replace('%title%', encodeURIComponent(document.getElementById('shareTitle').getAttribute('content')));

			// Throw the url
			if (network == 'Facebook')
				{
				window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
				}
			else
				{
				window.open(url, '_blank');
				}
			return false;
			}
		}


	/**
	* Updates the share this meta tags from the anchor clicked on
	*
	* @param		obj		The anchor clicked on
	*/
	this.shareUpdate = function(obj)
		{
		if (arguments.length && obj && obj.getAttribute('rel') != '')
			{
			// Update with the supplied values
			document.getElementById('shareURL').setAttribute('content', obj.getAttribute('rel'));
			document.getElementById('shareTitle').setAttribute('content', obj.getAttribute('title'));
			}
		else
			{
			document.getElementById('shareURL').setAttribute('content', window.location.href);
			document.getElementById('shareTitle').setAttribute('content', document.title);
			}
		}


	/**
	* Displays the share this dialog (social networking or email)
	*/
	this.shareDialog = function(obj)
		{
		// Update the share params, if new ones were supplied
		if (arguments.length)
			{
			xhtml.shareUpdate(obj);
			}

		// Kill any existing share dialog
		if (!!document.getElementById('share') == true)
			{
			document.body.removeChild( document.getElementById('share') );
			}

		// Build the dialog html
		var html = [];
		html.push('<div id="shareBackground" onclick="document.body.removeChild(document.getElementById(\'share\'));"></div>');
		html.push('<div id="shareDialog">');
		html.push('<div id="shareDialogSocial" class="social">');
		html.push('<h3>Share via Social Networking</h3>');
		html.push('<ul class="list1">');
		html.push('<li><a onclick="xhtml.shareSocial(\'facebook\');" href="javascript:;" class="facebook">Facebook</a></li>');
		html.push('<li><a onclick="xhtml.shareSocial(\'bebo\');" href="javascript:;" class="bebo">Bebo</a></li>');
		html.push('<li><a onclick="xhtml.shareSocial(\'delicious\');" href="javascript:;" class="delicious">Delicious</a></li>');
		html.push('<li><a onclick="xhtml.shareSocial(\'digg\');" href="javascript:;" class="digg">Digg</a></li>');
		html.push('<li><a onclick="xhtml.shareSocial(\'google\');" href="javascript:;" class="google">Google Bookmarks</a></li>');
		html.push('</ul>');
		html.push('<ul class="list2">');
		html.push('<li><a onclick="xhtml.shareSocial(\'myspace\');" href="javascript:;" class="myspace">MySpace</a></li>');
		html.push('<li><a onclick="xhtml.shareSocial(\'technorati\');" href="javascript:;" class="technorati">Technorati</a></li>');
		html.push('<li><a onclick="xhtml.shareSocial(\'windowslive\');" href="javascript:;" class="windowslive">Windows Live</a></li>');
		html.push('<li><a onclick="xhtml.shareSocial(\'yahoomyweb\');" href="javascript:;" class="yahoomyweb">Yahoo! My Web</a></li>');
		html.push('</ul>');
		html.push('</div>');
		html.push('<div class="email">');
		html.push('<h3>Email to a Friend</h3>');
		html.push('<form id="formShareEmail" onsubmit="return false" method="post" action="#">');
		html.push('<fieldset>');
		html.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>');
		html.push('<label class="hidden"><b>Sending Message</b><br/>Please wait...</label>');
		html.push('</fieldset>');
		html.push('<fieldset>');
		html.push('<label>Friend\'s Email</label>');
		html.push('<input type="text" value="" name="toAddress" class="text"/>');
		html.push('<label>Your Name</label>');
		html.push('<input type="text" value="" name="fromName" class="text"/>');
		html.push('<label>Your Email</label>');
		html.push('<input type="text" value="" name="fromAddress" class="text"/>');
		html.push('<label>Message</label>');
		html.push('<textarea name="message"></textarea>');
		html.push('<input id="formShareEmailUrl" type="hidden" name="url" value=""/>');
		html.push('<input id="formShareEmailTitle" type="hidden" name="title" value=""/>');
//		html.push('<label>Verfication Code</label>');
//		html.push('<input type="text" value="" name="captcha" class="text"/>');
//		html.push('<div class="captcha"><img src="images/FPO-captcha.png" width="182" height="60" alt=""/><a href="#">Can\'t read the verfication code?</a></div>');
		html.push('<a class="send" href="javascript:;" onclick="xhtml.shareEmail();">Send Message</a>');
		html.push('</fieldset>');
		html.push('</form>');
		html.push('</div>');
		html.push('<br class="clear"/>');
		html.push('<a class="close" href="javascript:;" onclick="document.body.removeChild(document.getElementById(\'share\'));"></a>');
		html.push('</div>');

		// Create the dialog
		var share = document.createElement('div');
		share.id = 'share';
		share.innerHTML = html.join('\n');
		document.body.appendChild( share );
		}


	/**
	* Displays the share this embed video dialog
	*/
	this.shareEmbed = function()
		{
		// Kill any existing share dialog
		if (!!document.getElementById('share') == true)
			{
			document.body.removeChild( document.getElementById('share') );
			}

		// Build embed code
		var flashHtml = '<object width="580" height="326"><param name="movie" value="' + document.getElementById('shareFlash').getAttribute('href') + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + document.getElementById('shareFlash').getAttribute('href') + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="580" height="326"></embed></object>';

		// Build the dialog html
		var html = [];
		html.push('<div id="shareBackground" onclick="document.body.removeChild(document.getElementById(\'share\'));"></div>');
		html.push('<div id="shareDialog">');
		html.push('<div class="embed">');
		html.push('<h3>Embed this Video</h3>');
		html.push('<p>Add this video to your blog or webpage, copy and paste the code in the box below:</p>');
		html.push('<form method="post" action="#">');
		html.push('<fieldset>');
		html.push('<textarea name="code" onfocus="this.select();">' + flashHtml + '</textarea>');
		html.push('</fieldset>');
		html.push('</form>');
		html.push('</div>');
		html.push('<br class="clear"/>');
		html.push('<a class="close" href="javascript:;" onclick="document.body.removeChild(document.getElementById(\'share\'));"></a>');
		html.push('</div>');

		// Create the dialog
		var share = document.createElement('div');
		share.id = 'share';
		share.innerHTML = html.join('\n');
		document.body.appendChild( share );
		}


	/**
	* 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?url=%url%&title=%title%';
				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 'stumbleupon':
				var url = 'http://www.stumbleupon.com/submit?url=%url%&title=%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:
				document.body.removeChild(document.getElementById('share'));
				return;
			}

		// Configure the url
		url = url.replace('%url%', encodeURIComponent(document.getElementById('shareURL').getAttribute('content')));
		url = url.replace('%title%', encodeURIComponent(document.getElementById('shareTitle').getAttribute('content')));

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

		// Close the share box
		document.body.removeChild(document.getElementById('share'));
		}


	/**
	* 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 = document.getElementById('shareURL').getAttribute('content');
		document.getElementById('formShareEmailTitle').value = document.getElementById('shareTitle').getAttribute('content');

		// Send the request
		dojo.xhrPost(
			{
			url: '/sharepage.ajax.php',
			form: 'formShareEmail',
			handleAs: "text",
				load: function(data)
					{
					xhtml.shareEmailSent();
					},
				error: function(error)
					{
					}
				}
			);

		// 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("if (!!document.getElementById('share')==true){document.body.removeChild( document.getElementById('share'));}", 1750);
		}
	}



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



// ############################################################################################
//
//   Old JavaScript Code Follows
//
// ############################################################################################



// Displays popup before and after for procedures pages
function showLarge(picture_set, index, total) {
	filename = 'gallery.html?set='+escape(picture_set)+'&index='+escape(index)+'&total='+escape(total);
	window.open(filename, 'fylargeview', 'toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,top=60,left=15,width=770,height=400');
	}


// Display answer to question on ask dr rahimi, consultation page
function showAnswer(id) {
	document.getElementById('answer'+id).style.display = 'block';
	}



// Displays the paragraph below the link heading
function expandQA(obj)
	{
	var paragraphs = obj.parentNode.getElementsByTagName('p');
	for (var x = 0; x < paragraphs.length; x++)
		{
		if (paragraphs[x].style.display == 'block')
			{
			paragraphs[x].style.display = 'none';
			}
		else
			{
			paragraphs[x].style.display = 'block';
			}
		}
	}



// Displays the paragraph below the link heading
function toggleProcedureFAQ(obj)
	{
	if (obj.style.display == 'block')
		{
		obj.style.display = 'none';
		}
	else
		{
		obj.style.display = 'block';
		}
	}
