	var player = null;
	var currentPosition = 0;
	var currentState = 'NONE';
	var currentItem = -1;
	
	var indexPlaylist = Array();
	 
	function playerReady(obj) {
		if (player){	// Se ha hecho antes el onload que el playerReady
			player.sendEvent('LOAD', lst);
			if (!inDev())	// Para que no se reproduzca en desarrollo
				player.sendEvent('PLAY');
		}
		else		
			player = window.document[obj.id];
		
		addListeners();
	}

	function addListeners() {
		if (player) {
			player.addModelListener("TIME", "positionListener");
			player.addModelListener("STATE", "stateListener");
			player.addControllerListener("ITEM", "itemListener");
		} else {
			setTimeout("addListeners()",100);
		}
	}
	
	function positionListener(obj) {
		currentPosition = obj.position;
	}

	function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
		currentState = obj.newstate;
	}
	
	function itemListener(obj) {
		if (obj.index != currentItem) {
			//previousItem = currentItem;
			currentItem = obj.index;
		}
	}
	
	
	
//	function volumeListener(obj) {
//		currentVolume = obj.percentage;
//	}

/**
 * yaEsta es un texto que se muestra en caso de que el tema ya esté en el playlist
 */
function addToPlayList(id, artistaVersionId, tema, artista, estilo, foto, fichero, tipo, nombreColor, yaEsta, link){
	var temaId = '' + id + (artistaVersionId ? '_' + artistaVersionId : '');
	
	if (!isNull(document.getElementById('indexPL_' + temaId).value)){
		showAlert(null, yaEsta);
	}
	else{
		var emptyPlayer = isPlaylistEmpty();
		var playerPlay = isPlayingPlayer();
		var position = currentPosition;
		
		addToPL(id, artistaVersionId, tema, artista, estilo, foto, fichero, tipo, nombreColor, link);
		var lst = createItem(tema, artista, estilo, foto, fichero, tipo, nombreColor, link);
		
		if (!emptyPlayer){
			if (playerPlay)
				player.sendEvent('PLAY');
			player.sendEvent('SEEK', position);
		}
	}
		
}

/**
 * yaEsta no se utiliza aquí
 */
function play(id, artistaVersionId, tema, artista, estilo, foto, fichero, tipo, nombreColor, yaEsta, link){
	addToPL(id, artistaVersionId, tema, artista, estilo, foto, fichero, tipo, nombreColor, link);
	var temaId = '' + id + (artistaVersionId ? '_' + artistaVersionId : '');
	
	//player.sendEvent('ITEM', document.getElementById('indexPL_' + temaId).value);
	//console.log("temaId: " + temaId);
	//console.log(jwplayer());
	jwplayer().playlistItem(document.getElementById('indexPL_' + temaId).value);
}

/**
 * Función común que se llama desde addToPlayList y play
 */
function addToPL(id, artistaVersionId, tema, artista, estilo, foto, fichero, tipo, nombreColor, link){
	var player = jwplayer();
	var currentPlayList = player.getPlaylist();
	
	if (isPlaylistEmpty()){
		currentPlayList = new Array();
	}
	
	var temaId = '' + id + (artistaVersionId ? '_' + artistaVersionId : '');
	
	if (isNull(document.getElementById('indexPL_' + temaId).value)){	// Si no es null, no debería de llegar aquí
		//var lst = createItem(tema, artista, estilo, foto, fichero, tipo, nombreColor, link);
		//stopPlayer();
		
		if (isPlaylistEmpty())
			currentPlayList = new Array();
			
		if (foto)
			foto = "/images/releases/thumbnails/" + foto;
		else
			foto = "/images/no-disc.png";
			
		fichero = "/tracks/" + nombreColor + "/" + fichero;
		
		if (!estilo)
			estilo = "&nbsp;";
		
		currentPlayList = addItemToPlaylist(currentPlayList, artista, estilo, fichero, link, foto, tema);
		showItemPlaylist(id, artistaVersionId, currentPlayList.length - 1);
		jwplayer().load(currentPlayList);
		
		/*if (!isPlaylistEmpty()){
			currentPlayList.push(lst);
			
			player.sendEvent('LOAD', currentPlayList);
			
			showItemPlaylist(id, artistaVersionId, currentPlayList.length - 1);
			
		}
		else{
			player.sendEvent('LOAD', lst);
			showItemPlaylist(id, artistaVersionId, 0);
		}*/
	}
}

function isNull(dato){
	return dato == null || dato == '' || dato == 'null';
}
	
function createItem(tema, artista, estilo, foto, fichero, tipo, nombreColor, link){
	if (tipo == 'sound')
		fichero = '/tracks/' + nombreColor + '/' + fichero;

	var lst = {
		author:artista,
		description:estilo,
		file:fichero,
		//link:'/COL/' + culture + '/' + artista,
		link: link,
		image:'/images/releases/' + foto,
		title:tema,
		type:tipo
	}
	
	return lst;
}

/**
 * Devuelve un elemento dummy,
 * @param texto, título del elemento dummy
 */
function createVoidItem(texto){
	var lst = {
		author:null,
		description:null,
		file:'/mediaplayer/void.mp3',
		link:null,
		image:'/mediaplayer/black.gif',
		title:texto,
		type:'sound'
	}
	
	return lst;  
}

