var isIOS = (navigator.userAgent.match(/iPhone/i) != null || navigator.userAgent.match(/iPod/i) != null || navigator.userAgent.match(/iPad/i) != null);
var isIE = (navigator.userAgent.match(/MSIE/i) != null)
var isPlaying = false;
var _gaq = _gaq || [];
var scrubber, scrubberWidth, loadedScrubber, duration, playIvl, currentVolume;
var showFullScreenButtonAfterAnimation = true;

// Initialization

$(document).ready
(
	function()
	{
		// basic setup
		
		$(document).pngFix();
		
		// setup the container and controls
		
		if(isIOS) $("#fullScreen").css("display", "none");
		
		$("#playerContainer").width(width);
		$("#playerVideo").width(width);
		$("#playerVideo").height(height);
		$(".playerControls").css("top", (height - 70) + "px");
		$("#fullScreenContainer").css("left", (width - 151) + "px");
		$("#shareContainer").css("left", (width - 84) + "px");
		$("#scrubber").width(width - ((!isIOS) ? 318 : 173));
		
		$("#playClickArea").width(width);
		$("#playClickArea").height(height);
		
		if(playBtn){
			$("#centeredPlayIcon").css("top", (height / 2) - ($("#centeredPlayIcon").height() / 2));
			$("#centeredPlayIcon").css("left", (width / 2) - ($("#centeredPlayIcon").width() / 2) + 3);
			$("#centeredPlayBackground").css("top", (height / 2) - ($("#centeredPlayBackground").height() / 2));
			$("#centeredPlayBackground").css("left", (width / 2) - ($("#centeredPlayBackground").width() / 2));
		}

		$("#loading").css("top", (height / 2) - ($("#loading").height() / 2));
		$("#loading").css("left", (width / 2) - ($("#loading").width() / 2));
		$("#loading").css("display", "none");
		
		if(nonEcom){
			$("#facebook").hide();
			$("#embed").hide();
		}
		$("#twitter").hide();
		
		if(!isIE)
		{
			$(".playerControls").css("opacity", "0");
			$(".playerControls").css("visibility", "visible");
		}
		
		// setup the scrubber
		
		scrubber = document.getElementById("scrubberTimeline");
		scrubberWidth = $(scrubber).width();
		$(scrubber).css("width", "0px");
		loadedScrubber = $("#scrubberLoadedTimeline");
		loadedScrubber.css("width", "0px");
		
		// default volume
		
		setVolume(defaultVolume, true);
		
		// populate the embed code
		
		var embedcode = '&lt;iframe src="' + document.location.href + '" width="' + width + '" height="' + height + '" style="border: none;" scrolling="no">&lt;/iframe>';
		if(document.getElementById("embedCode")){
			document.getElementById("embedCode").innerHTML = embedcode;
		}
		// auto play
		
		if(!autoPlay)
		{
			$("#imagePreview").css("display", "block");
		}
		else
		{
			play(true);
		}
				
		
		if (isIOS) {
			$("#volume").css("display", "none");
		}
		
		// setup ui event handlers
		
		if (isIOS) {
			$("#centeredPlayBackground").css("display", "none");
			$("#centeredPlayIcon").css("display", "none");
			if (autoPlay) {
				$(".playerControls").css("opacity", "300");
				$(".playerControls").css("visibility", "visible");
			} else {
				$(".playArea").click(
					function(e) {
						$(".playerControls").css("opacity", "300");
						$(".playerControls").css("visibility", "visible");
					}
				);
			}
		} else {
			$(".playArea").click(
				function(e) {
					if (!isPlaying) {
						play(false);
					}
				}
			);
			
			$("#playerContainer").hover
			(
				function(e)
				{
					if(!isIE)
					{
						if(!isIOS && isPlaying)
						{
							$("#fullScreenContainer").css("display", "block");
							swfobject.getObjectById("flashVideoPlayer").setFullScreenButtonVisibility(false);
						}
						
						var reshown = false;
						
						$(".playerControls").animate
						(
							{opacity: 1}, 
							300,
							function()
							{
								if(!reshown && isPlaying && !isIOS)
								{
									$("#fullScreenContainer").css("display", "none");
									if (showFullScreenButtonAfterAnimation) {
										swfobject.getObjectById("flashVideoPlayer").setFullScreenButtonVisibility(true);
									}
									reshown = true;
								}
							}
						);
					}
					else
					{
						if(isPlaying)
						{
							swfobject.getObjectById("flashVideoPlayer").setFullScreenButtonVisibility(true);
						}
						else
						{
							$("#fullScreenContainer").css("display", "block");
						}
						
						$(".playerControls").css("visibility", "visible");
						$("#scrubberTimeline").css("visibility", "visible");
						loadedScrubber.css("visibility", "visible");
					}
				},
				function(e)
				{
					showFullScreenButtonAfterAnimation = false;
					if(!isIE)
					{
						if(!isIOS && isPlaying)
						{
							if(!isIE) swfobject.getObjectById("flashVideoPlayer").setFullScreenButtonVisibility(false);
							$("#fullScreenContainer").css("display", "block");
						}
					
						$(".playerControls").animate({opacity: 0}, 500,
							function() {
								if(!isIOS && isPlaying) {
									showFullScreenButtonAfterAnimation = true;
								}
							}
						);
					}
					else
					{
						if(isPlaying)
						{
							swfobject.getObjectById("flashVideoPlayer").setFullScreenButtonVisibility(false);
						}
						else
						{
							$("#fullScreenContainer").css("display", "none");
						}
						
						$(".playerControls").css("visibility", "hidden");
						$("#scrubberTimeline").css("visibility", "hidden");
						loadedScrubber.css("visibility", "hidden");
					}
					
					$("#embedCodeContainer").css("display", "none");
				}
			);
		}
		
		$("#playPauseButton").click
		(
			function(e)
			{
				togglePlay();
				return false;
			}
		);
		
		$("#scrubberTimelineBg").click(
			function(e)	{
				if(isPlaying) seek((e.pageX - $(this).offset().left) / scrubberWidth * duration);
				return false;
			}
		);
		
		$("#scrubberTimeline").click(
			function(e)	{
				if(isPlaying) seek((e.pageX - $(this).offset().left) / scrubberWidth * duration);
				return false;
			}
		);
		
		loadedScrubber.click(
			function(e)	{
				if(isPlaying) seek((e.pageX - $(this).offset().left) / scrubberWidth * duration);
				return false;
			}
		);
		
		$(".volumeControl").click
		(
			function(e)
			{
				var level = Number(this.id.substr(6));
				setVolume(level);
				return false;
			}
		);
		
		$("#facebook").click
		(
			function(e)
			{
				window.open(facebookShareUrl);
				_gaq.push(["_trackEvent", "Video", "Facebook", gaEventLabel]);
				return false;
			}
		);
		
		$("#twitter").click
		(
			function(e)
			{
				window.open(twitterShareUrl);
				_gaq.push(["_trackEvent", "Video", "Twitter", gaEventLabel]);
				return false;
			}
		);
		
		$("#embed").click
		(
			function(e)
			{
				$("#embedCodeContainer").css("display", "block");
				_gaq.push(["_trackEvent", "Video", "Embed", gaEventLabel]);
				return false;
			}
		);
		
		$("#closeEmbed").click
		(
			function(e)
			{
				$("#embedCodeContainer").css("display", "none");
				return false;
			}
		);
		
	}
);

