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



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

	
	/**
	* Toggles the header search scope
	*
	* @param		obj			The anchor clicked on
	* @param		scope		The new scope
	*/
	this.headerSearchScope = function(obj, scope)
		{
		// Update the buttons
		var anchors = document.getElementById('globalHeaderSearch').getElementsByTagName('ul')[0].getElementsByTagName('a');
		for (var x = 0; x < anchors.length; x++)
			{
			anchors[x].className = '';
			}
		obj.className = 'active';

		// Update the scope
		document.getElementById('globalHeaderSearchScope').value = scope;
		}

        /**
 *          * Toggles the Like/Unlike textarea
 *                   *
 *                            * @param       obj     The achor clicked on
 *                                     * @param       type    The new type to send to script
 *                                              */
        this.switchLikeType = function(obj, type) {
                var switchLikeDiv = document.getElementById('switchLikeItem');
                var switchUnlikeDiv = document.getElementById('switchUnlikeItem');
                var likeHeaderDiv = document.getElementById('addLikeHeader');
                var unlikeHeaderDiv = document.getElementById('addUnlikeHeader');
                var addForm = document.addLikes;

                if ( type == 'unlike items' ) {
                        switchLikeDiv.style.display = 'block';
                        unlikeHeaderDiv.style.display = 'block';
                        switchUnlikeDiv.style.display = 'none';
                        likeHeaderDiv.style.display = 'none';
                        addForm.elements['task'].value = type;
                } else {
                        switchLikeDiv.style.display = 'none';
                        likeHeaderDiv.style.display = 'block';
                        switchUnlikeDiv.style.display = 'block';
                        unlikeHeaderDiv.style.display = 'none';
                        addForm.elements['task'].value = type;
                }
           }

           this.hideJoinBox = function()
                {
                // Hide the join box
                dojo.fadeOut({ node: "homeJoin", properties: {opacity: 0}, duration: 800,
                               onEnd: function(){
                                         document.getElementById('homeJoin').style.visibility = 'hidden';
                                         dojo.animateProperty({ node: "homeJoin", properties: {height: 0}, duration: 500 }).play();
                                      }
                              }).play();
                // TODO: Write a cookie or ajax the backend
                }
                //

            /**
        * Toggles the comment items
        *
        * @param                obj             The anchor clicked on
        */
        this.objectCommentToggle = function(obj)
                {
                var commentItem = obj.parentNode.parentNode.parentNode;
                if (commentItem.className.indexOf('collapsed') != -1)
                        {
                        commentItem.className = commentItem.className.replace('collapsed', 'expanded');
                        }
                else
                        {
                        commentItem.className = commentItem.className.replace('expanded', 'collapsed');
                        }
                }


	}



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