function savePlaylist(tituloError, mensajeError){
	if (isPlaylistEmpty())
		showAlert(tituloError, mensajeError, true);
	else{
		var items = "";
		
		for (var i=0; i<indexPlaylist.length; i++){
			var item = indexPlaylist[i];
			items += item;
			if (i < indexPlaylist.length-1)
				items += "|";
		}
		
		document.getElementById('tracks').value = items;
		document.getElementById('submitGuardarPlaylist').click();
	}
}

function removePlaylist(texto){
	var item = createVoidItem(texto);
	
	stopPlayer();

    //jwplayer().sendEvent("LOAD", item);
    jwplayer().load(item);
    
    for(var i=0; i<indexPlaylist.length; i++){
    	var idx = indexPlaylist[i];
    	
    	document.getElementById('indexPL_' + idx).value = null;
    	
		if (document.getElementById('delPL_'+ idx)){
			changeElement('delPL_' + idx, 'addPL_' + idx);
		}
	
		if (document.getElementById('p_delPL_' + idx)){
			changeElement('p_delPL_' + idx, 'p_addPL_' + idx);
		}
    }
    
    indexPlaylist = Array();
}

function isPlaylistEmpty(){
	return (indexPlaylist.length == 0);
}

/**
 * removeItemPlayList
 * Borra un item del playlist
 * @param id identificador del tema
 * @param texto texto que aparecerá en el playlist cuando no queden temas
 */
function removeItemPlayList(id, texto){
	var item = currentItem;	// Posición del índice que suena
	var playList = player.getPlaylist();
	var idx = document.getElementById('indexPL_'+id).value;
	var position = currentPosition;
	var playingBefore = isPlayingPlayer();
	
	playList.splice(idx, 1);
	indexPlaylist.splice(idx, 1);
	
	changeElement('delPL_' + id, 'addPL_' + id);
	
	if (document.getElementById('p_delPL_' + id)){
		changeElement('p_delPL_' + id, 'p_addPL_' + id);
	}
		
	document.getElementById('indexPL_'+id).value = null;
		
	// Actualizamos los campos hidden
	for (var i=idx; i<indexPlaylist.length; i++){
		var id = indexPlaylist[i];
		
		// Restamos a los campos hidden que había superiores al elemento borrado una posición
		var valor = document.getElementById('indexPL_'+id).value - 1;
		document.getElementById('indexPL_'+id).value = valor;
	}
	
	if (item > idx){
		item = item-1;		// Si el que hemos quitado está en una posición inferior, restamos una posición
		reinicePlayer();	// Pasamos el cursor a la posición inicial para que no de problemas
	}
	
	//stopPlayer();
	
	if (!indexPlaylist.length){	// Si se ha quedado el playlist vacío
		var element = createVoidItem(texto);
		player.sendEvent('LOAD', element);
	}
	else{
		player.sendEvent('LOAD', playList);

		// Hay un bug que da problemas a la hora de reproducir si idx es mayor que el archivo a reproducir
		if (playingBefore && idx != item){	//  && idx > item
			player.sendEvent('ITEM', item);
			player.sendEvent('SEEK', position);
		}
	}
}

/**
 * Reinicia el reproductor yendo a la primera posición en la que haya un tema y parándolo
 */
function reinicePlayer(){ 
	var encontrado = false;
	var i=0;
	var playlist = player.getPlaylist();
	
	// Buscamos el primer elemento que sea sonido (da menos problemas)
	while (!encontrado && i<playlist.length){
		econtrado = (playlist[i].type == 'sound');
		if (!encontrado)
			i++;
	}
	
	if (!encontrado)
		i=0;	// Si no hemos encontrado ningún tema, dejamos el primero
		
	player.sendEvent('ITEM', i);	// Vamos a la primera posición en el que haya un tema
	player.sendEvent('PLAY');	// Paramos el reproductor
}

/**
 * Función que para el reproductor y espera hasta que se haya parado
 */
function stopPlayer(){
	if (isPlayingPlayer()){
		player.sendEvent('PLAY');
		//while (!isStopPlayer()){}
	}
}

/**
 * Indica si el player está apagado
 */
function isStopPlayer(){
	return (currentState == 'PAUSED' || currentState == 'COMPLETED' || currentState == 'NONE');
}

/**
 * Función que actualiza el vector indexPlaylist y muestra el botón de eliminar del playlist
 */
function showItemPlaylist(id, artistaVersionId, posIndex){
	var post = (artistaVersionId ? '_'+artistaVersionId : '');
	indexPlaylist[posIndex] = '' + id + post;
	
	document.getElementById('indexPL_'+id+post).value = posIndex;
	
	changeElement('addPL_' + id + post, 'delPL_' + id + post);
	
	if (document.getElementById('p_delPL_' + id + post)){	// Aparece el botón de borrar en el top si existe
		changeElement('p_addPL_' + id + post, 'p_delPL_' + id + post);
	}
	
}

function isPlayingPlayer(){
	return (currentState == 'PLAYING' || currentState == 'COMPLETED' || currentState == 'BUFFERING');
}

function isPlayingBefore(state){
	return (state == 'PLAYING' || state == 'COMPLETED' || state == 'BUFFERING');
}

function addItemToPlaylist(playlist, author, description, file, link, image, title){
	//console.log("addItemToPlaylist:");
	//console.log("file: " + file);
	//console.log("image: " + image);
	//console.log("title: " + title);
	//console.log("description: " + description);
	
    var newItem = {
        author: author,
        description: description,
        file: file,
        link: link,
        image: image,
        title: title
    };
    playlist.push(newItem);
    
    return playlist;
}