function errorPlaying() {
	$(".playArea").unbind("click");
	var messageTop = height - 30;
	var message = "<h1 style='position:absolute;left:10px;top:" + messageTop + "px;'>The required movie does not exists</h1>";
	$('#playerVideo').html(message);
}
// Player controls

function togglePlay()
{
	if(!isPlaying)
	{
		play(false);
	}
	else
	{
		pause();
	}
}

function play(autoPlaying)
{
	if(isIOS)
	{
		var video = document.getElementById("html5Video");
		video.play();
		handleDurationUpdate(video.duration);
		playIvl = setInterval
		(
			function()
			{
				if (!duration) {
					handleDurationUpdate(video.duration);
				}
				
				showLoader(video.readyState < 3);
				handleTimeUpdate(video.currentTime);
			},
			50

		);
	}
	else
	{
		if(!autoPlaying) swfobject.getObjectById("flashVideoPlayer").playVideo();
		$("#fullScreenContainer").css("display", "none");
		$("#fullScreenIcon").css("opacity", "1");
		$("#fullScreenIcon").css("filter", "alpha(opacity = 100)");
	}
	
	$("#centeredPlay").css("display", "none");
	$("#imagePreview").css("display", "none");
	$("#scrubberTimeline").css("visibility", "visible");
	loadedScrubber.css("visibility", "visible");
	$("#playIcon").css("display", "none");
	$("#pauseIcon").css("display", "block");
	$("#embedCodeContainer").css("display", "none");
	
	_gaq.push(["_trackEvent", "Video", "Play", gaEventLabel]);

	isPlaying = true;
}

