/**
 * @author camilo
 */


var currentActiveSpot = -1;
var currentOpenSpot = -1;
var currentPlayingSpot = -1;
var currentMovieIndex = -1;
//playmovie set activeSpot
var timeOutId = -1;
var topTooltip;

function autoPlaySpots(){
	if (currentActiveSpot == -1 && currentPlayingSpot == -1) {
	
		if (currentOpenSpot == $($("#wizerSpotsHolder > .wizerSpot")[$("#wizerSpotsHolder > .wizerSpot").length - 1]).attr("id") || currentOpenSpot == -1) {
			showCurrentSpot($($("#wizerSpotsHolder > .wizerSpot")[0]).attr("id").substring(5));
		}
		else 
			showCurrentSpot($("#" + currentOpenSpot).next().attr("id").substring(5));
	}
	else {
		if (currentPlayingSpot != -1 && currentActiveSpot == -1) {
			if (currentOpenSpot != currentPlayingSpot) {
				showCurrentSpot(currentPlayingSpot.substring(5));
			}
		}
	}
	timeOutId = setTimeout("autoPlaySpots()", 10000);
	
}

function wizerInit()
{
	renderSyntasePlayer();
	
	
	var tooltipMouseout = function()
	{
		// clear the timeout to make sure it isnt shown
		clearTimeout(jQuery(this).attr("rel"));
		
		// remove the attribute we use to remember the timeout ref
		jQuery(this).removeAttr("rel");
		
		// unbind thyself
		jQuery(this).unbind("mouseout", tooltipMouseout);
	}


	jQuery.tools.addTipEffect("delayedShow", 
		function() { 

			clearTimeout(this.getTrigger().rel);
			var timeoutRef = setTimeout(
				CallbackProxy(this, function()
				{
					var opacity = this.getConf().opacity; 
       				this.getTip().css({opacity:0}).animate({opacity:opacity}, 200).show(); 
				})
				, 200);
			this.getTrigger().attr("rel", timeoutRef);
			this.getTrigger().bind("mouseout", tooltipMouseout);	
		}, 

		function() { 
			this.getTip().hide(); 
		}
	);
	
	topTooltip =  { 
		    position: ['top', 'left'], 
			delay: 30, 
		    offset: [4, 30],
			effect: "delayedShow",
			onBeforeHide: function(){clearTimeout(jQuery.tools.tooltipTimeout);}
	};
	
	
	// wait a little to make sure that the flash functions are available to js
	setTimeout(
		function()
		{
			showDefaultVideo();
		}, 
	500);
	var count = 0;
	for (var i in movies) {
		count++;
		createListItem(movies[i], count);
	}

	autoPlaySpots();
	$(".wizerSpot").bind("mouseover", function(){
		showSpot(this);
		currentActiveSpot = $(this).attr("id");
	});		
	$(".wizerSpot").bind("click", function(){
		showMovie($(this).attr("id").substring(5));
	});
	$(".wizerSpot").bind("mouseleave", function(){
		if (currentActiveSpot == $(this).attr("id")) {
			currentActiveSpot = -1;
			clearTimeout(timeOutId);
			timeOutId = setTimeout("autoPlaySpots()", 2000);
		}
	});
	$(".wizerDownloadSmall").bind("mousedown", function(){
		$(this).css("backgroundImage", "url('media/images/download_small_down.png')");
	});
	$(".wizerDownloadSmall").bind("mouseup", function(){
		$(this).css("backgroundImage", "url('media/images/download-small.png')");
	});
	$(".wizerDownloadSmall").bind("mouseover", function(){
		$(this).css("backgroundImage", "url('media/images/download_small_hover.png')");
	});
		$(".wizerDownloadSmall").bind("mouseout", function(){
		$(this).css("backgroundImage", "url('media/images/download-small.png')");
	});
	
	
	$(".mail_icon").bind("mousedown", function(){
		$(this).attr("src", "media/images/mail-icon-down.png");
		$(this).blur();
	});
	$(".mail_icon").bind("mouseup", function(){
		$(this).attr("src", "media/images/mail-icon.png");
	});
	$(".mail_icon").bind("mouseover", function(){
		$(this).attr("src", "media/images/mail-icon-hover.png");
	});
	$(".mail_icon").bind("mouseout", function(){
		$(this).attr("src", "media/images/mail-icon.png");
	});
	
	
	
	
	
	
	
	
}




