function thisMovie(movieName)
{
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

/*  for ie compatibility  */

if (!(console instanceof Object)) 
    var console = {
        log: function (a) {
            
        }
    }


function PresentationPlayer(presentation)
{
	this.SHEET_CHANGE = "sheetChange";
	this.PLAYER_INIT = "playerInit";
	
	this.presentation = presentation;
	
	this.currentSheetIndex = -1;
	this.listeners = new Array();
	
	this.currentSheet = null;
	this.prevSheet = null;
	
	this.audioOn = true;
	
	this.changing = false;
	this.autoPlay = false;
	this.autoPlayTime = 5;
	$("#autoPlayInput").val(this.autoPlayTime);
	this.autoPlayTimeOut = null;
	
	this.currentPreloading = null;
}

PresentationPlayer.prototype.constructor = PresentationPlayer;

/**
 * Inicjuje player
 */
PresentationPlayer.prototype.init = function(sheets)
{
	console.log('Init PresentationPlayer');
	
	this.sheets = sheets;
	
	if(this.presentation.sound)
	{
		var audioHtml = "";
		var audioPath = "";
		
		if (mode=='local')
		{
			audioPath = "data/mp3/" + this.presentation.sound;
		}else{
			audioPath = "/customers/edukator/web/presentation/data/sound/" + this.presentation.sound;
		}

		if(browser.toLowerCase() == "safari")
		{
			audioHtml = "<audio id=\"presentationAudio\" autoplay=\"autoplay\"><source src=\"" + audioPath + "\"></audio>";
		}else{
			//setTimeout('play("' + audioPath + '")',1000);
			
			var ac = '<object id="swfPlayer"  type="application/x-shockwave-flash" data="'+dataPath+'data/audioPlayer/audioPlayer.swf"  width="1" height="1">';
			ac += '<param name="AllowScriptAccess" value="always" />'; 
			ac += '<param name="FlashVars" value="url=' + audioPath + '" /></object>';
			
			$("#audioMp3Player").append(ac);
		}
		
		$("#audioC").html(audioHtml);
		
		if(browser.toLowerCase() == "safari")
		{
			// Funkcja loopujaca audio
			document.getElementById('presentationAudio').addEventListener('ended', function(){this.currentTime = 0;}, false);
		}
	}else{
		$("#audioButton").css("display", "none");
	}
	
	this.dispathEvent(this.PLAYER_INIT, null);
}

/**
 * Przypisuje listener dla zdarzenia
 */
PresentationPlayer.prototype.addEventListener = function(eventType, method)
{
	if(!this.listeners[eventType])
		this.listeners[eventType] = new Array();

	this.listeners[eventType].push(method);
}

/**
 * Rozsyla zdarzenie
 */
PresentationPlayer.prototype.dispathEvent = function(eventType, e)
{
	if(this.listeners[eventType])
	{
		for(var i=0; i<this.listeners[eventType].length; i++)
		{
			var f = this.listeners[eventType][i];
			f(e);
		}
	}
}

/**
 * Pokazuje slajd o podanym Indexie
 */
PresentationPlayer.prototype.changeSheet = function(sheetIndex)
{
	if(this.changing)
		return;

	if(this.currentSheetIndex == sheetIndex)
		return;
	
	clearTimeout(this.autoPlayTimeOut);
	
	if(this.currentSheet && this.currentSheet.sound)
	{
		//TUTAJ
	}
	this.changing = true;
	
	// Aktualny staje sie poprzednim slajdem
	this.prevSheet = this.currentSheet;
	
	// Index i instancja aktualnego slajdu
	this.currentSheetIndex = sheetIndex;
	this.currentSheet = this.sheets[this.currentSheetIndex];
	//alert(this.currentSheet.autoPlayTime);
	// Usuniecie tagu z dzwiekiem dla slajdu
	$("#sheetAudioC").html("");
	
	var containerHtml = "<div id=\"sheet_" + this.currentSheet.id + "\" class=\"sheet\">";
	
	containerHtml += "<div id=\"textplace\" class=\"toRemove\">" + unescape(this.currentSheet.txt) + "</div>";
	
	if (mode == 'local') {
		containerHtml += "<img src=\"data/"+this.currentSheet.path+"\"/>";
	} else {
		//containerHtml += "<object type=\"image/svg+xml\" data=\"" + this.currentSheet.path + "\" style=\"overflow:hidden;width:" + this.presentation.width + "px;height:" + this.presentation.height + "px;\"/>";
		containerHtml += "<img src=\""+this.currentSheet.path+"\"/>";
	}
	
	
	// TODO: Doroobic dla local
	if(mode == 'local')
	{
	
	}else{
		if(this.currentSheet.images)
		{
			for(var i=0; i<this.currentSheet.images.length; i++)
			{
				//containerHtml += "<img src=\"http://media.edukator.pl/customers/edukator/web/movie/data/png/zoom/" + this.currentSheet.images[i].path + ".png\">";
			}
		}
	}
	
		
	//containerHtml += "<img src=\"" + this.currentSheet.path + "\"/>";
	containerHtml += "</div>";
	
	$("#sheetsContainer").append(containerHtml);
	
	this.currentSheet.container = $("#sheet_" + this.currentSheet.id);
	
	console.log('Change sheet: ' + sheetIndex);
	
	this.showCurrentSheet();
}

PresentationPlayer.prototype.showCurrentSheet = function()
{
	this.currentSheet.container.css("display", "block");
	
	this.currentSheet.show();
}

PresentationPlayer.prototype.removePrevSheet = function()
{
	if(this.prevSheet)
	{
		this.prevSheet.container.remove();
		this.prevSheet = null;
	}
	
	this.changing = false;
	this.dispathEvent(this.SHEET_CHANGE, {sheet:this.sheets[this.currentSheetIndex], sheetIndex:this.currentSheetIndex});
}

PresentationPlayer.prototype.showCurrentSheetCompleteHandler = function()
{
	setTimeout("player.removePrevSheet()", 100);
	
	//player.removePrevSheet();
	
	// FILMY
	if(this.currentSheet.movies.length > 0)
	{
		for(var i=0; i<this.currentSheet.movies.length; i++)
		{
			var movie = this.currentSheet.movies[i];
			var playerHtml = "";
                        if(movie.type == "YTlink")
                            var style = "position:absolute;left:" + movie.x + "px;top:" + movie.y + "px; width:" + movie.w + "px; height:" + movie.h + "px;";
                        else if(movie.type == "file")
                            var style = "position:absolute;left:" + movie.x + "px;top:" + movie.y + "px; width:" + movie.w + "px; height:" + movie.h + "px;";
			
			if(movie.type == "YTlink")
			{
				playerHtml = "<iframe style=\"" + style + "\" src=\"http://www.youtube.com/embed/" + movie.file + "?wmode=transparent&autoplay=" + (this.autoPlay ? "1" : "0") + "\" frameborder=\"0\" allowfullscreen></iframe>";
			}else if(movie.type == "file")
			{       if (mode=='local') {
                                    playerHtml = "<video style=\"" + style + "background-color: #000;\" controls=\"controls\"><source src=\"data/videos/" + movie.file + ".mp4\" type=\"video/mp4\" />Your browser does not support the video tag.</video>";
//                                    playerHtml = "<a style=\"" + style + " display:block\" href=\"data/videos/" + movie.file + ".flv\" id=\"player" + movie.id + "\"></a>";
                                } else {
                                    if(browser.toLowerCase() != "safari")
                                    {
                                            playerHtml = "<a style=\"" + style + " display:block\" href=\"http://"+serverName+"/customers/edukator/web/movie/data/flv/" + movie.file + ".flv\" id=\"player" + movie.id + "\"></a>";
                                    }else{
                                            // Sciezka do pliku jest w : movie.file
                                            playerHtml = "<video style=\"" + style + "\" controls=\"controls\"><source src=\"http://"+serverName+"/customers/edukator/web/movie/data/mp4/" + movie.file + ".mp4\" type=\"video/mp4\" />Your browser does not support the video tag.</video>";
                                    }    
                                }
			}
			
			this.currentSheet.container.append(playerHtml);
			
			if(movie.type == "file")
			{
				if(browser.toLowerCase() != "safari")
				{
					if (mode=="local") {
						//flowplayer("player" + movie.id, "data/flowplayer/flowplayer-3.2.7.swf", {clip: {wmode:"transparent",autoPlay: this.autoPlay, wmode:"transparent", autoBuffering: true}, wmode:"transparent", key: "#@ff2637341d767104b82"});
					} else {
						flowplayer("player" + movie.id, "customers/edukator/global/data/flowplayer/flowplayer.commercial-3.2.7-2.swf", {clip: {wmode:"transparent",autoPlay: this.autoPlay, wmode:"transparent", autoBuffering: true}, wmode:"transparent", key: "#@ff2637341d767104b82"});
					}
				}
			}
		}
	}
	
	// FILMY CHEMICZNE
	if(this.currentSheet.chemMovies.length > 0)
	{
		for(var i=0; i<this.currentSheet.chemMovies.length; i++)
		{
			var movie = this.currentSheet.chemMovies[i];
			var playerHtml = "";
			var style = "position:absolute;left:" + movie.x + "px;top:" + movie.y + "px; width:" + movie.w + "px; height:" + movie.h + "px;";
			
			if(browser.toLowerCase() != "safari")
			{
				playerHtml = "<a style=\"" + style + " display:block\" href=\"http://media.edukator.pl/customers/edukator/web/movie/data/flv/" + movie.file + ".flv\" style=\"display:block;width:425px;height:300px;\" id=\"chemPlayer" + movie.id + "\"></a>";
			}else{
				// Sciezka do pliku jest w : movie.file
				playerHtml = "<video style=\"" + style + "\" controls=\"controls\"><source src=\"http://media.edukator.pl/customers/edukator/web/movie/data/mp4/" + movie.file + ".mp4\" type=\"video/mp4\" />Your browser does not support the video tag.</video>";
			}
			
			this.currentSheet.container.append(playerHtml);

			if(browser.toLowerCase() != "safari")
			{
				if (mode!="remote") {                               
					flowplayer("chemPlayer" + movie.id, "data/flowplayer/flowplayer-3.2.7.swf", {clip: {wmode:"transparent",autoPlay:true, onBeforeFinish: function() {return false; }, autoBuffering: true, wmode:"transparent"}, wmode:"transparent", key: "#@ff2637341d767104b82"});
				} else {
					flowplayer("chemPlayer" + movie.id, "customers/edukator/global/data/flowplayer/flowplayer.commercial-3.2.7-2.swf", {clip: {wmode:"transparent",autoPlay:true, onBeforeFinish: function() {return false; }, autoBuffering: true, wmode:"transparent"}, wmode:"transparent", key: "#@ff2637341d767104b82"});
				}
			}
		}
	}
	
	this.currentSheet.container.append("<div id=\"textplace\">" + unescape(this.currentSheet.txt) + "</div>");
	$(".toRemove").remove();
	
	// AUDIO DLA SLAJDU
	if(this.currentSheet.sound)
	{
		var audioHtml = "";
		var audioPath = "";

		if (mode=='local')
			audioPath = "data/mp3/" + this.currentSheet.sound;
		else
			audioPath = "/customers/edukator/web/presentation/data/sound/" + this.currentSheet.sound;
	
		if(browser.toLowerCase() == "safari")
		{
			audioHtml = "<audio id=\"sheetAudio\" autoplay=\"autoplay\"><source src=\"" + audioPath + "\"></audio>";
		}else{
			audioHtml = '<object id="swfPlayer2" type="application/x-shockwave-flash" data="' + dataPath + 'player_mp3_mini.swf" width="200" height="20" >';
			audioHtml += '<param name="movie" value="{$config->getAppPath()}web/presentation/data/player_mp3_mini.swf" />';
			audioHtml += '<param name="AllowScriptAccess" value="always" /> ';
			audioHtml += '<param name="FlashVars" value="mp3=' + escape(audioPath) + '&autoplay=1" />';
			audioHtml += '<param value="#000000" name="bgcolor"/>';  
			audioHtml += '</object>';
		}
		
		$("#sheetAudioC").html(audioHtml);
	}
	
	if(this.autoPlay && this.currentSheetIndex < this.sheets.length - 1)
	{
		var t = this.autoPlayTime;
		
		if(this.currentSheet.autoPlayTime)
			t = this.currentSheet.autoPlayTime + 5;
		
		t *= 1000;
		
		this.autoPlayTimeOut = setTimeout("player.next()", t);
	}
}

/**
 * Pokazuje nastepny slajd
 */
PresentationPlayer.prototype.next = function()
{
	if(this.currentSheetIndex < this.sheets.length - 1)
	{
		this.changeSheet(this.currentSheetIndex + 1);
	}
}

/**
 * Pokazuje poprzedni slajd
 */
PresentationPlayer.prototype.prev = function()
{
	if(this.currentSheetIndex > 0)
	{
		this.changeSheet(this.currentSheetIndex - 1);
	}
}

/**
 * Ładuje do niewidocznego kontenera wszystkie slajdy by znalazły się w cache przegladarki
 */
PresentationPlayer.prototype.startPreload = function()
{
	for(var i=0; i<this.sheets.length; i++)
	{
		var sheet = this.sheets[i];
		
		if(!sheet.preloaded && this.currentSheetIndex != i)
		{
			this.currentPreloading = sheet;
			$("#imagePreloader").attr("src", sheet.path).load(function(){player.imagePreloadHandler()}).error(function(){player.imagePreloadHandler()});
			
			console.log("Preloading: " + this.currentPreloading.path);
			return;
		}
	}
	
	$("#imagePreloader").remove();
}

PresentationPlayer.prototype.imagePreloadHandler = function()
{
	this.currentPreloading.preloaded = true;
	this.startPreload();
}

/**
 * Zmienia tryb autoodtwarzania
 */
PresentationPlayer.prototype.switchAutoPlay = function()
{
	this.autoPlay = !this.autoPlay;
	
	var autoPlayHtml = "";
	
	if(this.autoPlay)
	{
		clearTimeout(this.autoPlayTimeOut);
		this.autoPlayTimeOut = setTimeout("player.next()", this.autoPlayTime * 1000);
		autoPlayHtml = "Wyłącz autoodtwarzanie";
		$("#autoPlayTimeStepper").css("display", "block");
		$("#autoPlay").html(autoPlayHtml);
	}else{
		clearTimeout(this.autoPlayTimeOut);
		autoPlayHtml = "Włącz autoodtwarzanie";
		$("#autoPlayTimeStepper").css("display", "none");
		$("#autoPlay").html(autoPlayHtml);
	}
}

PresentationPlayer.prototype.updateAutoPlayTime = function()
{
	if($("#autoPlayInput").val() <= 0)
	{
		$("#autoPlayInput").val(1);
	}
	this.autoPlayTime = $("#autoPlayInput").val();
}

PresentationPlayer.prototype.toggleAudio = function()
{
	thisMovie("swfPlayer").toggleAudio("");
	
	//if(browser.toLowerCase() == "safari")
	//{
		var audioPlayer = document.getElementById('presentationAudio');
		
		if(this.audioOn) {
			if(browser.toLowerCase() == "safari")
			{
				audioPlayer.pause();
			}else{
				pause();
			}
		} else {
			if(browser.toLowerCase() == "safari")
			{
				audioPlayer.play();
			}else{
				play("/customers/edukator/web/presentation/data/sound/"+this.presentation.sound);
			}
		}
			
	//}
	
	this.audioOn = !this.audioOn;
}

//////////////////////////////////////// PREZENTACJA /////////////////////////////////////

function Presentation(id, width, height, sound)
{
	this.id = id;
	this.width = width;
	this.height = height;
	this.sound = sound;
}

Presentation.prototype.constructor = Presentation;

//////////////////////////////////////// SLAJD /////////////////////////////////////

function Sheet(id, sheetAnimation, movies, chemMovies, images, sound, txt)
{
	this.id = id;
	this.preloaded = false;
	this.container = null;
	this.animation = sheetAnimation;
	this.movies = movies;
	
	var movie = this.getLongestMovie();
	if(movie)
		this.autoPlayTime = movie.duration; 
	this.sound = sound;
	this.chemMovies = chemMovies;
	this.txt = txt;
	this.images = images;

	if (mode == 'local')
	{
		this.path = dataPath + "sheets/sheet_" + player.presentation.id + "_" + this.id + "_zoom" + ".png";
	}else{
		this.path = dataPath + "sheets_png/sheet_" + player.presentation.id + "_" + this.id + "_zoom" + ".png?rand=" + Math.random();
	}
}

Sheet.prototype.constructor = Sheet;

Sheet.prototype.getLongestMovie = function()
{
	var m = null;
	var l = 0;
	for(var i=0; i<this.movies.length; i++)
	{
		if(this.movies[i].duration > l)
		{
			l = this.movies[i].duration;
			m = this.movies[i];
		}
	}
	return m;
}

Sheet.prototype.show = function()
{
	if(!this.animation)
	{
		player.showCurrentSheetCompleteHandler();
		return;
	}

	switch(this.animation.type)
	{
		case 'fadeIn': fadeIn(this.container, $("#sheetsContainer"), "player.showCurrentSheetCompleteHandler()"); break;
		case 'entranceFromLeft': entranceFromLeft(this.container, $("#sheetsContainer"), "player.showCurrentSheetCompleteHandler()"); break;
		case 'entranceFromTop': entranceFromTop(this.container, $("#sheetsContainer"), "player.showCurrentSheetCompleteHandler()"); break;
		case 'entranceFromRight': entranceFromRight(this.container, $("#sheetsContainer"), "player.showCurrentSheetCompleteHandler()"); break;
		case 'entranceFromBottom': entranceFromBottom(this.container, $("#sheetsContainer"), "player.showCurrentSheetCompleteHandler()"); break;
	}
}

//////////////////////////////////// ANIMACJA SLAJDU ////////////////////////////////

function SheetAnimation(type)
{
	this.type = type;
}

SheetAnimation.prototype.constructor = SheetAnimation;

////////////////////////////////// FILM ///////////////////////////////////

function Movie(id, type, file, x, y, w, h, duration)
{
	this.id = id;
	this.type = type;
	this.file = file;
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
	this.duration = duration;
}

Movie.prototype.constructor = Movie;

//////////////////////////////////FILM CHEMICZNY ///////////////////////////////////

function ChemMovie(id, img, file, x, y, w, h)
{
	this.id = id;
	this.img = img;
	this.file = file;
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
}

ChemMovie.prototype.constructor = ChemMovie;

function Image(path, x, y, w, h)
{
	this.path = path;
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
}

Image.prototype.constructor = Image;