/*
 * PLUGIN DE PLAYER
 *
 * UNAS ACLARACIONES
 * SI VEN UN IF(this.<objeto>) Y POR ESAS CASUALIDADES DE LA VIDA ASUMEN QUE ESE OBJETO NUNCA PUEDE SER NULL
 * Y QUIEREN SACAR EL IF, SE VAN A LLEVAR UNA SORPRESA GRANDE
 * YA QUE AL DESTRUIR EL PLAYER TODAVIA SE DISPARAN ALGUNOS EVENTOS DE LOS OBJETOS
 * Y EN LA DESTRUCCION SE DESTRUYEN TODAS LAS VARIABLES, ASI QUE NO SAQUEN ESOS IF
 */
(function($) {
	$.widget("ui.player", {
		/**
		 * Funcion que se ejecuta al iniciar el widget
		 */
		_init: function() {
			//Creo el fake player
			this.videoDiv = $('<div id="'+this.element.attr("id")+'_playerVideo" class="ui-player-video"></div>').appendTo(this.element);
			//Creo la toolbar
			if (this.options.controlBar == "show") {
				this.controlDiv = $('<div id="'+this.element.attr("id")+'_controlBar" class="ui-player-controlbar"></div>').appendTo(this.element);
				this._drawControlBar();
			}
		},
		
		/**
		 * Referencia al objeto media que se esta reproduciendo actualmente
		 */
		currentMedia : function(value) {
			if (value === undefined) {
				return this._currentMedia;
			} else {
				this._currentMedia = value;
			}
		},
		
		/**
		 * Abre un objeto para reproducir
		 * @param params JSON
		 */
		open: function(params) {			
			window.fwk.debugJson(params,"player::open");
			//Detengo la reproduccion actual			
			this.stop();
			//Cierro lo que se este reproduciendo
			this.close();
			//Desactivo el cambio de tamaño
			this._disabledChangeSize();
			//Cargo el nuevo contenido
			var url = this.options.openUrl;
			var mthis = this;
			for(var param in params) {
				url += "/"+param+"/"+eval("params."+param);
			}
			//Apago el layout
			url += "?layoutOff=true";
			
			$.getJSON(url,function(data) {
				window.fwk.debugJson(data,"player::result_open");
				mthis.currentMedia(new media(data,data.preview));
				if (mthis._currentMedia.isLoaded) {
					//Refresco los botones de encodeos (Cambio de tamaño)
					mthis._refreshChangeSize(mthis._currentMedia.getMaterialProp("encodes_streaming"));
					//Obtengo el tamaño segun el video
					var size = mthis._getSizeByEncode(mthis._currentMedia.getMaterialProp("encode_id"));
					//Cambio el tamaño
					mthis.size(size.name);
					//Cargo el video
					var map = mthis._getMap(mthis._getExtension(mthis.currentMedia().url));
					if (map != null) {
						mthis._createPlayer(map);
						if (mthis._currentPlayer.isReady) {					
							mthis._currentPlayer.openUrl(mthis.currentMedia());
							/*ES INCREIBLE, PERO EL EVENTO DEL FLASH PLAYER QUE SE DISPARA CUANDO SE CARGA UN CONTENIDO, SE DISPARA CUANDO HACES PLAY!!!! DEL CONTENIDO
							ENTONCES ESTE CODIGO DE ABAJO QUE SOLAMENTE DEBERIA DE ESTAR EN EL _onMediaLoaded TENGO QUE PONERLO ACA POR EL PLAYER DE FLASH SOLAMENTE
							*/
							if (mthis._currentPlayer.type == "flash" && mthis.options.autoPlay) {
								mthis.play();
							}
						}
					}					
				} else {
					//Disparo el error
					mthis._onError(mthis.options.messages.fileNotFound);
				}
			});
			//Guardo los parametros que se usaron para abrir el contenido
			this._currentOpenParams = params;
		},
		
		/**
		 * Abre un objeto para reproducir y levanta el player asociado a la extension
		 * @param url string URL para reproducir el contenido
		 */
		url: function(url) {
			data = {
				url: url
			};
			//Guardo la url que se va a utilizar
			this.currentMedia(new media(data));
			var map = this._getMap(this._getExtension(url));
			if (map != null) {
				this._createPlayer(map);
				if (this._currentPlayer.isReady) {
					this._currentPlayer.openUrl(this.currentMedia());
					/*ES INCREIBLE, PERO EL EVENTO DEL FLASH PLAYER QUE SE DISPARA CUANDO SE CARGA UN CONTENIDO, SE DISPARA CUANDO HACES PLAY!!!! DEL CONTENIDO
					ENTONCES ESTE CODIGO DE ABAJO QUE SOLAMENTE DEBERIA DE ESTAR EN EL _onMediaLoaded TENGO QUE PONERLO ACA POR EL PLAYER DE FLASH SOLAMENTE
					*/
					if (this._currentPlayer.type == "flash" && this.options.autoPlay) {
						this.play();
					}
				}
			}
		},
		
		/**
		 * Cambia un mapeo extension/player
		 * @param value json JSON con el valor ext/player que se debe cambiar
		 */
		changeMap: function(value) {
			if (value != undefined) {
				for(var i = 0; i < this.options.mapFormats.length; i++) {
					if (this.options.mapFormats[i].ext.toLowerCase() == value.ext.toLowerCase()) {
						this.options.mapFormats[i].player = value.player;
						break;
					}
				}
			}
			return this;
		},
		
		/** 
		 * Retorna la referencia al objeto player utilizado actualmente por el plugin para reproducir un contenido
		 * @return object
		 */
		getCurrentPlayer: function() {			
			return this._currentPlayer;
		},
		
		/**
		 * Get del tiempo total del video en segundos
		 */
		mediaLength: function() {
			var ret = 0;
			if (this._currentPlayer != null && this._currentPlayer.isReady) {
					ret = this._currentPlayer.getMediaLength();
			}
			return ret;
		},
		
		/**
		 * Get/Set de la posicion del video
		 */
		mediaPosition: function(value) {
			if (this._currentPlayer != null && this._currentPlayer.isReady) {
				if (value === undefined) {
					return this._currentPlayer.getMediaPosition(); 
				} else {
					this._currentPlayer.setMediaPosition(value);
				}
			}
		},
						
		/**
		 * Get/Set del volumen
		 */
		volume: function(value) {
			if (this._currentPlayer != null && this._currentPlayer.isReady) {
				if (value === undefined) {
					return this._currentPlayer.getVolume();
				} else {
					this._currentPlayer.setVolume(value);
					this._currentVolume = value;
					//Actualizo el slider
					if (this.volumeSlider != null) {
						this.volumeSlider.slider("value",value);
					}
				}
			}
		},
		
		/** 
		 * Get/Set el mute del player
		 */
		mute: function(value) {
			if (this._currentPlayer != null && this._currentPlayer.isReady) {
				if (value === undefined) {
					//Obtengo el valor actual y lo invierto
					this._currentPlayer.setMute(!this._currentPlayer.getMute());
				} else {
					this._currentPlayer.setMute(value);
				}
			}
			this._currentMute = this._currentPlayer.getMute();
			if (this._currentMute) {
				this.muteDiv.addClass("ui-player-control-unmute");
				this.muteDiv.removeClass("ui-player-control-mute");
			} else {
				this.muteDiv.addClass("ui-player-control-mute");
				this.muteDiv.removeClass("ui-player-control-unmute");
			}
			
			return this._currentMute;
		},
		
		/**
		 * Get/Set tamaño
		 * @param string name Nombre del tamaño (low,normal,high)
		 */
		size: function(name) {
			if (name === undefined) {
				return this.options.size;
			} else {
				//Busco el size dentro de options
				var size = this._getSizeByName(name);
				if (size) {
					this._changeSize(this._getSizeByName(this.options.size),size);
					this.options.size = size.name;
					//Destruyo el player actual
					this._destroyPlayer();
					var map = this._getMap(this._getExtension(this.currentMedia().url));
					if (map != null) {
						this._createPlayer(map);
					}
				}
			}
		},
		
		/**
		 * Cambia de normal a fullscreen
		 */
		toggleFullScreen: function() {
			if (this._currentPlayer != null) {
				this._currentPlayer.toggleFullScreen();
			}
		},
		
		/**
		 * Play del contenido cargado
		 */
		play: function() {
			if (this.currentMedia() != null && this._currentPlayer != null && this._currentPlayer.isReady) {
				this._currentPlayer.play();
			}		
		},
		
		/**
		 * Stop del contenido actual
		 */
		stop: function() {
			if (this.currentMedia() != null && this._currentPlayer != null && this._currentPlayer.isReady) {
				this._currentPlayer.stop();
			}
		},
		
		/**
		 * Pausa el contenido actual
		 */
		pause: function() {
			if (this.currentMedia() != null && this._currentPlayer != null && this._currentPlayer.isReady) {
				this._currentPlayer.pause();
			}
		},
		
		status: function(text) {
			if (this.statusDiv) {
				this.statusDiv.text(text);
			}
		},
		
		/**
		 * Cierra el contenido cargado actualmente
		 */
		close: function() {
			if (this.currentMedia() != null && this._currentPlayer != null && this._currentPlayer.isReady) {
				this._currentPlayer.close();
			}
		},
		
		/**
		 * Fuerza a que el player muestre un mensaje de error
		 * @param err (string) Error que se debe mostrar
		 */
		raiseError: function(err) {
			this._showError(err);
		},
		
		/**
		 * Remuevo la instancia del objeto
		 */
		destroyPlayer: function() {
			this._destroyPlayer();			
		},		
		
		//////////////////////////////////////////////////////////////////////////
		// MEMBERS PRIVADAS
		//////////////////////////////////////////////////////////////////////////

		/**
		 * Objeto player actualmente instanciado
		 */
		_currentPlayer: null,
		_hndPositionTimer: null,
		_currentVolume: 50,
		_currentMute: false,
		_currentMedia: null,
		_changeStateByUserAction: false,
		_currentOpenParams: null,
		
		/**
		 * Actualiza la toolbar
		 */
		_drawControlBar: function() {
			//Si todavia no se dibujo nada entonces dibujo lo que necesito
			var mthis = this;
			if (this.playPauseDiv === undefined) {
				this.playPauseDiv = $('<div class="ui-player-control-pause"><span>Pausa</span></div>').appendTo(this.controlDiv);
				this.stopDiv = $('<div class="ui-player-control-stop"><span>Stop</span></div>').appendTo(this.controlDiv);
				this.muteDiv = $('<div class="ui-player-control-mute"><span>Mute</span></div>').appendTo(this.controlDiv);
				if (this.options.showPreviousNextButtons) {
					this.previousDiv = $('<div class="ui-player-control-previous"><span>Previous</span></div>').appendTo(this.controlDiv);
					this.nextDiv = $('<div class="ui-player-control-next"><span>Next</span></div>').appendTo(this.controlDiv);
				}
				//Encodeos / Tamaños
				this.sizeContainerDiv = $('<div class="ui-player-control-encodes"></div>').appendTo(this.videoDiv);
				this.sizeLowDiv = $('<div class="ui-player-size-low"></div>').appendTo(this.sizeContainerDiv);
				this.sizeNormalDiv = $('<div class="ui-player-size-normal"></div>').appendTo(this.sizeContainerDiv);
				this.sizeHighDiv = $('<div class="ui-player-size-high"></div>').appendTo(this.sizeContainerDiv);
				this.fullScreenDiv = $('<div class="ui-player-control-fullscreen"></div>').appendTo(this.sizeContainerDiv);

				this.positionSlider = $('<div id="'+this.element.attr("id")+'_positionSlider"></div>').appendTo(this.controlDiv).slider(
					{
						start: function(event,ui) {
							//Debo detener la actualizacion automatica
							mthis._clearPositionTimer();
						},
						slide: function(event,ui) {
							//Actualizo el positionDiv
							if (mthis.positionDiv) {
								mthis.positionDiv.text(new Date(1,0,1,0,0,(ui.value*mthis._currentPlayer.getMediaLength()) / 100).toTimeString().substring(1,8));
							}
						},
						stop: function(event,ui) {
							//Tomo el valor actual
							mthis._currentPlayer.setMediaPosition((ui.value*mthis._currentPlayer.getMediaLength()) / 100);
							//Vuelvo a prender el timer
							mthis._setIntervalPositionTimer();
						}
					}
				);
				this.positionDiv = $('<div class="ui-player-control-position"></div>').appendTo(this.controlDiv);
				this.durationDiv = $('<div class="ui-player-control-duration"></div>').appendTo(this.controlDiv);
				this.volumeSlider = $('<div id="'+this.element.attr("id")+'_volume"></div>').appendTo(this.controlDiv).slider(
					{
						value: (mthis._currentPlayer != null) ? mthis._currentPlayer.getVolume() : mthis._currentVolume,
						slide: function(event,ui) {
							mthis.volume(ui.value);
						}
					}
					
				);
				this.statusDiv = $('<div class="ui-player-statusbar"></div>').appendTo(this.controlDiv);
								
				//Bind del play/pause
				this.playPauseDiv.bind("click",this,function(e) {
					e.data._changeStateByUserAction = true;
					if(e.data._currentPlayer != null) {						
						if (e.data.playPauseDiv.hasClass("ui-player-control-pause")) { //Esta reproduciendo (es la inversa)
							e.data._currentPlayer.pause();
						} else { //Esta reproduciendo
							e.data._currentPlayer.play();
						}
					}
				});
				
				//Bind del stop
				this.stopDiv = this.stopDiv.bind("click",this,function(e) {
					e.data._changeStateByUserAction = true;
					if (e.data._currentPlayer != null) {
						e.data._currentPlayer.stop();
					}
				});
				
				//Bind del previous/next
				if (this.options.showPreviousNextButtons) {
					this.previousDiv.bind("click",this,function(e) {
						mthis._trigger("onPrevious");
					});
					this.nextDiv.bind("click",this,function(e) {
						mthis._trigger("onNext");
					});
				}
				
				//Bind del mute/unmute
				this.muteDiv = this.muteDiv.bind("click",this,function(e) {
					var mute = e.data.mute();
					if (mute) {
						$(this).addClass("ui-player-control-unmute");
						$(this).removeClass("ui-player-control-mute");
					} else {
						$(this).addClass("ui-player-control-mute");
						$(this).removeClass("ui-player-control-unmute");
					}
				});
				
				//Bind de los botones para cambiar los tamaños
				this.sizeContainerDiv.find("div:not(.ui-player-control-fullscreen)").each(function(i) {
					$(this).hover(function() {
						if (!$(this).hasClass("ui-player-size-disabled")) {
							$(this).addClass("ui-player-size-hover");							
						}
					},
					function() {
						if (!$(this).hasClass("ui-player-size-disabled")) {
							$(this).removeClass("ui-player-size-hover");
						}
					});
					$(this).bind("click",mthis,function(e) {						
						if (!$(this).hasClass("ui-player-size-selected") && !$(this).hasClass("ui-player-size-disabled")) {
							//Si hizo click quito el class de hover (lo hago aca para que la linea anterior obtenga el el class del size solamente)
							$(this).removeClass("ui-player-size-hover");
							var className = $(this).attr("class");
							//Ahora le quito el class de selected al objeto anterior
							$(".ui-player-size-selected").removeClass("ui-player-size-selected");
							//agrego el class para indicar que esta seleccionado
							$(this).addClass("ui-player-size-selected");
							//Obtengo el nombre del size
							var sizeName = className.substr(className.lastIndexOf("-")+1);
							//Obtengo el objeto size
							var sizeObject = e.data._getSizeByName(sizeName);
							//Abro el nuevo contenido peeeeero con el id_encodeo correspondiente al tamaño seleccionado
							e.data._currentOpenParams.encode_id = sizeObject.encode;
							e.data.open(e.data._currentOpenParams);
						}
					});
				});
				
				//Bind del fullscreen
				this.fullScreenDiv.bind("click",mthis,function(e) {
					e.data.toggleFullScreen(); 
				});
				
				//Cambio el tamaño
				var size = this._getSizeByName(this.options.size);
				this._changeSize(size,size);
			}
						
			if (this._currentPlayer) {
			
				//Chequeo de estados entre el player y las clases de los divs
				if (this._currentPlayer.playState == PLAY_STATE_IDLE && this._currentPlayer.openState == OPEN_STATE_OPENING) {
					this.playPauseDiv.removeClass("ui-player-control-pause");
					this.playPauseDiv.addClass("ui-player-control-play");					
				}
							
				//Verifico si debo mostrar o no el fullScreen
				if (!this._currentPlayer.settings.allowFullScreen) {
					if (!this.fullScreenDiv.hasClass("ui-player-control-fullscreen-disabled")) {
						this.fullScreenDiv.addClass("ui-player-control-fullscreen-disabled");
					}
				} else {
					//Solamente para mediaplayer tengo que mostrar el boton
					if (this._currentPlayer.type == "mediaplayer") {
						if (this.fullScreenDiv.hasClass("ui-player-control-fullscreen-disabled")) {
							this.fullScreenDiv.removeClass("ui-player-control-fullscreen-disabled");
						}
					} else {
						this.fullScreenDiv.addClass("ui-player-control-fullscreen-disabled");
					}
				}
				//Actualizo los botones segun el estado
				switch(this._currentPlayer.playState) {
					case PLAY_STATE_PLAYING:
						this.playPauseDiv.addClass("ui-player-control-pause");
						this.playPauseDiv.removeClass("ui-player-control-play");
						this.playPauseDiv.find("span").text("Pausa");
						//Disparo el timer para actualizar la toolbar de posicion
						this._setIntervalPositionTimer();
						break;
					case PLAY_STATE_PAUSED:
						this.playPauseDiv.addClass("ui-player-control-play");
						this.playPauseDiv.removeClass("ui-player-control-pause");
						this.playPauseDiv.find("span").text("Play");
						this._clearPositionTimer()
						break; 
					case PLAY_STATE_STOPED:
						this.playPauseDiv.addClass("ui-player-control-play");
						this.playPauseDiv.removeClass("ui-player-control-pause");
						this.playPauseDiv.find("span").text("Play");
						this._clearPositionTimer()
						this.positionSlider.slider("value",0);
						//Actualizo el position a 0
						this.positionDiv.text("0:00:00");
						break;
				}
				if (this.controlDisabledDiv) {
					this.controlDisabledDiv.remove();
					delete this.controlDisabledDiv;
				}
			} else { // No hay ningun player cargado todavia asi que deshabilito todo
				this.controlDisabledDiv = $('<div class="ui-player-controlbar-disabled"></div>').appendTo(this.controlDiv);
				this.positionDiv.text("0:00:00");
				this.durationDiv.text("0:00:00");
			}
			
			//Si se esta mostrando un mensaje de error lo oculto
			this._hideError();			
		},

		/**
		 * Hace el attach de los eventos del player a este objeto
		 */		
		_attachEvents: function() {
			if (this._currentPlayer != null) {
				this._currentPlayer.attachPlayerReady(this._onPlayerReady);
				this._currentPlayer.attachMediaLoaded(this._onMediaLoaded);
				this._currentPlayer.attachStateChanged(this._onStateChanged);
				this._currentPlayer.attachBeforePlay(this._onBeforePlay);
				this._currentPlayer.attachError(this._onError);
				this._currentPlayer.attachStartLicenseAcquisition(this._onStartLicenseAcquisition);
				this._currentPlayer.attachEndLicenseAcquisition(this._onEndLicenseAcquisition);
			}
		},
		
		/**
		 * Se desengancha de todos los eventos
		 */
		_deAttachEvents: function() {
			//Primero le digo al player que se desenganche de sus eventos
			if (this._currentPlayer != null) {
				this._currentPlayer.deAttachAll();
			}			
		},
		
		/**
		 * Crea la instancia del objeto player que se debe utilizar
		 * @param map JSON Datos de mapeo
		 */
		_createPlayer: function(map) {
			if (map != null && ((this._currentPlayer != null && this._currentPlayer.type != map.player) || this._currentPlayer == null)) { //Encontro el mapeo
				//Destruyo la instancia actual del player
				this._destroyPlayer();
				//Parametros para pasar al player
				var params = this._makePlayerParams(map);
				var player = this._getPlayerObject(map,params);				
				if (player != null) {
					//Asigno el player a la member del widget
					this._currentPlayer = player;
					//Engancho los eventos
					this._attachEvents();
					//Le seteo el volumen actual seleccionado por el usuario
					this._currentPlayer.setVolume(this._currentVolume);
					this._currentPlayer.setMute(this._currentMute);
					//ahora dibujo el player en la pantalla
					this._currentPlayer.drawPlayer();
				}
			}
		},
		
		/**
		 * Destruye la instancia actual del player
		 */
		_destroyPlayer: function() {
			if (this._currentPlayer != null) {
				this._clearPositionTimer() //Limpio el timer que actualiza la barra
				//Hago stop de lo que se esta viendo ahora
				this._currentPlayer.stop();
				//Cierro el contenido
				this._currentPlayer.close();
				//Quito los eventos de este objeto
				this._deAttachEvents();
				//tomo el id del objeto y lo destruyo
				this._currentPlayer.destroy();				
				delete this._currentPlayer;
			}
		},
				
		/**
		 * Devuelve la extension de un archivo
		 * @param url string URL con la extension del archivo a reproducir
		 * @return string
		 */
		_getExtension: function(url) {
			var data = url.split(".");
			if (data.length >=2) {
				return data[data.length-1]; //retorno el ultimo
			} else {
				//No se encontro el . asi que retorno "" para que se utilice el default
				return "";
			}
		},
		
		/**
		 * Devuelve el objeto asociado al mapeo
		 * @param extension string Extension del archivo a reproducir
		 * @return JSON
		 */
		_getMap: function(extension) {
			var ret = null;
			var checkPluginOk = false;
			for(var i = 0; i < this.options.mapFormats.length; i++) {
				if (ret == null && this.options.mapFormats[i].ext == "") {
					// Guardo la default por las dudas
					ret = this.options.mapFormats[i];
					if (this._checkPlugin(ret)) {
						checkPluginOk = true;
					}
				}
				if (this.options.mapFormats[i].ext.toLowerCase().indexOf(extension.toLowerCase()) != -1) {
					ret = this.options.mapFormats[i];
					//Ahora valido que pueda cargar el objeto
					if (this._checkPlugin(ret)) {
						checkPluginOk = true;
						break; //Salgo del loop, las validaciones fueron correctas y puedo usar este objeto
					}
				}
			}
			if (!checkPluginOk) {
				var urlDownload = "";
				if (BrowserDetect) {
					BrowserDetect.init();
					switch(BrowserDetect.OS.toLowerCase()) {
						case "mac":
							urlDownload = this.options.mapFormats[0].urlDownloadPlugin.mac;
							break;
						default:
							urlDownload = this.options.mapFormats[0].urlDownloadPlugin.others;
							break;
					}					
				} else {
					urlDownload = this.options.mapFormats[0].urlDownloadPlugin.others;
				}
				this._onPluginDetectionError(urlDownload);
				ret = null;
			}
						
			return ret;
		},
		
		/**
		 * Retorna un JSON con los parametros que se deben pasar a los players
		 * @param object map Objeto con informacion de mapeo seleccionada
		 * @return JSON
		 */
		_makePlayerParams: function(map) {
			return {
				videoDivId: this.videoDiv.attr("id"),
				/*
				width: this.videoDiv.css("width"),
				height: this.videoDiv.css("height"),
				*/
				width: this._getSizeByName(this.size()).width,
				height: this._getSizeByName(this.size()).height,
				allowFullScreen: map.allowFullScreen,
				wMode: this.options.wMode,
				autoPlay: this.options.autoPlay,
				embed:map.embed,
				urlPreDelivery: map.urlPreDelivery,
				version: map.version
			};
		},
				
		/**
		 * Devuelve el objeto player correspondiente
		 * @param map object Objeto con datos de mapeo
		 * @param params object Parametros para pasar al objeto player
		 */
		_getPlayerObject: function(map,params) {
			var ret = null;
			switch(map.player) {
				case "flash": 
					ret = new flashPlayer(params,this);					
					break;
				case "mediaplayer":
					ret = new mediaPlayer(params,this);
					break;
				case "silverlight":
					ret = new slPlayer(params,this);
					break;
			}			
			return ret;
		},
		
		/**
		 * Inicializa el timer para actualizar el slider de posicion
		 */
		_setIntervalPositionTimer: function() {
			if (this._hndPositionTimer == null) {
				var mthis = this;
				this._hndPositionTimer = setInterval(function() {widgetPositionUpdate(mthis);},1000);
			}								
		},
		
		/**
		 * Refresca es slider que indica la posicion actual de reproduccion
		 */
		_refreshPositionSlider: function() {
			if (this._currentPlayer != null && this._currentPlayer.isReady && this.positionSlider) {
				var curPos = this._currentPlayer.getMediaPosition();
				var curLen = this._currentPlayer.getMediaLength();
				if (curLen > 0) {
					this.positionSlider.slider("value",(curPos*100)/curLen);
				}
				//Si la duracion esta en 0 la actualizo (esto pasa porque no puedo obtener la duracion al abrir el contenido con el player de flash)
				if (this.durationDiv.text() == "0:00:00") {
					this.durationDiv.text(new Date(1,0,1,0,0,this._currentPlayer.getMediaLength()).toTimeString().substring(1,8));
				}				
				//Actualizo el div que muestra el tiempo actual de reproduccion
				this.positionDiv.text(new Date(1,0,1,0,0,curPos).toTimeString().substring(1,8));
			}
		},
		
		/**
		 * Detiene el setInterval que actualiza el slider de posicion y limpia la variable
		 */
		_clearPositionTimer: function() {
			clearInterval(this._hndPositionTimer);
			this._hndPositionTimer = null;
		},
		
		_debug: function(message) {
			
		},
		
		/**
		 * Cambia el tamaño del player al especificado en el parametro
		 * @param object oldSize Tamaño anterior
		 * @param object newSize Nuevo tamaño
		 */
		_changeSize: function(oldSize,newSize) {
			if (this.videoDiv) {				
				if (oldSize.name != newSize.name) {
					//Remuevo los tamaños anteriores
					this.videoDiv.removeClass("ui-player-video-"+oldSize.name);
					this.controlDiv.removeClass("ui-player-controlbar-"+oldSize.name);
					
				}
				//Cambio los tamaños de los div relacionados al player
				this.videoDiv.addClass("ui-player-video-"+newSize.name);
				this.controlDiv.addClass("ui-player-controlbar-"+newSize.name);
				//Le agrego el seleccionado al boton correspondiente
				//Ahora le quito el class de selected al objeto anterior
				$(".ui-player-size-selected").removeClass("ui-player-size-selected");
				this.sizeContainerDiv.find(".ui-player-size-"+newSize.name).addClass("ui-player-size-selected");
			}
		},
		
		/**
		 * Desactivo todos los botones de cambio de tamaño del player (no el fullscreen)
		*/
		_disabledChangeSize: function() {
			this.sizeContainerDiv.find("div:not(.ui-player-control-fullscreen)").addClass("ui-player-size-disabled");
		},
		
		/**
		 * Habilita los botones de encodeos que corresponden al parametro recibido
		 * @param sizes (string) Encodeos habilitados del video separados por ,
		 */
		_refreshChangeSize: function(sizes) {
			var aSizes = sizes.split(",");
			var selector = "";
			for(var i = 0; i < aSizes.length; i++) {
				var size = this._getSizeByEncode(aSizes[i]);
				if (size) {
					selector += ".ui-player-size-"+size.name+",";
				}
			}
			if (selector != "") {
				//quito la ultima ,
				selector = selector.substr(0,selector.length-1);
				$(selector).removeClass("ui-player-size-disabled");
			}
		},

		/**
		 * Devuelve el object size en base al id_encodeo
		 * @param encodeId (int)
		 * @returns (object)
		 */
		_getSizeByEncode: function(encodeId) {
			var ret = null;
			for(var i = 0; i < this.options.sizes.length; i++) {
				if (this.options.sizes[i].encode == encodeId) {
					ret = this.options.sizes[i];
					break;
				}
			}
			return ret;
		},

		/**
		 * Devuelve un JSON con los datos del size en base al nombre del parametro
		 * @param string name Nombre del size a buscar
		 * @return object
		 */
		_getSizeByName: function(name) {
			var ret = null;
			for(var i = 0; i < this.options.sizes.length; i++) {
				if (this.options.sizes[i].name == name) {
					ret = this.options.sizes[i];
					break;
				}
			}
			return ret;
		},
		
		/**
		 * Muestra un mensaje de error en el player
		 * @param string err Error
		 */
		_showError: function(err) {
			//Obtengo el size actual
			var size = this.size();
			//Antes de mostrar el nuevo error oculto el anterior
			this._hideError();
			//Ahora pongo el nuevo error (la gente de diseño pidio sacar el mensaje)
			//$('<div class="ui-player-video-'+size+' ui-player-video-error">'+err+'</div>').appendTo(this.element);
			$('<div class="ui-player-video-'+size+' ui-player-video-error"></div>').appendTo(this.element);
		},
		
		/**
		 * Oculta el mensaje de error
		 */
		_hideError: function() {
			$(".ui-player-video-error").remove();
		},
		
		/**
		 * Valida si existe el plugin que carga el player (silverlight/flash unicamente)
		 * @param object map  Datos del player que se debe cargar
		 * @return bool
		 */
		_checkPlugin: function(map) {
			if (map.checkPlugin === undefined) {
				return true;
			} else {
				var ret = false;
				switch(map.player) {
					case "flash":
						ret = this._checkPluginFlash();
						break;
					case "silverlight":						
						ret = this._checkPluginSilverlight(map.version);
						break;
					case "mediaplayer":
						ret = this._checkPluginMediaPlayer(map.embed);
						break;						
				}
				return ret;
			}	
		},
		
		/**
		 * Valida si el map que se va a utilizar es compatible con el navegador
		 * @param object map Datos del player que se va a cargar
		 * @return bool
		 */
		_checkNavigator: function(map) {
		},
		
		/**
		 * Valida si el map que se va a utilizar es compatible con el SO
		 * @param object map Datos del player que se va a cargar
		 * @return bool
		 */
		_checkSO: function(map) {
		}, 
		
		/**
		 * Verifica si existe el objeto flash
		 * @return bool
		 */
		_checkPluginFlash: function() {
			var ret = false;
			var version = swfobject.getFlashPlayerVersion();
			if (version.major != "0" && (version.minor != "0" || version.release != "0")) {
				ret = true; //Hay una version de flash
			}
			return ret;
		},
		
		/**
		 * Verifica si existe el objeto silverlight
		 * @param string version Version para validar si existe
		 * @return bool
		 */
		_checkPluginSilverlight: function(version) {
			var ret = false;
			if (typeof(Silverlight) != "undefined") { //No esta el JS de silverlight cargado
				ret = Silverlight.isInstalled(version); 			
			}			
			return ret;
		},
		
		/**
		 * Verifica si existe el objeto MediaPlayer
		 * @return bool
		 */
		_checkPluginMediaPlayer: function(clsid) {
			var ret = false;			
			if ($.browser.msie) {
				//Verifico si puedo cargar el objeto
				try {
					var o = new ActiveXObject("WMPlayer.OCX");
					delete o;
					ret = true;
				} catch (e) {
				}
			} else if ($.browser.mozilla || $.browser.safari ) {
				/*
				for(var i=0; i < navigator.plugins.length; i++) {
					if(navigator.plugins[i].name.toLowerCase().indexOf("windows media player firefox plugin") != -1) {
						ret = true;
					}
				}
				*/
			}
			return ret;
		},
		
		/**
		 * Guarda el tracking del contenido que se abrio
		 */
		_saveTracking: function() {
			if (this.options.trackUrl) { //Si hay una url de tracking entonces lo guardo
				//Armo el json con los parametros para tracking
				var params = {
					group_id: this._currentMedia.getMaterialProp("group_id"),
					content_id: this._currentMedia.getMaterialProp("content_id"),
					material_id: this._currentMedia.getCommonProp("id")
				};
				$.get(this.options.trackUrl,params);
			}
		},
		
		//////////////////////////////////////////////////////////////////////////
		// Eventos de los players
		//////////////////////////////////////////////////////////////////////////
		
		/**
		 * Se dispara cuando el objeto PLAYER que se debe utilizar esta listo para su uso
		 */
		_onPlayerReady: function() {
			//Disparo el evento
			this.widget._trigger("onPlayerReady");
			//Valido si tengo una URL
			if (this.widget.currentMedia()) {
				//Llamo al open
				this.openUrl(this.widget.currentMedia());
				if (this.widget.currentMedia() != null && this.widget._currentPlayer != null && this.widget.options.autoPlay && this.widget._currentPlayer.isReady) {				
					this.play();
				} else {
					this.widget._drawControlBar();
				}
			}
		},
		
		/*
		 * Se dispara para avisar que se termino de cargar un archivo para reproducir
		 */
		_onMediaLoaded: function() {
			//Actualizo la toolbar
			this.widget._drawControlBar();
			//Ponga la duracion del contenido en 0 para inicializar todo correctamente
			this.widget.durationDiv.text("0:00:00");
			//Disparo el evento			
			this.widget._trigger("onMediaLoaded",null,null);
			//Verifico si debo hacer play o no del contenido
			if (this.type != "flash") {
				if (this.widget.currentMedia() != null && this.widget._currentPlayer != null && this.widget.options.autoPlay && this.widget._currentPlayer.isReady) {
					this.play();
				}			
			}
			//Guardar el tracking del contenido
			this.widget._saveTracking();
		},
		
		/**
		 * Se dispara antes de realizar un play del video seleccionado
		 */
		_onBeforePlay: function() {
			var ret = true;
			return this.widget._trigger("onBeforePlay");
			return ret;
		},
		
		/*
		 * Se dispara cuando se produce un cambio de estado en la reproduccion de un contenido
		 */
		_onStateChanged: function(state) {
			//Actualizo la toolbar
			this.widget._drawControlBar(this.widget);
			if (state != PLAY_STATE_COMPLETED) {
				this.widget._trigger("onStateChanged",null,{state: state,isUserAction: this.widget._changeStateByUserAction});
			} else {
				this.widget._trigger("onCompleted");
			}
			if (this.widget) {
				//Restauro el valor de la variable			
				this.widget._changeStateByUserAction = false;				
			}
		},
		
		/**
		 * Se dispara cuando se produce un error en el player
		 * @param string err Error producido
		 */
		_onError: function(err) {
			var mthis = (this.widget === undefined) ? this : this.widget;
			mthis._showError(err);
			mthis._trigger("onError");
		},
		
		/**
		 * Se dispara cuando se esta adquiriendo una licencia para reproducir el contenido
		 */
		_onStartLicenseAcquisition: function() {
			this.widget._trigger("onStartLicenseAcquisition");
		},
		
		/**
		 * Se dispara cuando se termino de adquirir una licencia
		 * @param error string Mensaje de error
		 */
		_onEndLicenseAcquisition: function(error) {
			if (error) {
				this.widget._onError(error);
				this.widget._trigger("onEndLicenseAcquisition",event,{message: error});
			} else {
				this.widget._trigger("onEndLicenseAcquisition");			
			}
		},
		
		/**
		 * Se dispara cuando fallo la deteccion de todos los plugins configurados en el mapeo de formatos
		 */
		_onPluginDetectionError: function(url) {
			//Verifico si existe el div sino lo creo
			if (this.element.find("#playerPluginError").length == 0) {
				//No existe asi que lo creo
				$('<div id="playerPluginError" class="ui-player-plugin-error"></div>').appendTo(this.element);
			}
			
			this.element.find("#playerPluginError").unbind("click");
			this.element.find("#playerPluginError").bind("click",function() {
				document.location.href = url;
			});
			//Segun el plugin que dio error es la url que tengo que redireccionar
				
			this._trigger("onPluginDetectionError");
		}
	});
	
	$.extend($.ui.player, { 
		version: "@VERSION",
		getter: "getCurrentPlayer mediaLength mediaPosition volume mute currentMedia",
		eventPrefix: "player",
		defaults: {			
			mapFormats: [
				{ext:"",player:"flash",embed:"player.swf",allowFullScreen:false},
				{ext:"flv",player:"flash",embed:"player.swf",allowFullScreen:false},
				{ext:"wmv",player:"mediaplayer",embed:"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6",allowFullScreen:true}
			],
			sizes: [{name:"low",width:200,height:200,encode:128},{name:"normal",width:450,height:360,encode:350},{name:"high",width:500,height:400,encode:1024}],
			messages: {
				fileNotFound: "File Not Found" //Este error se dispara cuando no se obtuvo un contenido y el plugin se da cuenta, sino se va a disparar el error del objeto player cargado
			},
			size: "normal",
			defaultEncode: 350,
			controlBar: "show",
			allowFullScreen: true,
			autoPlay: false,
			wMode: "transparent",
			openUrl: null,
			trackUrl: null,
			showPreviousNextButtons: false
		}
	});	
})(jQuery);

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// SOBREESCRIBO EL PROTOTYPE DE FUNCTION PARA PODER HEREDAR EN JS
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
Function.prototype.inheritsFrom = function(parentClassOrObject) {
	/*
	if ( parentClassOrObject.constructor == Function ) { 
		//Normal Inheritance 
		this.prototype = new parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject.prototype;
	} else { 
		//Pure Virtual Inheritance 
		this.prototype = parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject;
	} 
	*/
	if ( parentClassOrObject.constructor == Function ) { 
		//Normal Inheritance 
		for(var i in parentClassOrObject.prototype){
			this.prototype[i] = parentClassOrObject.prototype[i];
		}		
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject.prototype;
		this.prototype.parentConstructor = parentClassOrObject;
	} 	
	return this;
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// FUNCIONES y VARIABLES GENERICAS
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

var PLAY_STATE_BUFFERING = "buffering";
var PLAY_STATE_PLAYING = "playing";
var PLAY_STATE_PAUSED = "paused";
var PLAY_STATE_STOPED = "stoped";
var PLAY_STATE_IDLE = "idle";
var PLAY_STATE_COMPLETED = "completed";

var OPEN_STATE_OPENING = "opening";
var OPEN_STATE_LICENSING = "licensing";
var OPEN_STATE_LICENSE_OK = "license_ok";
var OPEN_STATE_OPENED = "opened";
var OPEN_STATE_CLOSED = "closed";
var OPEN_STATE_ERROR = "error";

/**
 * Retorna la referencia al objeto que maneja al player
 */
function getPlayerObject(id) {
	var ret = null;
	if (("#"+id).length) {
		//AL QUE SAQUE ESTO LE CORTO LOS DEDOS (PA)
		try {
			ret = $("#"+id).parent().parent().player("getCurrentPlayer");					
		} catch (e) {
			
		}
	}
	return ret;
}

/**
 * Actualiza el slider de reproduccion del player
 * @param object widget Referencia al widget del player
 */
function widgetPositionUpdate(widget) {
	widget._refreshPositionSlider();
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// CLASE BASE PARA LOS PLAYERS
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

function basePlayer(settings,widget) {
	//Publicas
	this.settings = settings;
	this.widget = widget;
	this.type = "";
	this.player = null;
	this.isReady = false;
	this.openState = OPEN_STATE_CLOSED;	
	this.playState = PLAY_STATE_IDLE;
	//Privadas
	this._uniqId = null;	
	this._mediaLength = 0;
	this._mediaPosition = 0;
	this._volume = 50;
	this._mute = false;
	//Punteros a funciones
	this.__onPlayerReady = null;
	this.__onMediaLoaded = null;
	this.__onStateChanged = null;
	this.__onBeforePlay = null;
	this.__onError = null;
	this.__onStartLicenseAcquisition = null;
	this.__onEndLicenseAcquisition = null;
}

//Funciones Abstractas
basePlayer.prototype.drawPlayer = function() {};
basePlayer.prototype.play = function() {};
basePlayer.prototype.pause = function() {};
basePlayer.prototype.stop = function() {};
basePlayer.prototype.close = function() {this.openState = OPEN_STATE_CLOSED;};
basePlayer.prototype.getMediaLength = function() {return 0;};
basePlayer.prototype.getMediaPosition = function() {return 0;};
basePlayer.prototype.setMediaPosition = function(position) {};
basePlayer.prototype.toggleFullScreen = function() {};
basePlayer.prototype.getFullScreen = function() {};
basePlayer.prototype.storeLicense = function() {return false;};
//Funciones	
basePlayer.prototype.dataLicense= function(media) {
	var data = {
		/*
		content_id: 350003,
		material_id: 350004,
		encode_id: 350,
		preview: media.preview
		*/
		content_id: media.getMaterialProp("content_id"),
		material_id: media.getCommonProp("id"),
		encode_id: media.getMaterialProp("encode_id"),
		preview: media.preview
	}; 	
	return data;
};
basePlayer.prototype.openUrl = function(media) {
	var mthis = this;
	//Verifico si antes de abrir el contenido debo adquirir una licensia
	if (this.settings.urlPreDelivery && this.openState != OPEN_STATE_LICENSE_OK) {
		var data = this.dataLicense(media);
		if (data) {
			this.openState = OPEN_STATE_LICENSING;
			this.fireStartLicenseAcquisition();
			$.post(this.settings.urlPreDelivery,data,function(data,textStatus) {
				var error = mthis.storeLicense(data.license.raw);
				if (error === undefined) {
					mthis.openState = OPEN_STATE_LICENSE_OK;
					mthis.fireEndLicenseAcquisition();
					mthis.openUrl(media);
				} else {
					mthis.fireEndLicenseAcquisition(error);
				}
			},"json");
		} else {
			this.openState = OPEN_STATE_OPENING;
		}
	} else {
		this.openState = OPEN_STATE_OPENING;
	}
};

basePlayer.prototype.getUniqId = function() {
	if (this._uniqId == null) {
		do { 
			this._uniqId = new Date().getTime()+""+parseInt(Math.random()*9);
		} while(document.getElementById("playerWidget"+this._uniqId) != null);
	}
	return this._uniqId;
};

basePlayer.prototype.getPlayerWidgetId = function() {
	return "playerWidget"+this.getUniqId();
};			

basePlayer.prototype.attachPlayerReady = function(func) {
	this.__onPlayerReady = func;
};

basePlayer.prototype.firePlayerReady = function() {
	if (this.__onPlayerReady) {
		this.__onPlayerReady();
	}
};

basePlayer.prototype.attachMediaLoaded = function(func) {
	this.__onMediaLoaded = func;
};

basePlayer.prototype.fireMediaLoaded = function() {
	//Cambio el estado
	this.openState = OPEN_STATE_OPENED;
	if (this.__onMediaLoaded) {		
		this.__onMediaLoaded();
	}
};

basePlayer.prototype.attachStateChanged = function(func) {
	this.__onStateChanged = func;
};

basePlayer.prototype.fireStateChanged = function(state) {
	this.playState = state;
	if (this.__onStateChanged) {
		this.__onStateChanged(state);
	}
};

basePlayer.prototype.attachBeforePlay = function(func) {
	this.__onBeforePlay = func;
}

basePlayer.prototype.fireBeforePlay = function() {
	var ret = true;
	if (this.__onBeforePlay) {
		ret = this.__onBeforePlay();
	}
	return ret;
}

basePlayer.prototype.attachError = function(func) {
	this.__onError = func;
}

basePlayer.prototype.fireError = function(err) {
	if (this.__onError) {
		this.__onError(err);
	}
}

basePlayer.prototype.attachStartLicenseAcquisition = function(func) {
	this.__onStartLicenseAcquisition = func;
}

basePlayer.prototype.fireStartLicenseAcquisition = function() {
	if (this.__onStartLicenseAcquisition) {
		this.__onStartLicenseAcquisition();
	}
}

basePlayer.prototype.attachEndLicenseAcquisition = function(func) {
	this.__onEndLicenseAcquisition = func;
}

basePlayer.prototype.fireEndLicenseAcquisition = function(error) {
	if (this.__onEndLicenseAcquisition) {
		this.__onEndLicenseAcquisition(error);
	}
}

basePlayer.prototype.deAttachAll = function() {
	this.__onPlayerReady = null; 
	this.__onMediaLoaded = null;
	this.__onStateChanged = null;	
	this.__onBeforePlay = null;
	this.__onError = null;
	this.__onStartLicenseAcquisition = null;
	this.__onEndLicenseAcquisition = null;
};

basePlayer.prototype.destroy = function() {
	this.deAttachAll();
	this.player = null;
	this.openState = OPEN_STATE_CLOSED;
	this.playState = PLAY_STATE_IDLE;
	this._mediaLength = 0;
	this._mediaPosition = 0;
	//Borro todo para liberar memoria
	delete this.__onPlayerReady;
	delete this.__onMediaLoaded;
	delete this.__onStateChanged;
	delete this.__onBeforePlay;
	delete this.__onError;
	delete this.__onStartLicenseAcquisition;
	delete this.__onEndLicenseAcquisition;
	delete this.widget;
	delete this.settings;
	delete this.player; 
	delete this.parent;
	delete this.parentConstructor;
};

basePlayer.prototype.getVolume = function() {
	return this._volume;
};

basePlayer.prototype.setVolume = function(value) {
	this._volume = value;
};

basePlayer.prototype.getMute = function() {
	return this._mute;
};

basePlayer.prototype.setMute = function(value) {
	this._mute = value;
};

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// OBJETO MEDIA CON LA INFO
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////


function media(data,preview) {
	this.__data = data;
	this.isLoaded = (data.record_count);
	this.preview = (preview === undefined) ? 0 : preview;
	//Verifico si trajo datos o no
	if (this.isLoaded) {
		if (preview != undefined && preview) {
			this.url = data.materials.material[0].url_preview;
		} else {
			this.url = data.materials.material[0].url;
		}		
	}
	window.fwk.debugJson(this,"player::mediaopen");		
	
	/**
	 * Devuelve el valor de la propiedad dentro del objeto de material
	 * @param string name Nombre de propiedad que se esta buscando
	 * @return string
	 */
	this.getMaterialProp = function(name) {
		return this._getProp(this.__data.materials.material[0],name);
	};
	
	/**
	 * Devuelve el valor de la propiedad dentro del objeto de common
	 * @param string name Nombre de propiedad que se esta buscando
	 * @return string
	 */	
	this.getCommonProp = function(name) {
		return this._getProp(this.__data.materials.material[0].common,name);
	}
	
	/**
	 * Devuelve el valor de la propiedad dentro del objeto de Ranking
	 * @param string name Nombre de propiedad que se esta buscando
	 * @return string
	 */	
	this.getRankingProp = function(name) {
		return this._getProp(this.__data.materials.material[0].common.ranking,name);
	}
		
	/**
	 * Devuelve el valor de la propiedad dentro del objeto de VTC
	 * @param string name Nombre de propiedad que se esta buscando
	 * @return string
	 */	
	this.getVtcProp = function(name) {
		return this._getProp(this.__data.materials.material[0].common.was_purchased,name);
	}
	
	this.getMediaProp = function(name) {
		return this._getProp(this.__data.materials.material[0].media,name);
	}
	
	this._getProp = function(obj,name) {
		var ret = null;
		for(var prop in obj) {
			if (prop.toLowerCase() == name.toLowerCase()) {
				ret = eval("obj."+prop);
				ret = ret.replace(/&quote;/g,'"').
						  replace(/&amp;/g,"&").
						  replace(/&gt;/g,">").
						  replace(/&lt;/g,"<").
						  replace(/&aacute;/g,"á").
						  replace(/&eacute;/g,"é").
						  replace(/&iacute;/g,"í").
						  replace(/&oacute;/g,"ó").
						  replace(/&uacute;/g,"ú").
						  replace(/&uuml;/g,"ü");
;
				break;
			}
		}
		return ret;
	}	
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// OBJETO PLAYER DE FLASH Y FUNCION playerReady PARA SABER CUANDO ESTA LISTO EL PLAYER PARA USAR
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

/**
 * Ojbeto para manejo de player de Flash
 */
function flashPlayer(settings,widget) {
	this.parentConstructor.call(this,settings,widget);
	this.type = "flash";
}
flashPlayer.inheritsFrom(basePlayer); //Aca el objeto flashPlayer HEREDA de basePlayer

/**
 * Sobreescribo el metodo drawPlayer de flashPlayer para su propia implementacion
 */
flashPlayer.prototype.drawPlayer=function() {
	//$('<div id="'+this.getPlayerWidgetId()+'"></div>').appendTo($("#"+this.settings.videoDivId));
	$('<div id="'+this.getPlayerWidgetId()+'"></div>').appendTo($("#"+this.settings.videoDivId));
	var flashvars = {
		controlbar:"none",
		volume:this.getVolume(),
		mute:this.getMute(),
		displayclick:"fullscreen"
	};
	var params = {
		//allowfullscreen:'"'+this.settings.allowFullScreen+'"',
		allowfullscreen:this.settings.allowFullScreen,
		allowscriptaccess:"always",
		wmode:this.settings.wMode
	};
	var attributes = {
		id:this.getPlayerWidgetId(),
		name:this.getPlayerWidgetId()
	};
	
	//swfobject.embedSWF("player.swf",this.getPlayerWidgetId(),this.settings.width,this.settings.height,"9.0.115",false,flashvars,params,attributes);
	swfobject.embedSWF(this.settings.embed,this.getPlayerWidgetId(),this.settings.width,this.settings.height,this.settings.version,false,flashvars,params,attributes);

	/* Version 1.5
	this.swfObject = new SWFObject("player.swf",this.getPlayerWidgetId(),this.settings.width,this.settings.height,"9");
	this.swfObject.addParam("allowfullscreen",this.settings.allowFullScreen);
	this.swfObject.addParam("allowscriptaccess","always");
	this.swfObject.addParam("flashvars","controlbar=none&volume="+this.getVolume()+"&mute="+this.getMute());
	this.swfObject.addParam("wmode",this.settings.wMode);
	//this.swfObject.write(this.settings.videoDivId);	
	this.swfObject.write("playerContainer_"+this.getPlayerWidgetId()); 
	*/
};
	

/**
 * Sobreescribo el metodo openUrl para su propia implementacion
 */
flashPlayer.prototype.openUrl=function(media) {
	this.parent.openUrl.call(this);
	if (this.player != null) {
		this.player.sendEvent("LOAD",media.url);	 	
	}
};

/**
 * Funcion que hace play de un video en el player de flash
 */
flashPlayer.prototype.play=function() {
	if (this.player != null) {
		if (this.fireBeforePlay()) {
			this.player.sendEvent("PLAY",true);
		}
	}
};

/**
 * Funcion que pausa la reproduccion en el player de flash
 */
flashPlayer.prototype.pause=function() {
	if (this.player != null) {
		this.player.sendEvent("PLAY",false);
	}
};

/**
 * Funcion que hace stop de un video en el player de flash
 */
flashPlayer.prototype.stop=function() {		
	if (this.player != null) {
		this.player.sendEvent("STOP");
	}
};

/**
 * Obtengo la duracion del video en segundos
 */
flashPlayer.prototype.getMediaLength = function() {
	return this._mediaLength;
}

/**
 * Obtengo la posicion actual de reproduccion
 */
flashPlayer.prototype.getMediaPosition = function() {
	return this._mediaPosition;
}

/**
 * Seteo la posicion actual de reproduccion
 */
flashPlayer.prototype.setMediaPosition = function(position) {
	if (this.player != null) {
		this.player.sendEvent("SEEK",position);
		this._mediaPosition = position;
	}
}

/**
 * Devuelve el porcentaje de volumen actual
 * @return int
 */
flashPlayer.prototype.getVolume = function() {
	var ret = 0;
	if (this.player != null) {
		ret = this.player.getConfig().volume;
	} else {
		ret = this.parent.getVolume.call(this);
	}
	return ret;
}

/**
 * Setea el volumen en el player
 */
flashPlayer.prototype.setVolume = function(value) {
	if (this.player != null) {
		this.player.sendEvent("VOLUME",value);
	}
	this.parent.setVolume.call(this,value);
}

/**
 * Devuelve el estado actual del mute del player
 * @return bool
 */
flashPlayer.prototype.getMute = function() {
	var ret = this.parent.getMute.call(this);
	if (this.player != null) {
		ret = this.player.getConfig().mute;
	}
	return ret;
}

/**
 * Setea el mute del player
 */
flashPlayer.prototype.setMute = function(value) {
	if (this.player != null) {
		this.player.sendEvent("MUTE",value);
	}
	this.parent.setMute.call(this,value);
}

flashPlayer.prototype.deAttachAll = function() {
	this.parent.deAttachAll.call(this);
	this.player.removeModelListener("LOADED","playerFlashMediaLoad");	
	this.player.removeModelListener("STATE","playerFlashStateChanged");
	this.player.removeModelListener("TIME","playerFlashTime");
	this.player.removeModelListener("ERROR","playerFlashError");
}

flashPlayer.prototype.destroy = function() {
	this.parent.destroy.call(this);
	swfobject.removeSWF(this.getPlayerWidgetId());
}

/** 
 * Esta funcion es llamada por el player de flash para indicar que esta listo y se puede interactuar con el
 */
function playerReady(obj) {	
	//Pregunto cual es el currenPlayer instanciado y disparo el firePlayerReady para avisar que ya se puede usar
	var currentPlayer = getPlayerObject(obj["id"]);
	//Asigno el objeto flash al objeto flashPlayer
	currentPlayer.player = document.getElementById(currentPlayer.getPlayerWidgetId());
	//Me engancho de los eventos
	currentPlayer.player.addViewListener("LOAD","playerFlashMediaLoad");	
	//currentPlayer.player.addModelListener("LOADED","playerFlashMediaLoad");	
	currentPlayer.player.addModelListener("STATE","playerFlashStateChanged");
	currentPlayer.player.addModelListener("TIME","playerFlashTime");
	currentPlayer.player.addModelListener("ERROR","playerFlashError");
	//Seteo otras variables y disparo el evento playerReady
	currentPlayer.isReady = true;
	currentPlayer.firePlayerReady();
}

/**
 * Esta funcion captura el evento del objeto flash que nos indica que se termino de cargar un archivo
 * @params params object Parametros devueltos por el objeto flash que disparo la funcion
 */
function playerFlashMediaLoad(params) {
	var currentPlayer = getPlayerObject(params.id);	
	if (currentPlayer != null) {
		currentPlayer.fireMediaLoaded();
	}
}

/**
 * Esta funcion captura los cambios de estado del player de flash
 * @params params object Parametros devueltos por el objeto flash que disparo la funcion
 */
function playerFlashStateChanged(params) {
	var currentPlayer = getPlayerObject(params.id);
	if(params.newstate == "IDLE") {
		currentPlayer.fireStateChanged(PLAY_STATE_STOPED);
	} else {
		currentPlayer.fireStateChanged(params.newstate.toLowerCase());
	}	
};

/**
 * Esta funcion captura los cambios de posicion del video que se esta reproduciendo
 * @params params object Parametros devueltos por el objeto flash que disparo la funcion
 */
function playerFlashTime(params) {
	var currentPlayer = getPlayerObject(params.id);
	currentPlayer._mediaLength = params.duration;
	currentPlayer._mediaPosition = params.position;
}

/**
 * Esta funcion captura los errores del player de flash
 * @params object params Parametros del error
 */
function playerFlashError(params) {
	var currentPlayer = getPlayerObject(params.id);
	currentPlayer.fireError(params.message);
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// OBJETO PLAYER DE WINDOWS
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

function mediaPlayer(settings,widget) {
	this.parentConstructor.call(this,settings,widget); 
	this.type = "mediaplayer";	
}
mediaPlayer.inheritsFrom(basePlayer); //Aca el objeto mediaPlayer HEREDA de basePlayer

mediaPlayer.prototype.dataLicense = function(media) {
	var data = this.parent.dataLicense.call(this,media);
	var drm = document.getElementById("drm");
	if (drm) {
		data.challenge = drm.GetSystemInfo();
		return data; 
	} else {
		return false;
	}
};

mediaPlayer.prototype.storeLicense = function(license) {
	var drm = document.getElementById("drm");
	if (drm) {
		try {
			drm.StoreLicense(license);			
			//drm.StoreLicense();
		} catch (e) {
			return e.message;
		}
	}
}

mediaPlayer.prototype.fireMediaLoaded = function() {
	//Cambio algunos valores que no se porque los ignora cuando van definidos como <PARAM>
	//entonces antes de disparar la carga de un video los vuelvo a setear aca pero por javascript	
	this.setMute(this.parent.getMute.call(this)); //Llamo al parent porque sino el objeto me va a devolver que no esta mute
	//Disparo el evento
	this.parent.fireMediaLoaded.call(this);	
};

/**
 * Sobreescribo el metodo drawPlayer de mediaPlayer para su propia implementacion
 */
mediaPlayer.prototype.drawPlayer=function() {
	var windowlessVideo = "";
	if (this.settings.wMode=="transparent") {
		windowlessVideo = "true";
	}
	//ORIGINAL
	//var html = '<OBJECT ID="'+this.getPlayerWidgetId()+'" width="'+this.settings.width+'" height="'+this.settings.height+'" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"><PARAM name="autoStart" value="false" /><PARAM name="width" value="'+this.settings.width+'" /><PARAM name="height" value="'+this.settings.height+'" /><PARAM name="uiMode" value="none" /><PARAM name="showControls" value="false" /><PARAM name="windowlessVideo" value="'+windowlessVideo+'"/><PARAM name="volume" value="'+this.getVolume()+'"/><PARAM name="mute" value="'+this.getMute()+'"/><PARAM name="stretchToFit" value="true"/></OBJECT>';
	var size = this.widget._getSizeByName(this.widget.size());
	if ($.browser.msie) {
		var html =
		'<OBJECT ID="'+this.getPlayerWidgetId()+'"width="'+size.width+'" height="'+size.height+'" CLASSID="'+this.settings.embed+'"'+
				'<PARAM name="autoStart" value="false">'+
				'<PARAM name="uiMode" value="none">'+
				'<PARAM name="showControls" value="false">'+
				'<PARAM name="windowlessVideo" value="'+windowlessVideo+'">'+
				'<PARAM name="volume" value="'+this.getVolume()+'">'+
				'<PARAM name="mute" value="'+this.getMute()+'">'+
		'</OBJECT>';
		//Si maneja licencias entonces creo el object de DRM
		if (this.settings.urlPreDelivery) {
			html += '<OBJECT classid="clsid:A9FC132B-096D-460B-B7D5-1DB0FAE0C062" height="0" id="drm" width="0"></object>'; 
		}
	} else {
		var html =
		'<OBJECT type="application/x-ms-wmp" id="'+this.getPlayerWidgetId()+'"width="'+size.width+'" height="'+size.height+'">'+
				'<PARAM name="autoStart" value="false">'+
				'<PARAM name="uiMode" value="none">'+
				'<PARAM name="showControls" value="false">'+
				'<PARAM name="windowlessVideo" value="'+windowlessVideo+'">'+
				'<PARAM name="volume" value="'+this.getVolume()+'">'+
				'<PARAM name="mute" value="'+this.getMute()+'">'+
		'</OBJECT>';
	}
		
	//$("#"+this.settings.videoDivId).html(html);
	//document.getElementById(this.settings.videoDivId).insertAdjacentHTML("beforeEnd",html);
	if ($.browser.msie) {
		document.getElementById(this.settings.videoDivId).insertAdjacentHTML("beforeEnd",html);
	} else {
		$("#"+this.settings.videoDivId).append(html);		
	}

	//COMO NO TENGO EVENTO QUE DIGA QUE ESTA LISTO SETEO TODO ACA
	setTimeout("mediaPlayerReady('"+this.getPlayerWidgetId()+"');",1);
}

/**
 * Sobreescribo el metodo openUrl para su propia implementacion
 */
mediaPlayer.prototype.openUrl=function(media) {
	this.parent.openUrl.call(this,media)
	if (this.openState == OPEN_STATE_OPENING) {
		if (this.player != null) {
			this.player.URL = media.url;
		}
	}
}

/**
 * Funcion que hace play de un video en el player de flash
 */
mediaPlayer.prototype.play=function() {
	if (this.player != null) {		
		if (this.fireBeforePlay()) {
			this.player.controls.play();
		}
	}
}	

/**
 * Funcion que pausa la reproduccion en el media player
 */
mediaPlayer.prototype.pause=function() {
	if (this.player != null) {
		this.player.controls.pause();
	}
}

/**
 * Funcion que hace stop de un video en el player de flash
 */
mediaPlayer.prototype.stop=function() {
	if (this.player != null && this.player.controls != null) {
		this.player.controls.stop();
	}
}

/**
 * Cierra el contenido cargado actualmente
 */
mediaPlayer.prototype.close = function() {
	if (this.player != null) {
		this.player.close();
	}
	this.parent.close.call(this);
}

/**
 * Obtengo la duracion del video en segundos
 */
mediaPlayer.prototype.getMediaLength = function() {
	//return this._mediaLength;
	if (this.player.currentMedia) {
		return this.player.currentMedia.duration;		
	} 
}

/**
 * Obtengo la posicion actual de reproduccion
 */
mediaPlayer.prototype.getMediaPosition = function() {
	if (this.player != null) {
		this._mediaPosition = this.player.controls.currentPosition;
	}
	return this._mediaPosition; 
}

/**
 * Seteo la posicion actual de reproduccion
 */
mediaPlayer.prototype.setMediaPosition = function(position) {
	if (this.player != null) {
		this.player.controls.currentPosition = position;
		this._mediaPosition = position;
	}
}

mediaPlayer.prototype.getVolume = function() {
	var ret = 0;
	if (this.player != null) {
		ret = this.player.settings.volume;
	} else {
		ret = this.parent.getVolume.call(this);
	}
	return ret;
}

mediaPlayer.prototype.setVolume = function(value) {
	if (this.player != null) {
		this.player.settings.volume = value;
	}
	this.parent.setVolume.call(this,value); 
}

mediaPlayer.prototype.getMute = function() {
	var ret = this.parent.getMute.call(this);
	if (this.player != null) {
		ret = this.player.settings.mute;
	}
	return ret;
}

mediaPlayer.prototype.setMute = function(value) {	
	if (this.player != null) {
		this.player.settings.mute = value;
	}
	this.parent.setMute.call(this,value); 
}

mediaPlayer.prototype.deAttachAll = function() {
	this.parent.deAttachAll.call(this);
	var currentPlayer = getPlayerObject(this.getPlayerWidgetId());
}

/**
 * Destruyo la instancia del mediaplayer
 */
mediaPlayer.prototype.destroy = function() {
	this.parent.destroy.call(this); //Llamo al padre
	$("#"+this.getPlayerWidgetId()).remove(); //quito el object
	//quito el objeto drm
	$("#drm").remove();
}

mediaPlayer.prototype.getFullScreen = function() {
	if (this.player != null) {
		return this.player.fullScreen;
	}
}

mediaPlayer.prototype.toggleFullScreen = function() {
	if (this.player != null) {
		this.player.fullScreen = !this.getFullScreen();
	}
}

/** 
 * Esta funcion es llamada por el media playerpara indicar que esta listo y se puede interactuar con el
 */
function mediaPlayerReady(id) {	
	//Pregunto cual es el currenPlayer instanciado y disparo el firePlayerReady para avisar que ya se puede usar
	var currentPlayer = getPlayerObject(id);
	//Asigno el objeto flash al objeto flashPlayer
	if (currentPlayer) {
		//Instancia real del objeto
		currentPlayer.player = document.getElementById(currentPlayer.getPlayerWidgetId());
		currentPlayer.player.attachEvent("openStateChange",function(state) {
			if (state == 13) {
				if (currentPlayer.openState == OPEN_STATE_OPENING) {
					currentPlayer.fireMediaLoaded();
				}								
			}
		});
		currentPlayer.player.attachEvent("playStateChange",function(state) {
			var newState = "";
			switch(state) {
				case 1: //Stoped
					newState = PLAY_STATE_STOPED;
					break;
				case 2: //Paused
					newState = PLAY_STATE_PAUSED;
					break;
				case 3: //Playing
					newState = PLAY_STATE_PLAYING;
					break;
				case 8: // Finalizado
					newState = PLAY_STATE_COMPLETED;
					break;
			}
			if (newState != "") {
				currentPlayer.fireStateChanged(newState);
			}
		});
		currentPlayer.player.attachEvent("error",function() {
			var err = "";
			for(var i = 0; i < currentPlayer.player.error.errorCount; i++) {
				err += "["+currentPlayer.player.error.item(i).errorCode+"] "+currentPlayer.player.error.item(i).errorDescription;
			}
			currentPlayer.fireError(err);
		});
		//Seteo otras variables y disparo el evento playerReady
		currentPlayer.isReady = true;
		currentPlayer.firePlayerReady();
	}
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// OBJETO PLAYER DE SILVERLIGHT Y FUNCION slPlayerReady PARA SABER CUANDO ESTA LISTO EL PLAYER PARA USAR
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

function slPlayer(settings,widget) {
	this.parentConstructor.call(this,settings,widget); 
	this.type = "silverlight";	
}
slPlayer.inheritsFrom(basePlayer); //Aca el objeto mediaPlayer HEREDA de basePlayer

/**
 * Sobreescribo el metodo drawPlayer de mediaPlayer para su propia implementacion
 */
slPlayer.prototype.drawPlayer=function() {
	var windowlessVideo = "";
	if (this.settings.wMode=="transparent") {
		windowlessVideo = "true";
	}
	//ORIGINAL
	//var html = '<OBJECT ID="'+this.getPlayerWidgetId()+'" width="'+this.settings.width+'" height="'+this.settings.height+'" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"><PARAM name="autoStart" value="false" /><PARAM name="width" value="'+this.settings.width+'" /><PARAM name="height" value="'+this.settings.height+'" /><PARAM name="uiMode" value="none" /><PARAM name="showControls" value="false" /><PARAM name="windowlessVideo" value="'+windowlessVideo+'"/><PARAM name="volume" value="'+this.getVolume()+'"/><PARAM name="mute" value="'+this.getMute()+'"/><PARAM name="stretchToFit" value="true"/></OBJECT>';
	var size = this.widget._getSizeByName(this.widget.size());
	var html = $('<object id="'+this.getPlayerWidgetId()+'" data:"application/x-silverlight-2," type="application/x-silverlight-2" width="'+size.width+'" height="'+size.height+'"><param name="source" value="'+this.settings.embed+'"/><param name="background" value="white"/><param name="minRuntimeVersion" value="2.0.31005.0"/><param name="autoUpgrade" value="true"/><param name="windowless" value="true"/><param name="initparams" value="autoStart=false,volume='+this.getVolume()+',mute='+this.getMute()+',allowFullScreen='+this.settings.allowFullScreen+',actionDefault=fullscreen"/></object>').appendTo($("#"+this.settings.videoDivId));
	
	//var html = '<object id="'+this.getPlayerWidgetId()+'" data:"application/x-silverlight-2," type="application/x-silverlight-2" width="'+size.width+'" height="'+size.height+'"><param name="source" value="'+this.settings.embed+'"/><param name="background" value="white"/><param name="minRuntimeVersion" value="2.0.31005.0"/><param name="autoUpgrade" value="true"/><param name="windowless" value="true"/><param name="initparams" value="autoStart=false,volume='+this.getVolume()+',mute='+this.getMute()+',allowFullScreen='+this.settings.allowFullScreen+',actionDefault=fullscreen"/></object>';	
	//$("#"+this.settings.videoDivId).html(html);
}

/**
 * Sobreescribo el metodo openUrl para su propia implementacion
 */
slPlayer.prototype.openUrl=function(media) {
	this.parent.openUrl.call(this);
	if (this.player != null) {
		this.player.open(media.url);
	}
}

/**
 * Sobreescribo esta funcion para silverligth ya que si se hace play de un contenido
 * que finalizo tengo que primero voler la posicion a 0 y luego hacer el play
 */
slPlayer.prototype.fireBeforePlay = function () {
	if (this.playState == PLAY_STATE_COMPLETED) {		
		this.setMediaPosition(0);
	}
	return this.parent.fireBeforePlay.call(this);	
}

/**
 * Funcion que hace play de un video en el player de flash
 */
slPlayer.prototype.play=function() {
	if (this.player != null) {
		if (this.fireBeforePlay()) {
			this.player.play();
		}
	}
}	

/**
 * Funcion que pausa la reproduccion en el media player
 */
slPlayer.prototype.pause=function() {
	if (this.player != null) {
		this.player.pause();
	}
}

/**
 * Funcion que hace stop de un video en el player de flash
 */
slPlayer.prototype.stop=function() {
	if (this.player != null) {
		this.player.stop();
	}
}

/**
 * Cierra el contenido activo
 */
slPlayer.prototype.close = function() {
	if (this.player != null) {
		this.player.close();
	}
	this.parent.close.call(this);	
}

/**
 * Obtengo la duracion del video en segundos
 */
slPlayer.prototype.getMediaLength = function() {
	return this._mediaLength;
}

/**
 * Obtengo la posicion actual de reproduccion
 */
slPlayer.prototype.getMediaPosition = function() {
	if (this.player != null) {
		this._mediaPosition = this.player.position;
	}
	return this._mediaPosition; 
}

/**
 * Seteo la posicion actual de reproduccion
 */
slPlayer.prototype.setMediaPosition = function(position) {
	if (this.player != null) {
		this.player.position = position;
		this._mediaPosition = position;
	}
}

slPlayer.prototype.getVolume = function() {
	var ret = 0;
	if (this.player != null) {
		ret = this.player.volume;
	} else {
		ret = this.parent.getVolume.call(this);
	}
	return ret;
}

slPlayer.prototype.setVolume = function(value) {
	if (this.player != null) {
		this.player.volume = value;
	}
	this.parent.setVolume.call(this,value); 
}

slPlayer.prototype.getMute = function() {
	var ret = this.parent.getMute.call(this);
	if (this.player != null) {
		ret = this.player.isMuted;
	}
	return ret;
}

slPlayer.prototype.setMute = function(value) {	
	if (this.player != null) {
		this.player.isMuted = value;
	}
	this.parent.setMute.call(this,value); 
}

slPlayer.prototype.deAttachAll = function() {
	this.parent.deAttachAll.call(this);
	var currentPlayer = getPlayerObject(this.getPlayerWidgetId());
}

/**
 * Destruyo la instancia del mediaplayer
 */
slPlayer.prototype.destroy = function() {
	this.parent.destroy.call(this); //Llamo al padre
	$("#"+this.getPlayerWidgetId()).remove(); //quito el object
}

slPlayer.prototype.getFullScreen = function() {
	if (this.player != null) {
		return this.player.isFullScreen;
	}
}

slPlayer.prototype.toggleFullScreen = function() {
	if (this.player != null) {
		this.player.isFullScreen = !this.getFullScreen();
	}
}

/**
 * Esta funcion es disparada por el player de silverlight para avisar que esta listo para poder ser usado
 */
function slPlayerReady(id) {
	//Pregunto cual es el currenPlayer instanciado y disparo el firePlayerReady para avisar que ya se puede usar
	var currentPlayer = getPlayerObject(id);
	if (currentPlayer) {
		//Asigno el objeto al objeto slPlayer
		currentPlayer.player = document.getElementById(currentPlayer.getPlayerWidgetId()).content.player;
		//Me engancho de los eventos
		currentPlayer.player.onLoaded = function(sender,e) {
			var currentPlayer = getPlayerObject(sender.playerId);
			if (currentPlayer) {
				currentPlayer._mediaLength = currentPlayer.player.duration;
				currentPlayer.fireMediaLoaded();			
			}
		};	
		currentPlayer.player.onCompleted = function(sender,e) {
			var currentPlayer = getPlayerObject(sender.playerId);
			if (currentPlayer) {
				currentPlayer.fireStateChanged(PLAY_STATE_COMPLETED);			
			}
		};
		currentPlayer.player.onError = function(sender,e) {
			var currentPlayer = getPlayerObject(sender.playerId);
			if (currentPlayer) {
				currentPlayer.fireError(e.message);					
			}
		};
		currentPlayer.player.onStateChange = function(sender,e) {
			var newState = "";
			switch(e.newState) {
				case 3: //Playing
					newState = PLAY_STATE_PLAYING;
					break;
				case 4: //Paused
					newState = PLAY_STATE_PAUSED;
					break;
				case 5: //Stoped
					newState = PLAY_STATE_STOPED;
					break;
			}
			if (newState != "") {
				var currentPlayer = getPlayerObject(sender.playerId);
				if (currentPlayer && currentPlayer.fireStateChanged) {
					currentPlayer.fireStateChanged(newState);				
				}
			}
		};			
		currentPlayer.isReady = true;
		currentPlayer.firePlayerReady();		
	}
}