/**
 * PoolTube Video Controller
 * Concept from: http://bit.ly/5u5x0c
 */

	/**
	 * Function progressChanged()
	 * Displays the loading progress on the controller.
	 */
	function progressChanged(e) {
		// Video information
			var loaded = $("#e"+e.data.rel)[0].GetMaxTimeLoaded();
			var total  = $("#e"+e.data.rel)[0].GetDuration();
		
		// Calculate how much is loaded, and how much is left
			var percentLoaded = parseInt((loaded / total) * 100);
			var percentLeft = 100 - percentLoaded;
		
		// Set the width of the indicator
			$("#pr"+e.data.rel).width(percentLeft + "%");
		
		// Repeat the function because it isn't called
		// very often. The loading bar is smoother as
		// a result.
			var pc = function() { progressChanged(e); };
			if(loaded != total) setTimeout(pc, 0);
	}


	/**
	 * Function: timeChanged()
	 * Fires every time the time changes
	 */
	function timeChanged(e) {
		// Video ID
			var rel = e.data.rel;
		
		// Get video details
			var time = $("#e"+rel)[0].GetTime();
			var dur  = $("#e"+rel)[0].GetDuration();
			var scale = $("#e"+rel)[0].GetTimeScale();
			var percent  = parseFloat((time / dur) * 100);
			$("#p"+rel).width(percent + "%");
		
		// Duration - current, total, remaining
			var curSec = parseInt(time / scale);
			var durSec = parseInt(dur  / scale);
			var left   = durSec - curSec;
		
		// Put them into the video
			$("#tc"+rel).html(splitTime(curSec));
			$("#tl"+rel).html("- " + splitTime(left));
		
		// Repeat the function
			var timeout = function() { timeChanged(e); };
			if(time != dur) setTimeout(timeout, 0);
	}
	
	/**
	 * Function: moviePaused()
	 * Fires when the movie is paused, changing the action button.
	 */
	function moviePaused(e) {
		$("#play"+e.data.rel).css("display", "block");
		$("#stop"+e.data.rel).css("display", "none");
		$('#c'+e.data.rel).fadeIn('fast')
	}
	
	/**
	 * Function: movieStarted()
	 * Fires when the movie is played, changing the action button
	 * and starting the timeChanged() loop.
	 */
	function movieStarted(e) {
		$("#play"+e.data.rel).css("display", "none");
		$("#stop"+e.data.rel).css("display", "block");
		$("#loading"+e.data.rel).remove();
		timeChanged(e);
	}
	
	/**
	 * Function: setPosition()
	 * Set the position of the movie/playhead. Wouldn't be
	 * awesome if it actually worked in Firefox?
	 */
	function setPosition(event, isntfirst) {
		var obj = event.target;
		var rel = event.data.rel;
		
		// Get the mouse position
			var offset = $("#content")[0].offsetLeft;
			
			var posx = 0;
			if (event.pageX) 	{
				posx = event.pageX;
			}
			else if (event.clientX) 	{
				posx = event.clientX + document.body.scrollLeft
					+ document.documentElement.scrollLeft;
			}
			
			var click = posx - offset - 93; // why 93? the world may never know.
		
		// Percent (click / width)
			var percent = click / 439;
		
		// Quicktime time
			var dur = $("#e"+rel)[0].GetDuration();
			var qt  = parseInt(dur * percent);
			
			$("#e"+rel)[0].SetTime(qt);
	}
	
	/**
	 * Function: splitTime()
	 * Convert seconds to hh:mm:ss
	 */
	function splitTime(a) { 
		var hours	= Math.floor(a / 3600); 
		var minutes	= Math.floor(a / 60) - (hours * 60); 
		var seconds	= a - (hours * 3600) - (minutes * 60); 
	
		var hs=' hour';var ms=' minute';var ss=' second'; 
		if(hours   < 10) hours   = "0" + hours; 
		if(minutes < 10) minutes = "0" + minutes;
		if(seconds < 10) seconds = "0" + seconds;
		return hours + ':' + minutes + ':' + seconds;
	}

	
	var moviesRegistered = false;
	
	/**
	 * Function: registerMovies()
	 * Sets up all of the movies with IDs for use later
	 */
	function registerMovies() {
		$("div.embed").each(function(i, obj) {
			// Give it an ID
				// The "rel" idea is probably a horrible implementation,
				// but at least it works for now.
				$(obj).attr("rel", i).attr("id", "d"+i);
		});
				
		moviesRegistered = true;
		
		// While we're at it, let's setup the search box listener.
			$("#mainSearchBox").bind("focus", function() { if($("#mainSearchBox").val() == " Search") $("#mainSearchBox").val(""); });
			$("#mainSearchBox").bind("blur",  function() { if($("#mainSearchBox").val() == "") $("#mainSearchBox").val(" Search"); });
			
		// Test for IE6 and IE7.. And if someone is still using IE5,
		// maybe they deserve to suffer with a terribly rendered page.
		if(($.browser.msie && $.browser.version=="6.0") || ($.browser.msie && $.browser.version=="7.0")) {
			$("body").append("<div style='position: absolute; top: 20px; left: 20px; z-index: 200; background: #FFF; padding: 20px; width: 300px;'><b>Whoa, there!</b> This website was built with the latest and greatest technologies, and your browser (<i>Internet Explorer</i>) just isn't up to speed.<br/><br/>But all is not lost! Get <a href='http://google.com/chrome'><b>Google's Chrome</b></a> or <a href='http://firefox.com'><b>Mozilla's Firefox</b></a> browsers for free to see PoolTube (and the rest of the Internet) the way it was intended to be.<br/><br/>They're a lot faster and safer, too. Trust me; you'll be doing yourself a favor.</div>");
		}
	}
	
	
	
	/**
	 * Function: clickPosterFrame(event, a href)
	 * Fires when a video's poster frame is clicked, generating
	 * the video, controller, and event listeners
	 */
	function clickPosterFrame(a) {
		
		// If the user clicks before the page is loaded,
		// we'll start everything up.
			if(moviesRegistered == false) registerMovies();
		
		// 1. Setup
	
			// Movie ID, object, movie url
				var obj = a.parentNode;
				var num = $(obj).attr("rel");
				var url = $(a).attr("href");
			
			// Remove the poster frame
				$(a).remove();
			
			// Some variables to ease things later
				var embed = "#e"+num;	// Embed object ID
				var div   = "#d"+num;	// Movie DIV
		
		
		// 2. Generate the movie and controller

				if($.browser.safari) {
/*					// Chrome and Safari
					
					$(obj).append($("<div class='loading' id='loading"+num+"'><img src='http://pooltube.tv/wp-content/themes/pooltube/img/load.gif' alt=''/></div>"));
					
					// Movie
					//$(obj).append($("<embed src='"+url+"' width='640px' height='360px' autoplay='false' loop='false' controller='false' pluginspage='http://www.apple.com/quicktime/' id='e"+num+"' postdomevents='true' wmode='transparent'/>"));
*/
					
					$(obj).append($("<video src='"+url+"' width='640px' height='360px' controls='true' id='e"+num+"' autoplay></video>"));
					
/*
					// Controller
					$(obj).append($("<div class='controller' id='c"+num+"'><div class='playButton' id='play"+num+"'></div><div class='pauseButton' id='stop"+num+"'></div><div class='time'><div class='timeCurrent' id='tc"+num+"'>00:00:00</div><div class='track' id='t"+num+"'><div class='trackwrap'><div class='playhead' id='p"+num+"'></div><div class='progress' id='pr"+num+"'></div></div><div class='tracker' id='tr"+num+"'></div></div><div class='timeLeft' id='tl"+num+"'>Loading&hellip;</div></div></div>"));
*/				}
				else {
					// Firefox and everything else
					
					// Movie
					$(obj).append($("<embed src='"+url+"' width='640px' height='360px' autoplay='false' loop='false' controller='false' pluginspage='http://www.apple.com/quicktime/' id='e"+num+"' postdomevents='true'/>")); // Firefox on Windows takes the wmode='transparent' a bit too literally.
					
					// Controller
					$(obj).append($("<div class='controller ff' id='c"+num+"'><div class='playButton' id='play"+num+"'></div><div class='pauseButton' id='stop"+num+"'></div><div class='time'><div class='timeCurrent' id='tc"+num+"'>00:00:00</div><div class='track' id='t"+num+"'><div class='trackwrap'><div class='playhead' id='p"+num+"'></div><div class='progress' id='pr"+num+"'></div></div><div class='tracker' id='tr"+num+"'></div></div><div class='timeLeft' id='tl"+num+"'>- 00:00:00</div></div></div>"));
					
					$("#d"+num).height("392px");
					
					// 3. Listeners
				
					// <object>
						$(embed).bind("qt_progress",		{rel:num},	progressChanged	);
						$(embed).bind("qt_load",			{rel:num},	progressChanged	);
						$(embed).bind("qt_play",			{rel:num},	progressChanged	); // just in case
						$(embed).bind("qt_timechanged",		{rel:num},	timeChanged		);
						$(embed).bind("qt_pause", 			{rel:num},	moviePaused		);
						$(embed).bind("qt_ended", 			{rel:num},	moviePaused		);
						$(embed).bind("qt_play", 			{rel:num},	movieStarted	);
						$(embed).bind("qt_canplaythrough",	{rel:num},	function() { $(embed)[0].Play() });
					
					// Playhead track
						$("#tr"+num).bind("click",		{rel:num},	setPosition  );
					
					// Play/Pause
						$("#play"+num).bind("click", function() { $(embed)[0].Play() });
						$("#stop"+num).bind("click", function() { $(embed)[0].Stop() });
					
					// Browser-specific features
						if($.browser.safari) {
							// The controller appears on top of the video in Webkit browsers
							// and fades in/out upon hovering.
							$(div).bind("mouseenter", function(e) { $('#c'+num).fadeIn('fast') });
							$(div).bind("mouseleave", function(e) { $('#c'+num).fadeOut('slow') });
						}
						else {
							// In everything else, the controller will go below.
							// Todo: Create a new controller meant for below. Same concept,
							//       just different CSS and images.
							//document.getElementById("c"+num).style.marginTop = "0px";
							//document.getElementById("c"+num).style.display = "block";
						}
						
						
						var playit = function() { $(embed)[0].Play() };
						setTimeout(playit, 0);
				}

		
		

/*
		// 3. Listeners
		
			// <object>
				$(embed).bind("qt_progress",		{rel:num},	progressChanged	);
				$(embed).bind("qt_load",			{rel:num},	progressChanged	);
				$(embed).bind("qt_play",			{rel:num},	progressChanged	); // just in case
				$(embed).bind("qt_timechanged",		{rel:num},	timeChanged		);
				$(embed).bind("qt_pause", 			{rel:num},	moviePaused		);
				$(embed).bind("qt_ended", 			{rel:num},	moviePaused		);
				$(embed).bind("qt_play", 			{rel:num},	movieStarted	);
				$(embed).bind("qt_canplaythrough",	{rel:num},	function() { $(embed)[0].Play() });
			
			// Playhead track
				$("#tr"+num).bind("click",		{rel:num},	setPosition  );
			
			// Play/Pause
				$("#play"+num).bind("click", function() { $(embed)[0].Play() });
				$("#stop"+num).bind("click", function() { $(embed)[0].Stop() });
			
			// Browser-specific features
				if($.browser.safari) {
					// The controller appears on top of the video in Webkit browsers
					// and fades in/out upon hovering.
					$(div).bind("mouseenter", function(e) { $('#c'+num).fadeIn('fast') });
					$(div).bind("mouseleave", function(e) { $('#c'+num).fadeOut('slow') });
				}
				else {
					// In everything else, the controller will go below.
					// Todo: Create a new controller meant for below. Same concept,
					//       just different CSS and images.
					//document.getElementById("c"+num).style.marginTop = "0px";
					//document.getElementById("c"+num).style.display = "block";
				}
				
				
				var playit = function() { $(embed)[0].Play() };
				setTimeout(playit, 0);
*/

		
		// And, prevent the javascript-fallback link from following through:
			return false;
	}
