/**
 * @author camilo
 */


var currentActiveSpot = -1;
var currentOpenSpot = -1;
var currentPlayingSpot = -1;
var currentMovieIndex = -1;
//playmovie set activeSpot
var timeOutId = -1;
var topTooltip;
var initFlashPlayer = true;
var html5VideoEnabled = !!document.createElement('video').canPlayType;
var currentPlaylist = playlist1;


//html5VideoEnabled = false;
function autoPlaySpots(){
	if ($("#wizerSpotsHolder").length > 0)
	{
		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()
{
        initFlash();
	
	
	var tooltipMouseout = function()
	{
		// clear the timeout to make sure it isnt shown
		clearTimeout($(this).attr("rel"));
		
		// remove the attribute we use to remember the timeout ref
		$(this).removeAttr("rel");
		
		// unbind thyself
		$(this).unbind("mouseout", tooltipMouseout);
	}


	$.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($.tools.tooltipTimeout);}
	};
	
	
	// wait a little to make sure that the flash functions are available to js
	setTimeout(
		function()
		{
		    //showDefaultVideo();
		    initFlash();
		}, 
	500);

	createPlaylists();

	autoPlaySpots();
	
	$(".wizerSpot").bind("mouseover", function(){
		showSpot(this);
		currentActiveSpot = $(this).attr("id");
	});		
	
	
	$(".wizerSpot").bind("click.open", function(){
		showSpot(this);
		currentActiveSpot = $(this).attr("id");
	});
	
	
	
	
	/* spot bidnings */
	$("#spot-movie1").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie1");
	});
	
	$("#spot-movie7").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie7");
	});
	
	$("#spot-movie10").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie10");
	});
	
	$("#spot-movie14").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie14");
	});
	
	$("#spot-movie8").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie8");
	});
	
	$("#spot-movie13").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie13");
	});
	
	$("#spot-movie6").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie6");
	});
	
	$("#spot-movie9").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie9");
	});
	
	$("#spot-movie12").bind("click", function(){
		currentPlaylist = playlist1;
		showMovie("movie12");
	});
	
	
	
	
	
	
	
	
	
	$(".wizerSpot").bind("mouseleave", function(){
		if (currentActiveSpot == $(this).attr("id")) {
			currentActiveSpot = -1;
			clearTimeout(timeOutId);
			timeOutId = setTimeout("autoPlaySpots()", 2000);
		}
	});
	
	$(".wizerPlaylist .playlist-control .view").each(function(){
		$(this).click(function(){
			var $this = $(this);
			var f = function(){
			    $this.hide();
			    $this.siblings("div").show();
			};
			$(this).parent().parent().find(".movies").slideDown(1000, f);
			
			// this is to make sure only one list is open simultaniously. It works by checking all other listst and close them
			$(".wizerPlaylist .movies").each(
				function()
				{
					var moviesContainer = $(this);
					if ($this.parent().parent().find(".movies")[0] != moviesContainer[0])
					{
						moviesContainer.slideUp(500, 
							function()
							{
								var controls = moviesContainer.parents(".wizerPlaylist").find(".playlist-control");
								controls.find(".view").show();
								controls.find(".close").hide();
							}
						);
					}
				}
			);
			
		    });
	    });
	
	$(".wizerPlaylist .playlist-control .close").each(function(){
		$(this).click(function(){
			var $this = $(this);
			var f = function(){
			    $this.hide();
			    $this.siblings("div").show();
			};
			$(this).parent().parent().find(".movies").slideUp(1000, f);
		    });
	    });
	
	$(".wizerDownloadSmall").bind("mousedown", function(){
		$(this).css("backgroundImage", "url('/wp-content/themes/wizerize/images/wizer/download_small_down.png')");
	});
	$(".wizerDownloadSmall").bind("mouseover", function(){
		$(this).css("backgroundImage", "url('/wp-content/themes/wizerize/images/wizer/download_small_hover.png')");
	});
		$(".wizerDownloadSmall").bind("mouseout", function(){
		$(this).css("backgroundImage", "url('/wp-content/themes/wizerize/images/wizer/download-small.png')");
	});
	
	
	$(".mail_icon").bind("mousedown", function(){
		$(this).attr("src", "/wp-content/themes/wizerize/images/wizer/mail-icon-down.png");
		$(this).blur();
	});
	$(".mail_icon").bind("mouseup", function(){
		$(this).attr("src", "/wp-content/themes/wizerize/images/wizer/mail-icon.png");
	});
	$(".mail_icon").bind("mouseover", function(){
		$(this).attr("src", "/wp-content/themes/wizerize/images/wizer/mail-icon-hover.png");
	});
	$(".mail_icon").bind("mouseout", function(){
		$(this).attr("src", "/wp-content/themes/wizerize/images/wizer/mail-icon.png");
	});
	
	
	
	$("#downloadBtn").tooltip(topTooltip).bind("mousemove",
							  function(e)
							  {
							      var tooltip = $(this).next();
								  var left = Math.round(e.pageX - tooltip.parent().offset().left + 57);
							      tooltip.css("left", left + "px");
							      tooltip.css("top", (e.pageY - 145) + "px");
							  }
	).bind("click.download", downloadMovieFromJS);
	
	$("td.padding img").tooltip(topTooltip).bind("mousemove",
		function(e)
		{
			var tooltip = $(this).next();
			tooltip.css("left", (e.pageX - tooltip.parent().offset().left + 10 ) + "px");
			tooltip.css("top", (e.pageY - tooltip.parent().offset().top + 10) + "px");
		}
	)
	
	
	// set the modal for the first movie
	$("#modalplay").find(".info-1").html("NEXT MOVIE<br><strong>\"" + movie1.title + "\"</strong><br>time: " + movie1.time)

	$("#modalplay").bind("click",
		function()
		{
			showNextMovie();	
		}
	);
	
	if (!html5VideoEnabled && (swfobject.getFlashPlayerVersion().major == 0))
	{
		$("#noFlash").show();
	}	
	
}

