/**
* Assign the view handler
*/

dojo.require('dojo.cookie');

viewHandler = Home;

/**
* Creates a new object with methods used by the Home page
*
* @author				Matt Gifford
* @copyright			2008 Timeshifting Interactive Limited
*/
function Home()
	{
	// Step 1. Define Properties

	var _instance = this;
	this.votingEnabled = true;
	this.currentVideoId = 0;
	this.currentVideoId = null;



	// Step 2. Define Public Methods

	/**
	* Sets up the initial page state and event handlers
	*/
	this.init = function()
		{
		// Call generic page init method
		this.base.init.call(this);

		// Initialize page elements
		this.initVoteBox();
		this.scrollingRegionInit('episodeList');

		// Initialize video player box for iphone
		if (this.isMobileSafari == true)
			{
			if (document.getElementById('mediaPlayerOverlay'))
				{
				document.getElementById('mediaPlayerOverlay').className = 'hidden';
				}
			if (document.getElementById('mediaPlayerSpeed'))
				{
				document.getElementById('mediaPlayerSpeed').className = 'hidden';
				}
			if (document.getElementById('mediaPlayer'))
				{
				var nodes = dojo.query('#episodeListArtboard div.episodeItemPlaying');
				if (nodes.length)
					{
					document.getElementById('mediaPlayer').innerHTML = '<embed width="576" height="324" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/" src="' + nodes[0].getAttribute('sharePreview') + '" href="' + nodes[0].getAttribute('iphoneUrl') + '" target="myself" controller="false" autoplay="false" scale="aspect"></embed>';
					}
				}
			}
		}


	/**
	* Returns the flash movie with the specified name
	*
	* @param		movieName		The movie to return
	*/
	this.getFlashMovieObject = function(movieName)
		{
		return document.getElementById(movieName);
		}


	/**
	* Updates the meta data on video change
	*
	* @param		id		The video id
	*/
	this.updateMeta = function(id)
		{
		// Send the ajax request to get the ratings info
		dojo.xhrGet(
			{
			url: '/index/videometa/id/' + id,
			preventCache: true,
			handleAs: "text",
				load: function(data)
					{
					// Add the new coworker/comments content in to the document
					document.getElementById('videoMeta').innerHTML = data;
					xhtml.ratingStars.init();
					},
				error: function(error)
					{
					xhtml.ratingStars.init();
					}
			});
		}

	/**
	* Plays the specified video
	*
	* @param		obj				The anchor clicked on
	* @param		id					The id of the video to load
	* @param		title				The share title
	* @param		playlistId		The playlist Id
	* @return		url				The share modrewrite url
	*/
	this.playVideo = function(obj, id, index, title, playlistId, url)
		{
		// Log video play
		this.log('Play Video: ' + id + ', ' + url);

		// Set the current video id
		this.currentVideoId = index;

		// Update the playlist state
		var nodes = dojo.query('#episodeListArtboard div.episodeItemPlaying');
		for (var x = 0; x < nodes.length; x++)
			{
			nodes[x].className = nodes[x].className.replace(/\s?episodeItemPlaying/g, '');
			}

		// If an episodeItem node was supplied, set the now playing class
		if (obj != null)
			{
			obj.className += ' episodeItemPlaying';
			}

		// Check if we should load in the flash, or a preview image
		if (this.isMobileSafari == false)
			{
			try {
				// Standard Browser - Load the video
				var flashMovie = xhtml.getFlashMovieObject('videoPlayer');
				var playlist = '/index/xml/id/' + playlistId;
				if (typeof(flashMovie) != 'undefined' && flashMovie)
					{
					flashMovie.updateVideoData(playlist, index, "updateMeta", url);
					}
				} catch (err) { _log(err); }
			}
		else
			{
			// Mobile Safari version, update the preview image and queue quicktime player
			var nodes = dojo.query('#episodeListArtboard div.episodeItemPlaying');
			if (nodes.length)
				{
				document.getElementById('mediaPlayer').innerHTML = '<embed width="576" height="324" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/" src="' + nodes[0].getAttribute('sharePreview') + '" href="' + nodes[0].getAttribute('iphoneUrl') + '" target="myself" controller="false" autoplay="false" scale="aspect"></embed>';
				}
			}

		// Update the share this values
		this.shareUpdate();

		// Update the flash share url (used for the embed functionality)
		if (document.getElementById('shareFlash'))
			{
			document.getElementById('shareFlash').setAttribute('href', 'http://www.easytoassembleseries.com/flash/IKEA_VideoPlayer.swf?playlist=http://www.easytoassembleseries.com/xml/' + playlistId + '&videoID=' + id + '&');
			}

		// Load the featured coworkers and comments
		dojo.xhrGet(
			{
			url: '/index/coworkers/videoId/' + id,
			preventCache: true,
			handleAs: "text",
				load: function(data)
					{
					// Add the new coworker/comments content in to the document
					document.getElementById('homeCommentsCoworkers').innerHTML = data;
					}
				}
			);

		// Load the video meta
		dojo.xhrGet(
			{
			url: '/index/videometa/id/' + id,
			preventCache: true,
			handleAs: "text",
				load: function(data)
					{
					// Add the new coworker/comments content in to the document
					document.getElementById('videoMeta').innerHTML = data;
					xhtml.ratingStars.init();
					},
				error: function(error)
					{
					xhtml.ratingStars.init();
					}
				}
			);
		}


	/**
	* Updates the video meta panel (ratings and stars) for the currently playing video
	*/
	this.playlistAdvance = function()
		{
		var newVideoId = null;
		var playlistItems = dojo.query('#episodeListArtboard div.episodeItem');
		var playlistActiveNode = dojo.query('#episodeListArtboard div.episodeItemPlaying');

		// Check if there's a playlist and selected item
		if (!!document.getElementById('episodeListArtboard') == false || playlistItems.length == 0 || playlistActiveNode.length == 0)
			{
			return;
			}

		// Get the currently playing video node if it's not set
		if (this.currentVideoId != null)
			{
			// Extract the currently playing id
			this.currentVideoId = playlistActiveNode[0].getAttribute('rel');
			}

		// Select the next video
		for (var x = 0; x < playlistItems.length; x++)
			{
			// If we're found the currently playing node, set the next node as active and store the new video id
			if (playlistItems[x] === playlistActiveNode[0])
				{
				// Clear the now playing class
				playlistItems[x].className = playlistItems[x].className.replace(/\s?episodeItemPlaying/g, '');

				// Find the next playable node
				var y = x+1;
				var nextPlayableNode = playlistItems[y++];
				while (nextPlayableNode != null)
					{
					// Check if there's a video id (stored in the 'rel' attribute) and it isn't a coming soon video
					if (nextPlayableNode.getAttribute('rel') == '' || nextPlayableNode.className.indexOf('episodeItemComingSoon') != -1)
						{
						// This playlist item is unplayable, so grab the next node and we'll check again
						nextPlayableNode = playlistItems[y++];
						}
					else
						{
						// Playable playlistItem found, so break out of loop
						break;
						}
					}

				// If there was a next playable node, update its class and store the currently playing video id
				if (nextPlayableNode != null)
					{
					nextPlayableNode.className += ' episodeItemPlaying';
					newVideoId = nextPlayableNode.getAttribute('rel');

					// Update the flash share url (used for the embed functionality)
					if (document.getElementById('shareFlash'))
						{
						document.getElementById('shareFlash').setAttribute('href', 'http://www.easytoassembleseries.com/flash/IKEA_VideoPlayer.swf?playlist=http://www.easytoassembleseries.com/xml/' + nextPlayableNode.getAttribute('playlist') + '&videoID=' + nextPlayableNode.getAttribute('rel') + '&');
						}
					}
				}
			}

		// If we're started a new video, update the meta data bar below the video
		if (newVideoId != null)
			{
			// Update the currently playing id
			this.currentVideoId = newVideoId;

			// Update the share this values
			this.shareUpdate();

			// Send the ajax request to get the ratings info
			dojo.xhrGet(
				{
				url: '/index/videometa/id/' + this.currentVideoId,
				preventCache: true,
				handleAs: "text",
					load: function(data)
						{
						// Add the new coworker/comments content in to the document
						document.getElementById('videoMeta').innerHTML = data;
						xhtml.ratingStars.init();
						},
					error: function(error)
						{
						xhtml.ratingStars.init();
						}
					}
				);
			}
		}


	/**
	* Stops the playback of the current video
	*/
	this.stopVideo = function()
		{
		}


	/**
	* Changes the season
	*
	* @param		obj				The anchor clicked on
	* @param		id					The id of the season to load
	* @param		video			The video Id to be played
	* @param		loadVideo		...
	*/
	this.getSeason = function(obj, id, videoIndex, video, loadVideo)
		{
		// Log season load
		this.log('Get Season: ' + id + ', ' + videoIndex);

		// Update the season post-its
		var nodes = document.getElementById('seasons').getElementsByTagName('a');
		if (obj != null)
			{
			for (var x = 0; x < nodes.length; x++)
				{
				nodes[x].className = '';
				}

				obj.className = 'active';
			}

		// Stop the currently playing video
		this.stopVideo();
		var myUrl = '/index/playlist/id/' + id;
		if (videoIndex != 0)
			{
			myUrl = myUrl + '/videoId/' + videoIndex;
			}

		// Delete current playlist
		document.getElementById('episodeListArtboard').innerHTML = '';
		document.getElementById('episodeListArtboard').className = 'artboard artboardLoading';
		document.getElementById('episodeListArtboard').style.top = '0px';

		// Load new playlist
		dojo.xhrGet(
			{
			url: myUrl,
			preventCache: true,
			handleAs: "text",
				load: function(data)
					{
					// Add the new playlist in to the document
					document.getElementById('episodeListArtboard').className = 'artboard';
					document.getElementById('episodeListArtboard').innerHTML = data;
					xhtml.scrollingRegionInit('episodeList');

					// Update the preview for mobile safari
					if (xhtml.isMobileSafari == true)
						{
						var nodes = dojo.query('#episodeListArtboard div.episodeItem');
						if (nodes.length)
							{
							document.getElementById('mediaPlayer').innerHTML = '<embed width="576" height="324" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/" src="' + nodes[0].getAttribute('sharePreview') + '" href="' + nodes[0].getAttribute('iphoneUrl') + '" target="myself" controller="false" autoplay="false" scale="aspect"></embed>';

							try {
								// Reassign event handlers (to workaround safari bug)
								for (var x = 0, code = ''; x < nodes.length; x++)
									{
									code = nodes[x].getAttribute('onclick');
									nodes[x].setAttribute('onclick', '');
									nodes[x].onclick = new Function(code);
									}
								} catch (err) {}
							}
						}
					},
				error: function(error)
					{
					document.getElementById('episodeListArtboard').className = 'artboard';
					document.getElementById('episodeListArtboard').innerHTML = '<div style="padding: 20px 80px 20px 20px">An error occurred loading the playlist, please try again.<br/><br/>' + error + '</div>';
					}
				}
			);

		// Start the new Video
		if (loadVideo)
			{
			this.playVideo(null, video, videoIndex, null, id, null);
			}
		else {
			// Make sure we update the coworkers
			// Load the featured coworkers and comments
			dojo.xhrGet(
				{
				url: '/index/coworkers/videoId/' + video,
				preventCache: true,
				handleAs: "text",
					load: function(data)
						{
						// Add the new coworker/comments content in to the document
						document.getElementById('homeCommentsCoworkers').innerHTML = data;
						}
					}
				);
			}
		}


	/**
	* Hides the main vote box
	*/
	this.closeVoteBox = function()
		{
		if (document.getElementById('homeVote'))
			{
			dojo.fadeOut(
					{
					node: 'homeVote',
					onEnd: function()
						{
						// Remove the notice
						dojo.destroy('homeVote');
						}
					}
				).play();
			}
		}


	/**
	* Submits the comment form
	*/
	this.submitComment = function(currentVideoId)
		{
		// Get the form fields
		var inputs = document.getElementById('formComments').getElementsByTagName('input');
		var textarea = document.getElementById('formComments').getElementsByTagName('textarea')[0];

		// Validate the fields
		if (inputs[0].value.length < 4)
			{
			alert('Please fill out the \'name\' field.');
			return;
			}
		if (inputs[1].value.length < 4)
			{
			alert('Please fill out the \'email\' field.');
			return;
			}
		var regex = /^[a-z0-9_+-.]+@[a-z0-9_-]*\.?[a-z0-9_-]*\.?[a-z0-9_-]*\.[a-z]+$/i;
		if (regex.test(inputs[1].value) == false)
			{
			alert('Please check that your \'email address\' is entered correctly.');
			return;
			}
		if (inputs[2].value.length != 6)
			{
			alert('The \'verification code\' should be 6 characters long, please check that it is entered correctly.');
			return;
			}
		if (textarea.value.length < 4)
			{
			alert('Please fill out the \'comments\' text box.');
			return;
			}

		// Submit the form
		document.getElementById('formComments').action = '/index/coworkers/videoId/' + currentVideoId;
		dojo.xhrPost(
				{
				url: '/index/coworkers/videoId/' + currentVideoId,
				form: 'formComments',
				load: function(data)
					{
					// Add the new coworker/comments content in to the document
					document.getElementById('homeCommentsCoworkers').innerHTML = data;
					},
				error: function(data)
					{
					alert('Sorry we were unable to add your comment.\nPlease try again.');
					}
				}
			);
		}


	/**
	* Adds the event handlers to the vote box
	*/
	this.initVoteBox = function()
		{
		if (!document.getElementById('homeVote'))
			{
			return;
			}

		// 1. Define event handlers
		var __eventHandlerMouseOver = function()
			{
			if (xhtml.votingEnabled) document.getElementById('homeVote').className = this.id;
			}
		var __eventHandlerMouseOut = function()
			{
			if (xhtml.votingEnabled) document.getElementById('homeVote').className = '';
			}
		var __eventHandlerClick = function()
			{
			if (xhtml.votingEnabled)
				{
				// Kill the mouse over events
				xhtml.votingEnabled = false;

				// Set the class
				document.getElementById('homeVote').className = this.id;

				// Send the ajax request
				dojo.xhrGet(
						{
						url: '/index/vote/id/' + this.getAttribute('rel'),
						preventCache: true,
						handleAs: "text",
						load: function(data)
							{
							// Display message
							if (data.indexOf('Success') != -1)
								{
								xhtml.closeVoteNowBox();
								document.getElementById('homeVote').className = 'voted';
								xhtml.thanksVotingShow();
								}
							else
								{
								alert(data);
								}
							return false;
							},
						error: function(error)
							{

							// Display message
							xhtml.closeVoteNowBox();
							document.getElementById('homeVote').className = 'voted';
							return false;
							}
						}
					);
				}
			}
		// 2. Assign the event handlers
		document.getElementById('voteA').onmouseover = __eventHandlerMouseOver;
		document.getElementById('voteA').onmouseout = __eventHandlerMouseOut;
		document.getElementById('voteA').onclick = __eventHandlerClick;
		document.getElementById('voteB').onmouseover = __eventHandlerMouseOver;
		document.getElementById('voteB').onmouseout = __eventHandlerMouseOut;
		document.getElementById('voteB').onclick = __eventHandlerClick;
		}
	}
