/**
 * The Page object handles all the ways for
 * the users to interact with the website.
 *
 * @module FrancesTwiddy
 * @class Control
 * @author Dan Whitfield
 */
var Control = 
{
	/**
	 * Locking flag for both clicks and key events.
	 *
	 * @property _lockPhotoThumbChangeEvent
	 * @type Bool
	 * @private
	 */
	_lockPhotoThumbChangeEvent: false,
	
	
	/**
	 * Runs through the control initialisation.
	 *
	 * @method initialise
	 * @public
	 */
	initialise: function()
	{
		this._disableSpecifiedKeys();
		this._disableHorizontalScroll();
		this._registerMainNavLinks();
		this._initialiseAppMenu();
		this._registerVideoLinks();
		this._registerPhotoLinks();
		this._registerPhotoThumbLinks();
		this._registerExternalAnchors();
		this._registerFormSubmit();
		this._registerFormFieldEvents();
	},
	
	
	/**
	 * Disable all keys specified in the specifiedDisabledKeys array.
	 *
	 * @method _disableSpecifiedKeys
	 * @private
	 */
	_disableSpecifiedKeys: function()
	{
		var that = this;
		var specifiedDisabledKeys = [9];
		var exceptions = ["text", "email", "textarea"];
		
		$(document).keydown(function(e)
		{
			var keyCodeNumber = e.keyCode;
			var delegateName  = Utils.keyMappings[keyCodeNumber];
			
			// Allow custom delegate functions.
			if(that._customKeyDelegates[delegateName])
			{
				that._customKeyDelegates[delegateName]();
			}
			
			if($.inArray(keyCodeNumber, specifiedDisabledKeys) > -1 && $.inArray(e.currentTarget.activeElement.type, exceptions) === -1)
			{
    			e.preventDefault();
    		}
		});
	},
	
	
	/**
	 * Define delegates for specified keys.
	 *
	 * @method _customKeyDelegates
	 * @private
	 */
	_customKeyDelegates:
	{
		"esc": function()
		{
			// Prevent any other navigation after key event.
			Page._navigationLock = true;
			
			if($(".boxy-wrapper").length)
			{
				// If a Boxy element exists then remove it.
				$(".boxy-wrapper").remove();
			}
			
			// Had to unlock navigation in setTimeout to prevent appMenu running.
			setTimeout(function(){Page._navigationLock = false;}, 100);
		},
		
		"left": function()
		{
			Control._movePhotoSelectionWithKey("left");
		},
		
		"right": function()
		{
			Control._movePhotoSelectionWithKey("right");
		}
	},
	
	
	/**
	 * Move to the next/prev photo/thumbnail.
	 *
	 * @method _movePhotoSelectionWithKey
	 * @private
	 */
	_movePhotoSelectionWithKey: function(direction)
	{
		if($("#mainImageTag").length && !this._lockPhotoThumbChangeEvent)
		{
			var currentlySelected = $(".currentlySelected");
			var elementToTrigger  = null;
			
			this._lockPhotoThumbChangeEvent = true;
			$(currentlySelected).removeClass("currentlySelected");
			
			if(direction === "right")
			{	
				if($(currentlySelected).next().length !== 0)
				{
					elementToTrigger = $(currentlySelected).next().children("img");
				}
				else
				{
					elementToTrigger = $(currentlySelected).parent("ul").children("li:first").children("img");
				}
			}
			else
			{
				if($(currentlySelected).prev().length !== 0)
				{
					elementToTrigger = $(currentlySelected).prev().children("img");
				}
				else
				{
					elementToTrigger = $(currentlySelected).parent("ul").children("li:last").children("img");
				}
			}
			
			$(elementToTrigger).trigger("click");
		}
	},
	
	
	/**
	 * Disable horizontal scroll.
	 *
	 * @method _disableHorizontalScroll
	 * @private
	 */
	_disableHorizontalScroll: function()
	{
		var mouseWheelEvt = function (e)
		{
		    var event = e || window.event;
		    
		    if(event.axis === 1)
			{
				e.preventDefault();
				return false;
			}
		}
		
		if ("onmousewheel" in document.body)
		{
		    document.body.onmousewheel = mouseWheelEvt;
		}
		else
		{
		    document.body.addEventListener("DOMMouseScroll", mouseWheelEvt, true);
		}
	},
	
	
	/**
	 * Register main nav link 'click' events.
	 *
	 * @method _registerMainNavLinks
	 * @private
	 */
	_registerMainNavLinks: function()
	{
		var that = this;
		
		// Set up an event for the nav clicks.
		$("#mainnav li a").live("click", function(e)
		{
			if(Page._navigationLock === false)
			{
				Page._selectedPageId = $(this).attr("href").split("#")[1];
				
				// Make sure that we would not be trying to switch to the current page.
				if(Page._currentPageId === Page._selectedPageId)
				{
					// It is the current page that is being requested so take no action.		
					Utils.debugConsole("Page already displayed");
				}
				else
				{
					Page._navigationLock = true;
					Page._toggleMainNav();
					Page.switchPage();
				}
			}
			
			e.preventDefault();
		});
	},
	
	
	/**
	 * Register video link 'click' events.
	 *
	 * @method _registerVideoLinks
	 * @private
	 */
	_registerVideoLinks: function()
	{
		// Set up the video link clicks.
		$(".videoLink").live("click", function(e)
		{
			Utils.toggleActivityIndicator();
			
			// Grab the video attrubites.
			var videoUrl   = $(this).attr("href");
			var videoTitle = $(this).attr("title");
			var videoSizes = $(this).attr("rel").split("|");
			
			// Generate the video embed HTML.
			Utils.showVideo(
			{
				url: videoUrl,
				width: videoSizes[0],
				height: videoSizes[1],
				controller: false,
				title: videoTitle
			});
			
			e.preventDefault();
		});
	},
	
	
	/**
	 * Register photo link 'click' events.
	 *
	 * @method _registerPhotoLinks
	 * @private
	 */
	_registerPhotoLinks: function()
	{
		// Set up the photo link clicks.
		$(".photoAlbumLink").live("click", function(e)
		{
			Utils.toggleActivityIndicator();
			var albumName = $(this).attr("href").replace("#", "");
			var albumDisplayName = $(this).attr("title");
			Utils.showPhotoAlbum(albumName, albumDisplayName);
			e.preventDefault();
		});
	},
	
	
	/**
	 * Register photo thumb link 'click' events.
	 *
	 * @method _registerPhotoThumbLinks
	 * @private
	 */
	_registerPhotoThumbLinks: function()
	{
		var that = this;
		
		// Set up the photo link clicks.
		$("#imageThumbs ul li img").live("click", function(e)
		{
			// The image load event had been being called twice so had to impliment lock fix.
			var imageLoadLock = false;
			
			Utils.toggleActivityIndicator("#mainImageTag");
			var newImageSrc = $(this).attr("src").replace("-thumb", "");
			$("#mainImageTagElement").attr("src", newImageSrc);
			$("#imageThumbs ul li").removeClass("currentlySelected");
			$(this).parent("li").addClass("currentlySelected");
			
			$("#mainImageTagElement").load(function()
			{
				if(!imageLoadLock)
				{
					Utils.toggleActivityIndicator("#mainImageTag");
					imageLoadLock = true;
					that._lockPhotoThumbChangeEvent = false;
				}
			});
			
			e.preventDefault();
		});
	},
	
	
	/**
	 * Register links that are external.
	 *
	 * @method _registerExternalAnchors
	 * @private
	 */
	_registerExternalAnchors: function()
	{
		// Set up the video link clicks.
		$(".ext").live("click", function(e)
		{
			window.open($(this).attr("href"));
			e.preventDefault();
		});
	},
	
	
	/**
	 * This handles contact form submission.
	 *
	 * @method _registerFormSubmit
	 * @private
	 */
	_registerFormSubmit: function()
	{
		// Set up the video link clicks.
		$("#submit").live("click", function(e)
		{
			Contact.submitForm("contactForm");
			e.preventDefault();
		});
	},
	
	
	/**
	 * This handles contact form field focus/blur.
	 *
	 * @method _registerFormFieldEvents
	 * @private
	 */
	_registerFormFieldEvents: function()
	{
		// Only use JavaScript placeholders for non HTML 5 browsers.
		if(Modernizr.input.placeholder)
		{
			// Hide the JavaScript placeholders for HTML 5 supporting browsers.
			$("#contactForm label").css("line-height", "20000px");
		}
		else
		{
			// Set up the video link clicks.
			$("#contactForm input, #contactForm textarea").live("focus", function(e)
			{
				if($(this).val() === "")
				{
					var currentLineHeight = $(this).prev().css("line-height");
					
					if(currentLineHeight === "10000px")
					{
						$(this).prev().css("line-height", "24px");
					}
					else
					{
						$(this).prev().css("line-height", "10000px");
					}
				}
				
				e.preventDefault();
			});
			
			// Set up the video link clicks.
			$("#contactForm input, #contactForm textarea").live("blur", function(e)
			{
				if($(this).val() === "" && $(this).prev().css("line-height") === "10000px")
				{
					$(this).prev().css("line-height", "24px");
				}
				
				e.preventDefault();
			});
		}
	},
	
	
	/**
	 * Initialise the App Menu plugin.
	 *
	 * @method _initialiseAppMenu
	 * @private
	 */
	_initialiseAppMenu: function()
	{
		var that = this;
		
		$('#appMenu').appMenu(
		{
			showControl: false,
			onSelect: function(obj, appMenuOpts)
			{
				that._handleAppMenuSelection(obj, appMenuOpts);
			}
		});
	},
	
	
	/**
	 * This handles navigation via the app menu plugin.
	 *
	 * @method _handleAppMenuSelection
	 * @private
	 * @param {Object} obj
	 * @param {Object} appMenuOpts
	 */
	_handleAppMenuSelection: function(obj, appMenuOpts)
	{
		if(Page._navigationLock === false)
		{
			var nextPageId = $(obj).attr("href").split("#")[1];
			
			if(nextPageId != Page._currentPageId)
			{
				Page._navigationLock = true;
				Page._toggleMainNav();
				Page.switchPage(nextPageId);
			}
			else
			{
				// It is the current page that is being requested so take no action.		
				Utils.debugConsole("Page already displayed");
			}
		}
	}
};