function createPlaylists()
{
    var lists = $("#wizerPlaylists");
    for (var i in moviePlaylists)
	{
	    var l = moviePlaylists[i];
	    var list = $("<ul class='wizerPlaylist'></ul>").attr("id", l.id);
	    list.id = l.id;
	    $("<li class='banner'><div class='text'>" + l.banner_text + "</div></li>").appendTo(list);
	    $("<li class='now-playing'></li>").appendTo(list);
	    $("<li class='playlist-control'><div class='view'>" + l.view_movie_playlist_text + "</div><div class='close'>" + l.close_movie_playlist_text + "</div></li>").appendTo(list);
	    var movies = $("<ul></ul>");
	    for (var j = 0; j <  l.array.length; j++)
		{
		    var movie = l.array[j];
		    var li = $("<li id='" + movie.id + "'></li>");
		    if (movie.isHeaderMovie) 
			{
				li.attr("class", "header");
		    }
			else 
			{
				li.attr("class", "movie");
		    }
		    var movie_link = $((movie.isMovie ? "<span class='time'>(" + movie.time + ")</span>" : "") + "<span>" + movie.title + "</span>");
		    movie_link.data("playlist", l);
		    movie_link.data("movie", movie);

			li.data("movieRef", movie);
			
		    if (movie.isMovie)
			{
			    movie_link.bind("click", function(){
			    	currentPlaylist = $(this).data("playlist");
				    showMovie($(this).parent().attr("id"));
				});

				var downloadLink = $("<a class='download'></a>");
				li.append(downloadLink);

				downloadLink.attr("rel", movie.id)
				.bind("click", downloadMovieFromJS)
				.after("<div class='toolip'>Download movie as mp4:<br/>File size " + movie.size + "MB</div>")
				.tooltip(topTooltip).bind("mousemove",
					  function(e)
					  {
					      var tooltip = $(this).next();
					      tooltip.css("left", (e.pageX - tooltip.parent().offset().left - 184) + "px");
					      tooltip.css("top", (e.pageY - 130) + "px");
					  }
				);
				
				
			}
		    else if (movie.playMovieInstead != 'undefined')
			{
			    movie_link.attr("rel", movie.playMovieInstead);
			    movie_link.click(function(){
				    showMovie($(this).attr("rel"));
				});
			}
		    movie_link.appendTo(li);
		    li.appendTo(movies);
		}
	    $("<li class='movies'></li>").append(movies).appendTo(list);
	    $("<li class='download-flash'><a href='" + l.download_flash + "' target='_blank'>Download all movies</a></li>").appendTo(list);
	    /*$("<li class='download-wmv'><a href='" + l.download_wmv + "'>Download all movies as Windows Media Videos</a></li>").appendTo(list);*/
	    $("<li class='download-pdf'><a href='" + l.download_pdf + "' target='_blank'>Download PDF booklet</a></li>").appendTo(list);
	    $("<li class='link-booklet'><a href='" + l.link_booklet + "' target='_blank'>Watch our Interactive Online Booklet</a></li><div class='clr'></div>").appendTo(list);
	    
	    $("<div class='wizerPlaylistTop'></div>").appendTo(lists);
	    list.appendTo(lists);
	    $("<div class='wizerPlaylistBottom'></div>").appendTo(lists);
	}
}

