// Dreamscope
// Global Javascript functions
// Powered by Prego

var dreamscopeSelectedVideo = 0;
var dreamscopeVideoAnimating = false;
var dreamscopeVideoData = {};
var dreamscopeAnimationSpeed = 1500;

$(function()
{
	dreamscopeInitVideoList();
});

function dreamscopeInitVideoList()
{
	// Don't bother if we're not on a page with a video list
	if($("#video").length == 0)
		return;

	// Don't animate in IE6 or lesser
	if(jQuery.browser.msie && jQuery.browser.version < 7)
	{
		displayVideoPlayButton();
		return;
	}
	
	$("#video ul.navigation li a").each(function(i)
	{
		// Work out the index of the currently selected image
		if($(this).parent("li").hasClass("current"))
			dreamscopeSelectedVideo = i;
		
		// Replace navigation links with animation
		$(this).click(function()
		{
			if(dreamscopeVideoAnimating)
				return false;
			
			dreamscopeVideoAnimating = true;
			dreamscopeAnimateVideoList(i);
			
			this.blur();
			
			window.location.hash = $(this).attr("href").replace(/^.*\//, "");
			
			return false;
		});
		
		// Preload reflection images
		var reflectionImageURL = $(this).parent("li").css("background-image");
		reflectionImageURL = reflectionImageURL
			.replace(/^url\(['"]?/, "")
			.replace(/['"]?\)$/, "")
			.replace(/\/reflected-small\//, "/reflected/");
		$("<img>").attr("src", reflectionImageURL);
	});
	
	// If there's a fragment, transition to that video
	if(window.location.hash)
	{
		var originalAnimationSpeed = dreamscopeAnimationSpeed;
		dreamscopeAnimationSpeed = 0;
		$("#video ul.navigation li a[href$=/"+window.location.hash.replace(/^#/, "")+"]").trigger("click");
		dreamscopeAnimationSpeed = originalAnimationSpeed;
	}
	else
	{
		displayVideoPlayButton();
	}
}

function dreamscopeAnimateVideoList(videoIndex)
{		
// Set up for animation
	
	// Set up animation parameters
	var animationSpeed = dreamscopeAnimationSpeed;
	jQuery.easing.def = "easeInOutCubic"; 

	// Get rid of the video and play button
	$("a.play-video").remove();
	$("div.video-container").html("<div id=\"video-player-flash\"></div>");

	// Relevant items in the video list
	var $selectedVideo = $("#video ul.navigation li:eq("+videoIndex+")");
	var $nextVideo = $("#video ul.navigation li:eq("+(videoIndex+1)+")");
	var $previousVideo= $("#video ul.navigation li:eq("+(videoIndex-1)+")");
	
	// Find the URL of the background image for the current video
	var reflectionImageURL = $("div.current-video .description").css("background-image");
	reflectionImageURL = reflectionImageURL
		.replace(/^url\(['"]?/, '')
		.replace(/['"]?\)$/, '');
		
	// Create an <img> version of the current video's background image
	// (Background image cannot be animated and scaled, this can)
	var $reflectionImage = $("<img/>")
		.attr("alt", "")
		.attr("src", reflectionImageURL)
		.attr("width", "512")
		.attr("height", "288");
	
	// Replace the current video's description with the <img> version of its reflection
	$("div.current-video .description").hide();
	$("div.current-video").append($reflectionImage);
	
	// Find the URL of the background image for the selected video
	var selectedReflectionImageURL = $("img", $selectedVideo).attr("src").replace("/main/", "/reflected/");
	
	// Create an <img> version of the selected video's background image
	var $selectedReflectionImage = $("<img/>")
		.attr("alt", "")
		.attr("src", selectedReflectionImageURL)
		.attr("width", "256")
		.attr("height", "144");
	
	// Add the reflection image to the selected video
	$("a", $selectedVideo).append($selectedReflectionImage);
	
// Animate

	// Move the whole video list left or right
	$("#video").animate({marginLeft:(videoIndex * -269)+"px"}, animationSpeed);
		
	// Grow the selected video image
	var selectedVideoAnimation = {marginTop:"-144px"};
	
	if($selectedVideo.hasClass("next"))
		selectedVideoAnimation.marginLeft = "0";
	else
		$("#video li.next").animate({marginLeft:"0"}, animationSpeed);
	
	$selectedVideo.animate(selectedVideoAnimation, animationSpeed);
	$nextVideo.animate({marginLeft:"256px"}, animationSpeed);
	$("img", $selectedVideo).animate({width:"512px", height:"288px"}, animationSpeed);
	
	// Move the current video image to reflect its smaller size
	var currentVideoAnimation = {marginTop:"144px"};
	if(videoIndex < dreamscopeSelectedVideo)
		currentVideoAnimation.marginLeft = (parseInt($("div.current-video").css("margin-left")) + 256) + "px";
	
	// Remove the arrows from the previous and next items
	// (This must be done after any animations on these elements have begun)
	$("#video li.next").removeClass("next");
	$("#video li.previous").removeClass("previous");
	
	// Shrink the current video
	$("div.current-video img").animate({width:"256px", height:"144px"}, animationSpeed);
	$("div.current-video").animate(currentVideoAnimation, animationSpeed, function()
	{	
// Animation complete
		
		// Swap the current video for the current video's list item
		// They will be in exactly the same place, so this will have no effect visually
		$("#video li.current").removeClass("current");
		$("div.current-video").hide();

		// Get details of the selected video
		var selectedTitle = $("span.title", $selectedVideo).text();
		var selectedImageURL = $("img:first", $selectedVideo).attr("src");
		var selectedImageRelfectionURL = selectedImageURL.replace("/main/", "/reflected/");

		// Update the current video to display the selected videos information
		$("div.current-video h1").text(selectedTitle);
		$("div.current-video img:first").attr("src", selectedImageURL);
		$("div.current-video img:last").attr("src", selectedImageRelfectionURL);
		$("div.current-video .description").css("background-image", "url("+selectedImageRelfectionURL+")");

		// Increase the current video image's size back to its original dimensions
		$("div.current-video img")
			.css("width", "512px")
			.css("height", "288px");

		// Move the current video back to its original position, remove the <img> version of the backgorund image and display it
		$("div.current-video img:last").remove();
		$("div.current-video")
			.css("margin-top", "0")
			.css("margin-left", ((videoIndex * 269) + 336)+"px")
			.show();

		// Move the selected video back to its original position, reset the image size and remove the <img> version of the background image
		// This will not be displayed because it has className 'current'
		$selectedVideo
			.addClass("current")
			.css("margin-top", "0");
		$("img", $selectedVideo)
			.css("width", "256px")
			.css("height", "144px");
		$("img:last", $selectedVideo)
			.remove();

		// Remove the margin-top style attribute if it's set to zero
		// This fixes layout issues in IE
		$("#video ul.navigation li").each(function()
		{
			var style = $(this).attr("style").replace(/margin-top: 0px;/i, "");
			$(this).attr("style", style);
		});

		// Display the video description container
		$("div.current-video .description")
			.html("")
			.show();

		// Work out the ID of the selected video
		var videoIDParts = $("#video li.current").attr("id").match(/^video([0-9]+)$/);
		var videoID = videoIDParts[1];
		
		// Display the selected videos description, lazily loaded via XML HTTP Request
		if(typeof(dreamscopeVideoData[videoID]) != "undefined")
		{
			$("div.current-video .description").html(dreamscopeVideoData[videoID].description);
			$("div.current-video .description *").hide().fadeIn();

			var videoURL = "video/" + dreamscopeVideoData[videoID].video;
			displayVideoPlayButton(videoURL);
		}
		else
		{
			jQuery.getJSON("xhr/video.php", {"v":videoID}, function(data)
			{
				if(typeof(data.error) != "undefined")
				{
					alert(data.error);
					return;
				}

				dreamscopeVideoData[data.id] = data;

				$("div.current-video .description").html(data.description);
				$("div.current-video .description *").hide().fadeIn();

				var videoURL = "video/" + data.video;
				displayVideoPlayButton(videoURL);
			});
		}

		// Restore the previous and next arrows
		$previousVideo.addClass("previous");
		$nextVideo.addClass("next");
		
		// Set parameters for the next animation
		dreamscopeSelectedVideo = videoIndex;
		dreamscopeVideoAnimating = false;
	});

}

function displayVideoPlayButton(videoURL)
{
	if(typeof(videoURL) == "undefined")
	{
		var videoIDParts = $("#video li.current").attr("id").match(/^video([0-9]+)$/);
		var videoID = videoIDParts[1];
		$.getJSON("xhr/video.php", {"v":videoID}, function(data)
		{
			if(typeof(data.error) != "undefined")
			{
				alert(data.error);
				return;
			}

			var videoURL = "video/" + data.video;
			displayVideoPlayButton(videoURL);
		});
		return;
	}

	$("div.current-video").append(
		$("<a/>")
			.hide()
			.append("Play video")
			.addClass("play-video")
			.click(function() {playVideo(videoURL);})
			.fadeIn()
	);
}

function playVideo(videoURL)
{
	$("a.play-video").remove();

	var baseURL = $("base").attr("href");

	var flashVars = {
			file:baseURL+videoURL,
			autostart:"true"
		};

	var params = {
			allowfullscreen:"true",
			wmode:"transparent"
		};

	swfobject.embedSWF(
		baseURL+'flash/player.swf',
		'video-player-flash',
		'512',
		'288',
		'8.0.0',
		false,
		flashVars,
		params
	);
}