function createListItem(movie, count)
{
	var listLink = $("<li id='"+movie.id+"' class='wizerListItemDefault' />");
	if (count == 1) listLink.addClass("wizerListItemFirst");
	if(movie.isHeaderMovie){ listLink.addClass("wizerListItemBold");}
	
	var movieLink = $("<span>"+movie.title+"</span>").appendTo(listLink);
	if (movie.isMovie) {
		movieLink.bind("click", function(){
			showMovie($(this).parent().attr("id"));
		});
		
		$("<a class='wizerDownloadSmall'></a>").appendTo(listLink).data("id", movie.id).bind("click", downloadMovieFromJS)
			.after(movie.wmv != -1 ? 
				"<div class='toolip'>Download movie in higher resolution:<br/>File size " + movie.size + "MB</div>" :
				"<div class='toolip'>This movie isn´t<br/> available for download</div>"
			)
			.tooltip(topTooltip).bind("mousemove", 
			function(e)
			{
				var tooltip = jQuery(this).next();
				tooltip.css("left", (e.pageX - tooltip.parent().offset().left - 186) + "px");
				tooltip.css("top", (e.pageY - 84) + "px");
			}
		);
		
		
		$("<span class='wizerListItemTime'>(" + movie.time + ")</span>").appendTo(listLink).bind("click", function(){
			showMovie($(this).parent().attr("id"));
		});
	}else if(typeof movie.playMovieInstead != 'undefined'){
		movieLink.attr("rel", movie.playMovieInstead)
		movieLink.bind("click", function(){
			showMovie($(this).attr("rel"));
		});
	}
	
	listLink.appendTo($("#wizerPlaylist"));
}

function showMovie(listItemId)
{	
	var currentMovie = eval("movies."+listItemId);
	currentMovieIndex = currentMovie.index;
	loadVideo(currentMovie.url, currentMovie.desc, currentMovie.time, currentMovie.downloadUrl, currentMovie.size);		
	
	try 
	{
		// track events
		pageTracker._trackEvent('Videos', currentMovie.title);
	}
	catch (err){}
	
	if($(".wizerListItemCurrent")){
		$(".wizerListItemCurrent").removeClass("wizerListItemCurrent");
	}
	
	$(".wizerPlayIcon").remove();
	$("#"+listItemId).prepend("<img class='wizerPlayIcon' src='media/images/play.png' alt='play' />");

	
	$("#"+listItemId).addClass("wizerListItemCurrent");
	
	//animate spot if it exist a spot.
	if (currentMovie.isSpot) {
		$(".wizerOverSelectedSpot").remove();
		var selectedImgOver = $("<img src='media/images/activeSpot.png' class='wizerOverSelectedSpot' />");
		selectedImgOver.css("height", "32px");
		
		
		if (currentOpenSpot != "spot-" + currentMovie.id) {
			currentPlayingSpot = "spot-" + currentMovie.id;
			selectedImgOver.appendTo($(".wizerList", $("#spot-" +  currentMovie.id)));
			showCurrentSpot(currentMovie.id);
		}
		else
		{
			currentPlayingSpot = "spot-" + currentMovie.id;
			selectedImgOver.appendTo($(".wizerList", $("#spot-" +  currentMovie.id)));
			showFadeOverForSelectedSpot(currentMovie.id);
		}
	}
	else
	{
		$(".wizerOverSelectedSpot").remove();
		currentPlayingSpot =-1;
	}
}
/**
 * 
 * 
 * @param {Object} movieId
 */
function showCurrentSpot(movieId)
{
	var spot = $("#spot-"+movieId);
	//if(spot)
	//{
		
		currentOpenSpot = "spot-"+movieId;
		///if ($(".wizerSpotInfoHolder", spot).height() < 10) {// if its not spot is already open
		
		//$(".wizerSpotInfoHolder", $(".wizerSpot")).stop(true);//stoppar alla
		$(".wizerSpotCurrent .wizerSpotInfoHolder").animate({height:0});//gömmer alla
		$(".wizerSpotCurrent").removeClass("wizerSpotCurrent"); // den nuvarande öppna icke aktiv
		
		
		if ($(".wizerOverSelectedSpot")) {
				if ("spot-" + movieId != currentPlayingSpot) {
					
					$(".wizerOverSelectedSpot").animate({
						height: "32px"
					});
				}
			}
				
		//spot.stop(true);//stannar den som ska visas , då den inte ska gömmas
		//$(".wizerOverSelectedSpot").stop(true);
		
		spot.addClass("wizerSpotCurrent");
		$(".wizerSpot").unbind("mouseover");
		var innerToAnimate = $("#spot-" +movieId + " .wizerSpotInfoHolder");
		
		// shows the spot that should be shown
		
		innerToAnimate.animate({
				height:  $("#spot-"+movieId+ " .wizerSpotInfo").height() +"px"
		}, function(){
			$(".wizerSpot").bind("mouseover", function(){
				showSpot(this);
				currentActiveSpot = $(this).attr("id");
			});	
			
		});
		showFadeOverForSelectedSpot(movieId);
		//}
	//}	
}
function showFadeOverForSelectedSpot(movieId)
{
	if ($(".wizerOverSelectedSpot")) {			
		if ("spot-" + movieId == currentPlayingSpot) {
			$(".wizerOverSelectedSpot").animate({
				height: ($(".wizerSpotInfo", $("#spot-"+movieId)).height() + 32) + "px",
				duration: 10100,
				queue: false
			});
		}
	}
	
}
/***
 * @param {Object} obj
 */
function showSpot(obj)
{
	if($(obj).attr("class").indexOf("Current") < 0)
	{
	 	showCurrentSpot($(obj).attr("id").substring(5));
	}	
}
function activateSpot(obj)
{
	if($(obj).attr("class").indexOf("Current") < 0)
	{
	 	showMovie($(obj).attr("id").substring(5));
	}	
}
/***
 * Creates an spot and adds it to the dom
 * 
 * @param {Object} movie
 */