function nowPlaying(movie_id, playing)
{
    if (playing == null)
	playing = 'Now playing';

    var li = $("#" + movie_id);
    
    var movie = currentPlaylist.movies[movie_id];
    $(".now-playing").each(function(){
	    $(this).hide();
	});
    var now_playing = li.parent().parent().parent().find(".now-playing");
    now_playing.show();
    now_playing.html("<img src='" + movie.image + "' alt='' /><div class='holder'><div class='info-1'>" + playing + "</div><div class='info-2'>\""
		     + movie.title + "\"</div><div class='info-3'><span>"
		     + movie.time + "</span>|<a href='#'>Download movie</a></div></div><div class='clr'></div>" );
	
	now_playing.find(".info-3").data("movieRef", movie).find("a").bind("click.download", downloadMovieFromJS);
	
	
}

function showMovie(listItemId)
{
	var currentMovie = currentPlaylist.movies[listItemId];//eval("movies."+listItemId);
	
	
	if (!html5VideoEnabled)
	{
    	renderSyntasePlayer();
    }
	else
	{
		$("#videoControls").data("movieRef", currentMovie);
	}
    //onsole.log(currentPlaylist.movies, listItemId);

	currentMovieIndex = currentMovie.index;
	loadVideo(currentMovie.url, currentMovie.desc, currentMovie.time, currentMovie.downloadUrl, currentMovie.size);
	nowPlaying(listItemId);
	
	try 
	{
		// track events
		pageTracker._trackEvent('Videos', currentMovie.title);
	}
	catch (err){}

	$(".wizerListItemCurrent").each(function(){
		$(this).removeClass("wizerListItemCurrent");
	    });
	$(".wizerListCurrentMovie").each(function(){
		$(this).removeClass("wizerListCurrentMovie");
	    });

	if (currentMovie.isMovie)
	    $("#" + listItemId).addClass("wizerListCurrentMovie");
	else
	    $("#"+listItemId).addClass("wizerListItemCurrent");
	
	//animate spot if it exist a spot.
	if (currentMovie.isSpot) {
		$(".wizerOverSelectedSpot").remove();
		var selectedImgOver = $("<img src='/wp-content/themes/wizerize/images/wizer/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");
		$(".wizerSpot").unbind("click.open");
		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");
			});	
			$(".wizerSpot").bind("click.open", 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()
{
    if (initFlashPlayer)
	{
	    $(".wizerPlayer #noFlashContent").show();
	    swfobject.embedSWF
		(
		 "/wp-content/themes/wizerize/swf/wizerplayer.swf?version=100903.4",
		 "wizerPlayerContainer",
		 "438",
		 "285",
		 "9.0.0",
		 "/wp-content/themes/wizerize/swf/expressInstall.swf",
		 {},
		 {wmode: "opaque", allowscriptaccess: "always", swliveconnect: "true", allowfullscreen: "true"},
		 {id: "wizerPlayer" , name: "wizerPlayer"}
		 );
	    initFlashPlayer = false;
	}

}

function initFlash()
{
    var m = movie1; //movieArray[0];
    $("#flash-splash .info-1").html("NEXT MOVIE<br /><strong>" + m.title + "</strong><br />time: " + m.time);
    nowPlaying(m.id, "Next Movie");
    $("#flash-splash").click(function(){
	    showDefaultVideo();
	});
}

function showDefaultVideo()
{
	try 
	{
	    var firstMovie = movieArray[0];
	    //var firstMovie = moviePlaylists[0].movies[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 (!html5VideoEnabled)
	{
		if (swfobject.getObjectById("wizerPlayer") != null)
		{
		    /*	    var obj = swfobject.getOjbectById("wizerplayer");
			    var i = 1;*/
			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
			)
			
		}
	}
	else
	{
		loadHtmlVideoMovie(url, size, title, time, downloadUrl);
	}
}

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()
{
	$("#modalplay").hide();
	
	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()
{
	var movie = $(this).parent().data("movieRef");
	var movieUrl = movie.url.substring(0, movie.url.lastIndexOf(".flv")) + ".mp4";
	movieUrl = "/wp-content/themes//wizerize/media/movies/" + movieUrl.substr(movieUrl.lastIndexOf("/"));
	location.href = wordpressThemeUrl + "download.aspx?file=" + movieUrl;
}


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);
	}
}