function showLoader(show) {
	if (show) {
		$("#loading").css("display", "block");
	} else {
		$("#loading").css("display", "none");
	}
}

function pause()
{
	if(isIOS)
	{
		document.getElementById("html5Video").pause();
		clearInterval(playIvl);
	}
	else
	{
		swfobject.getObjectById("flashVideoPlayer").pauseVideo();
		$("#fullScreenIcon").css("opacity", "0.2");
		$("#fullScreenIcon").css("filter", "alpha(opacity = 20)");
		$("#fullScreenContainer").css("display", "block");
	}
	
	$("#centeredPlay").css("display", "block");
	$("#playIcon").css("display", "block");
	$("#pauseIcon").css("display", "none");
	$("#loading").css("display", "none");
	
	_gaq.push(["_trackEvent", "Video", "Pause", gaEventLabel]);
	
	isPlaying = false;
}

function seek(position)
{
	if(isIOS)
	{
		document.getElementById("html5Video").currentTime = position;
	}
	else
	{
		swfobject.getObjectById("flashVideoPlayer").seek(position);
	}
	handleTimeUpdate(position);
}

function setVolume(level, initializing)
{
	if(currentVolume == level) level--;
	var normalizedLevel = (level / 5);
	
	if(isIOS)
	{
		document.getElementById("html5Video").volume = normalizedLevel;
	}
	else
	{
		if(!initializing) swfobject.getObjectById("flashVideoPlayer").setVolume(normalizedLevel);
	}
	
	for(var i = 1; i <= 5; i++)
	{
		var color = (i <= level) ? "#000000" : "#b5b5b5";
		$("#volume" + i).css("background-color", color);
	}
	
	currentVolume = level;
}

// Notifications from the SWF

function handleDurationUpdate(value)
{
	duration = value;
}

function handleTimeUpdate(current)
{
	if (Math.round(current) == Math.round(duration)) {
		handleVideoEnd();
	} else {
		var w = Math.round(current / duration * scrubberWidth);
		$(scrubber).css("width", w + "px");
	}
}

function handleTimeLoadedUpdate(total, loaded) {
	var w = Math.round(loaded / total * scrubberWidth);
	loadedScrubber.css("width", w + "px");
}

//function traceText(str, append) {
//	if (append) {
//		$("#traceText").html($("#traceText").html() + "\n" + str);
//	} else {
//		$("#traceText").html(str);
//	}
//}

function handleVideoEnd()
{
	$("#centeredPlay").css("display", "block");
	$("#playIcon").css("display", "block");
	$("#pauseIcon").css("display", "none");
	_gaq.push(["_trackEvent", "Video", "PlayComplete", gaEventLabel]);
	pause();
	seek(0);
	isPlaying = false;
}