function createSpotItem(movie)
{
/*	var spotItem = $("<div id='spot"+movie.id+"' class='wizerSpot' />").append("<h1>"+movie.title+"</h1>");
	var hiddenInfoHolder = $('<div class="wizerSpotInfoHolder" />');
	var hiddenInfo = $("<div class='wizerSpotInfo' />").appendTo(hiddenInfoHolder);
	if(movie.img != -1)	$("<img src='"+movie.img+"' />").appendTo(hiddenInfo);
	$("<p>"+ movie.desc + "</p>").appendTo(hiddenInfo);
	hiddenInfoHolder.appendTo(spotItem);
	spotItem.appendTo($('#wizerSpotsHolder'));*/
}



/****
 * Video part
 * 
 */
function renderSyntasePlayer()
{
	jQuery(".wizerPlayer #noFlashContent").show();
	swfobject.embedSWF
	(
		"media/swf/wizerplayer.swf?version=090920", 
		"wizerPlayerContainer", 
		"438", 
		"367", 
		"9.0.0", 
		"meda/swf/expressInstall.swf", 
		{}, 
		{wmode: "opaque", allowscriptaccess: "always", swliveconnect: "true", allowfullscreen: "true"}, 
		{id: "wizerPlayer" , name: "wizerPlayer"}
	);

}

function showDefaultVideo()
{
	try 
	{
		var firstMovie = movieArray[0];
		//currentMovieId = movieArray[0].id;
		showMovie(firstMovie.id);
	}
	catch(err)
	{
		alert(movieArray);
	}
	//loadVideo(firstMovie.url, firstMovie.desc, firstMovie.time, firstMovie.downloadUrl);
	//showMovie(movie.id);
}

function loadVideo(url, title, time, downloadUrl, size)
{
	if (swfobject.getObjectById("wizerPlayer") != null)
	{
		if (swfobject.getObjectById("wizerPlayer").loadVideo != null) 
		{
			swfobject.getObjectById("wizerPlayer").loadVideo(url, title, time, downloadUrl, size);
		}
		else
		{
			setTimeout(
				function()
				{
					loadVideo(url, title, time, downloadUrl);
				}, 500
			)
			
		}
	}
	else
	{
		setTimeout(
			function()
			{
				loadVideo(url, title, time, downloadUrl);
			}, 500
		)
		
	}
}

function showCuePoint(data)
{
	//console.log(data);
}
function getNextMovieInfo()
{

	console.log("0");
	console.log(currentMovieIndex);
	console.log(movieArray);
	if (currentMovieIndex + 1 < movieArray.length)
	{
		console.log(".5 - " + currentMovieIndex);
		var nextMovie = movieArray[currentMovieIndex + 1];
		console.log("1");
		if (!nextMovie.isMovie) nextMovie = movieArray[currentMovieIndex + 2];
		console.log(nextMovie);
		return {url: nextMovie.url, title: nextMovie.title, url: nextMovie.downloadUrl, end: false};
	}
	else
		return {end: true}

	
}


function showNextMovie()
{
	setTimeout(
		function()
		{
			if (currentMovieIndex + 1 < movieArray.length) 
			{
				var nextMovie = movieArray[currentMovieIndex + 1];
				if (!nextMovie.isMovie) 
				{
					nextMovie = movieArray[currentMovieIndex + 2];
				}
				showMovie(nextMovie.id);
				//loadVideo(nextMovie.url, nextMovie.desc, nextMovie.time, nextMovie.downloadUrl)
			}
		}
	, 100);
}


function downloadMovieFromJS()
{
	//alert("This movie isnt avalailable for download yet.");
	//return false;
	var movie = movies[jQuery(this).data("id")];
	
	if (movie.wmv != -1)
	{
		location.href = "download.aspx?file="+movie.wmv;
	}
	else
	{
		alert("This movie isnt avalailable for download yet.")
	}
}


function downloadMovie()
{
//	alert("This movie isnt avalailable for download yet.");
//return false;

	if (movieArray[currentMovieIndex].wmv != -1)
	{
		return true;
		//location.href = "download.aspx?file="+movieArray[currentMovieIndex].wmv;
	}
	else
	{
		alert("This movie isnt avalailable for download yet.");
		return false;
	}
}

function reportError(message)
{
	console.log("ERROR: " + message)
}

 /**
  * Create a proxy for functions so that they run in the desired scope with all its arguments intact
  * 
  * @param {Object} scope The scope defines where the function should be run
  * @param {Object} functionRef - The actuall function
  * @param {Object} args Any additional arguments that should be passed alongside any other arguments sent by the trigger
  * @example CallbackProxy(this, this.testMe); would retrun a function that will run testMe() inside "this".
  */ 
CallbackProxy = function(scope, functionRef, args)
{
	return function()
	{
		var argsList = []
		for(var i = 0; i < arguments.length; i++)
		{
			argsList.push(arguments[i]);
		}
		if (args != null) argsList.push(args);
		functionRef.apply(scope, argsList);
	}
}

