function updateHTML(elmId, value) {
	document.getElementById(elmId).innerHTML = value;
}

function setytplayerState(newState) {
	updateHTML("playerstate", newState);
}

var intervalo;

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	
	/* Carga el cronJob */
	intervalo = setInterval(cronJob, 500);
	cronJob();
	
	/* Prepara la lista de canciones */
	array_tracks = preparaTracks();
	
	/* Escucha botones asociado a cada cancion */
	escucharBotonesPlay(array_tracks.length);
	
	/* Inicia el reproductor */
	youtube_player = new youtube_player(array_tracks);
	youtube_player.playVideo();
}

function onytplayerStateChange(newState) {
	setytplayerState(newState);
}

/* Youtube API */
function loadNewVideo(id, startSeconds) {
	if (ytplayer) {
		if (id != 0) {
			document.getElementById('adecuado').style.display = 'none';
			document.getElementById('marca').style.display = 'none';
			ytplayer.unMute();
			ytplayer.loadVideoById(id, parseInt(startSeconds));
		} else {
			youtube_player.nextVideo();
		}
	}
}

function cueNewVideo(id, startSeconds) {
	if (ytplayer) {
		ytplayer.cueVideoById(id, startSeconds);
	}
}

function play() {
	if (ytplayer) {
		ytplayer.playVideo();
	}
}

function pause() {
	if (ytplayer) {
		ytplayer.pauseVideo();
	}
}

function stop() {
	if (ytplayer) {
		ytplayer.stopVideo();
	}
}

function getPlayerState() {
	if (ytplayer) {
		return ytplayer.getPlayerState();
	}
}

function seekTo(seconds) {
	if (ytplayer) {
		ytplayer.seekTo(seconds, true);
		if (youtube_player.paused) {
			pause();
		}
	}
}

function getBytesLoaded() {
	if (ytplayer) {
		return ytplayer.getVideoBytesLoaded();
	}
}

function getBytesTotal() {
	if (ytplayer) {
		return ytplayer.getVideoBytesTotal();
	}
}

function getCurrentTime() {
	if (ytplayer) {
		currentTime = ytplayer.getCurrentTime();
		return currentTime;
	}
}

function getDuration() {
	if (ytplayer) {
		return ytplayer.getDuration();
	}
}

function getTimeLeft() {
	if (ytplayer) {
		duration = ytplayer.getDuration();
		current = ytplayer.getCurrentTime();
		return duration - current;
	}
}

function getStartBytes() {
	if (ytplayer) {
		return ytplayer.getVideoStartBytes();
	}
}

function mute() {
	if (ytplayer) {
		ytplayer.mute();
	}
}

function unMute() {
	if (ytplayer) {
		ytplayer.unMute();
	}
}

function getEmbedCode() {
	alert(ytplayer.getVideoEmbedCode());
}

function getVideoUrl() {
	alert(ytplayer.getVideoUrl());
}

function setVolume(newVolume) {
	if (ytplayer) {
		ytplayer.setVolume(newVolume);
	}
}

function getVolume() {
	if (ytplayer) {
		return ytplayer.getVolume();
	}
}

function clearVideo() {
	if (ytplayer) {
		ytplayer.clearVideo();
	}
}

function setSize(width, height) {
	if (ytplayer) {
		ytplayer.setSize(width, height);
	}
}

/* Secondary functions */


function intToTime(time) {
	if (time < 0) time = 0;
	time = parseInt(time);
	
	minutes = time / 60;
	seconds = time % 60;
	
	str_minutes = parseInt(minutes);
	
	if (seconds < 10) str_seconds = "0"+seconds;
	else str_seconds = seconds;
	
	return str_minutes+":"+str_seconds;
}
id_global="";
function obtenerYoutubeId(track) {
    $.ajax({
        type: "POST",
        url: "../../../../../getYoutubeId",
        data: "query="+track,
		async: false,
        success: function procesarId(xml) {

            $(xml).find('nodo').each(function() {
                var id;
                id = $(this).find('valor0').text();
		id_global = id;
		document.getElementById('alt1').innerHTML = $(this).find('valor1').text();
		document.getElementById('alt2').innerHTML = $(this).find('valor2').text();
		document.getElementById('alt3').innerHTML = $(this).find('valor3').text();
		document.getElementById('alt4').innerHTML = $(this).find('valor4').text();
		document.getElementById('alt5').innerHTML = $(this).find('valor5').text();				
                return id;
            });

        }
    });
	
	return id_global;
	

}

function obtenerLetra(artist,title) {
    $.ajax({
        type: "POST",
        url: "../../../../../getLyric",
        data: "cr.artist="+artist+"&cr.title="+title,
        success: function procesarLetra(xml) {

            $(xml).find('nodo').each(function() {

                var titulo = document.getElementById('artista_titulo');
                titulo.innerHTML =  Url.decode(artist +" - "+ title);

                var letra = '';
                letra = $(this).find('letra').text();
                var url = $(this).find('url').text();
                var url_name = $(this).find('url_name').text();
                var url_image = $(this).find('url_image').text();

                //cragr artista y titulo en cabecera reproductor
                letra = letra.replace(/\n/g,"<br/>");

                document.getElementById('letras_h3').innerHTML = "Letra de la canci&oacute;n";
                document.getElementById('letra_cancion').innerHTML = Url.decode(letra);

		if (letra != 'Letra no disponible'){

                    //borrar anterior
                    var d = document.getElementById('letras');
                    var olddiv = document.getElementById("img_letra");
                    if (olddiv!= null){
                        d.removeChild(olddiv);
                    }


                    
                }else{
                    //borrar anterior
                    var d = document.getElementById('letras');
                    var olddiv = document.getElementById("img_letra");
                    if (olddiv!= null){
                        d.removeChild(olddiv);
                    }

                }
            });
        }
    });
}

function setShareLinks(artista, titulo, id) {
	$('#facebook a').attr('href', 'http://www.facebook.com/sharer.php?u=http://www.youtube.com/watch?v='+id);
	$('#tuenti a').attr('href', 'http://www.tuenti.com/#m=sharevideo&id='+id);
	$('#myspace a').attr('href', 'http://www.myspace.com/Modules/PostTo/Pages/?t='+artista+'-'+titulo+'&c=%3Cobject%20width%3D%22425%22%20height%3D%22355%22%3E%3Cparam%20name%3D%22movie%22%20value%3D%22http%3A//www.youtube.com/v/'+id+'+%26hl%3Des%26rel%3D0%22%3E%3C/param%3E%3Cembed%20src%3D%22http%3A//www.youtube.com/v/'+id+'%26hl%3Des%26rel%3D0%22%20type%3D%22application/x-shockwave-flash%22%20width%3D%22425%22%20height%3D%22355%22%3E%3C/embed%3E%3C/object%3E&u=http://www.youtube.com/watch?v='+id+'&l=1');

}

function marcarTema(actual, number) {
	for (n=0; n<number; n++) {
		$("#fila"+n).css('background-color', '#f1f1f1');
	}
	$("#fila"+actual).css('background-color', '#999');
	return false;
}

function revisarPaginacion(actual) {
	var elementos = 25;
	
	pagina = Math.ceil((actual+1)/elementos);
	
	//alert((actual+1) + "/" + elementos  + "=" + pagina);
	
	$('#player > table tbody tr').each(function(i) {
	
		if ((i < (elementos * (pagina-1))) || i >= elementos * pagina) 
			$(this).css('display', 'none');
		else 
			$(this).css('display', '');
	});
	
	$("#paginacion").pagination($('#player > table tbody tr').length, {
		items_per_page: elementos,
		current_page: pagina-1,
		callback: function(id, container) {
			
			$('#player > table tbody tr').each(function(i) {
				if (i >= id*elementos && i < (id*elementos)+elementos) 
					$(this).css('display', '');
				else 
					$(this).css('display', 'none');
			});
			
			return false;
		}
	});
}

function escucharBotonesPlay(number) {
	
	$('#player table tbody tr').each(function(x) {
		
		
		$(this).find('.play a').click(function() {
			//alert(i);
			youtube_player.playVideoByNumber(x);
			
			return false;
		});
		
	});

}



function getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	var arrayPageScroll = {'xScroll':xScroll,'yScroll':yScroll};
	return arrayPageScroll;
}

function getPageSize() {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}


	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	//
	var largestWidth;
	var largestHeight;
	var smallestWidth;
	var smallestHeight;
	//
	if ( pageWidth >= windowWidth )
	{	largestWidth = pageWidth; smallestWidth = windowWidth;	}
	else
	{	largestWidth = windowWidth; smallestWidth = pageWidth;	}
	//
	if ( pageHeight >= windowHeight )
	{	largestHeight = pageHeight; smallestHeight = windowHeight;	}
	else
	{	largestHeight = windowHeight; smallestHeight = pageHeight;	}
	
	// Return
	var arrayPageSize = {'pageWidth':pageWidth,'pageHeight':pageHeight,'windowWidth':windowWidth,'windowHeight':windowHeight,'largestWidth':largestWidth,'largestHeight':largestHeight};
	return arrayPageSize;
}

/* Player Object */

var youtube_player = function(list) {
	
	this.setRepeat = function() {
		this.repeat = !this.repeat;
		if (this.repeat) {
			$('#repeat a').addClass('on');
		}
		else {
			$('#repeat a').removeClass('on');
		}
	};
	
	this.setRandom = function() {
		this.random = !this.random;
		if (this.random) {
			this.list.sort(function() {return 0.5 - Math.random()});
			$('#random a').addClass('on');
		}
		else {
			this.current = this.list[this.current].orden;
			
			this.list.sort(function(x,y) { 
				if (x.orden < y.orden) return -1;
				if (x.orden > y.orden) return 1;
				return 0;
			});
			/*
			this.list = undefined;
			this.list = this.list_aux;
			*/
			$('#random a').removeClass('on');
		}
	};

	this.nextVideo = function() {
		$('#timeline > div:first').css('display', 'block');
		this.ended = false;
		
		if (this.current >= this.list.length-1) {
			if (this.repeat) {
				this.current = 0;
				if (this.list[this.current].id == undefined) {
					this.list[this.current].id = obtenerYoutubeId(this.list[this.current].artista+" - "+this.list[this.current].titulo);
					this.list_aux[this.current].id = this.list[this.current].id;
				}
				loadNewVideo(this.list[this.current].id, 0);
				setShareLinks(this.list_aux[this.current].artista, this.list_aux[this.current].titulo, this.list_aux[this.current].id);
				obtenerLetra(this.list_aux[this.current].artista, this.list_aux[this.current].titulo);
			}
		}
		else {
			this.current += 1;
			if (this.list[this.current].id == undefined) {
				this.list[this.current].id = obtenerYoutubeId(this.list[this.current].artista+" - "+this.list[this.current].titulo);
				this.list_aux[this.current].id = this.list[this.current].id;
			}
			loadNewVideo(this.list[this.current].id, 0);
			setShareLinks(this.list_aux[this.current].artista, this.list_aux[this.current].titulo, this.list_aux[this.current].id);
			obtenerLetra(this.list_aux[this.current].artista, this.list_aux[this.current].titulo);
		}
		marcarTema(this.list[this.current].orden, this.list.length);
		revisarPaginacion(this.list[this.current].orden);
		$('#progreso').css('left', '0px');
		
	};
	
	this.prevVideo = function() {
		$('#timeline > div:first').css('display', 'block');
		this.ended = false;
		
		if (this.current <= 0) {
			if (this.repeat) {
				this.current = list.length-1;
				
				if (this.list[this.current].id == undefined) {
					this.list[this.current].id = obtenerYoutubeId(this.list[this.current].artista+" - "+this.list[this.current].titulo);
					this.list_aux[this.current].id = this.list[this.current].id;
				}
				loadNewVideo(this.list[this.current].id, 0);
				setShareLinks(this.list_aux[this.current].artista, this.list_aux[this.current].titulo, this.list_aux[this.current].id);
				obtenerLetra(this.list_aux[this.current].artista, this.list_aux[this.current].titulo);
			}
		}
		else {
			this.current -= 1;
			if (this.list[this.current].id == undefined) {
				this.list[this.current].id = obtenerYoutubeId(this.list[this.current].artista+" - "+this.list[this.current].titulo);
				this.list_aux[this.current].id = this.list[this.current].id;
			}
			loadNewVideo(this.list[this.current].id, 0);
			setShareLinks(this.list_aux[this.current].artista, this.list_aux[this.current].titulo, this.list_aux[this.current].id);
			obtenerLetra(this.list_aux[this.current].artista, this.list_aux[this.current].titulo);
		}
		marcarTema(this.list[this.current].orden, this.list.length);
		revisarPaginacion(this.list[this.current].orden);
		$('#progreso').css('left', '0px');
	};
	
	this.playVideo = function() {
		this.ended = false;
		if (this.paused) {
			play();
			$('#pausa a').removeClass('on');
			this.paused = false;
		}
		else {
			if (this.list[this.current].id == undefined) {
				this.list[this.current].id = obtenerYoutubeId(this.list[this.current].artista+" - "+this.list[this.current].titulo);
				//alert(obtenerYoutubeId(this.list[this.current].artista+" "+this.list[this.current].titulo));
				this.list_aux[this.current].id = this.list[this.current].id;
			}
			//alert("play video le llega el id como: "+this.list[this.current].id)
			loadNewVideo(this.list[this.current].id, 0);
			setShareLinks(this.list_aux[this.current].artista, this.list_aux[this.current].titulo, this.list_aux[this.current].id);
			obtenerLetra(this.list_aux[this.current].artista, this.list_aux[this.current].titulo);
			marcarTema(this.list[this.current].orden, this.list.length);
			revisarPaginacion(this.list[this.current].orden);
			$('#progreso').css('left', '0px');
		}
	};
	
	this.playVideoByNumber = function(number) {
		$('#timeline > div:first').css('display', 'block');
		for (v=0; v<this.list.length; v++) {
			if (this.list[v].orden == number) {
				this.current = v;
				this.playVideo();
			}
		}
	
	}
	
	this.pauseVideo = function() {
		this.paused = !this.paused;
		
		if (this.paused) {
			$('#pausa a').addClass('on');
			pause();
		}
		else {
			$('#pausa a').removeClass('on');
			play();
			this.paused = false;
		}
	}
	
	this.stopVideo = function() {
		this.ended = false;
		this.current = 0;
		stop();
		marcarTema(this.current, this.list.length);
	}
	
	this.setFullscreen = function() {
		
		this.fullscreen = !this.fullscreen;
		
		if (this.fullscreen) {
			pageScroll = getPageScroll();
			pageSize = getPageSize();
			//alert(pageScroll.xScroll + "-" + pageScroll.yScroll);
			//alert(pageSize.pageWidth + "-" +pageSize.pageHeight);
			//alert(pageSize.windowWidth + "-" +pageSize.windowHeight);
			
			$('#player-object').css('position','absolute');
			$('#player-object').css('top',pageScroll.yScroll);
			$('#player-object').css('left','0');
			$('#player-object').css('width', pageSize.windowWidth+'px');
			$('#player-object').css('height', pageSize.windowHeight+'px');
			$('#myytplayer').attr('width', pageSize.windowWidth);
			$('#myytplayer').attr('height', pageSize.windowHeight-40);
			setSize(pageSize.windowWidth, pageSize.windowHeight-40);		
			$('body').css('overflow', 'hidden');
			
		}
		else {
			$('#player-object').css('position','relative');
			$('#player-object').css('width','400px');
			$('#player-object').css('height','300px');
			$('#myytplayer').attr('width', '400');
			$('#myytplayer').attr('height', '300');
			setSize(400, 300);
			$('body').css('overflow', 'auto');
		}
		
	}

	this.list = list;
	this.list_aux = list;
	this.current = indice;
	this.repeat = false;
	this.random = false;
	this.ended = true;
	this.paused = false;
	this.fullscreen = false;
		
}

compartir_enlaces = false;

function calculateNow() {
	currentTime = getCurrentTime();
	duration = getDuration();
	
	return (currentTime*100)/duration;
}

moved = false;

function updateControl(width, controlWidth) {
	if (!width) {
		width=400;
	}
	if (!controlWidth) {
		controlWidth = 23;
	}
	width = width - controlWidth;
	porcentajeControl = calculateNow();
	pxPosition =(porcentajeControl*width)/100;
	//pxPosition = pxPosition;
	/*
	if (moved) {
		pxPosition = pxPosition -20;
	}
	*/
	$('#control').css('left', pxPosition+'px');
	
	//alert(pxPosition);
	
	//clearInterval(intervalo);
}

function calculateProgress() {
	bytesLoaded = getBytesLoaded();
	bytesTotal = getBytesTotal();
	
	return (bytesLoaded*100)/bytesTotal;
}

function updateProgress() {
	porcentaje = calculateProgress();
	$('#progreso').css('width', porcentaje+'%');
}

$(document).ready(function() {
	$('#compartir-enlaces').css('display', 'none');
	$('#progreso').wrap('<div style="margin-left:23px" id="wrapper-progreso"></div>');
	$('#timeline').prepend('<div style="position:absolute;top:0;left:0;width:23px;background:#4DA8C1 url(../../../../../grafica/reproductor/progreso.png) repeat-x scroll 0 0;height:8px">&nbsp;</div>');
	$('#compartir a').click(function() {
		compartir_enlaces = !compartir_enlaces;
		if (compartir_enlaces) {
			$('#compartir-enlaces').css('display', 'block');
		}
		else {
			$('#compartir-enlaces').css('display', 'none');
		}
	});
	$('#timeline').click(function(e) {

		positionControlLeft = e.pageX - findPosX(document.getElementById('wrapper-progreso'));

		$('#progreso').css('width', '0');
		$('#timeline > div:first').css('display', 'none');
		//$('#wrapper-progreso').css('margin-left', '0');
		
		//alert(positionControlLeft);
		widthTimeline = $('#timeline').width() - 23;
		
		seconds = ((positionControlLeft + 23) * getDuration()) / widthTimeline;
		//alert(seconds);
		seekTo(seconds);
		
		$('#control').css('left', positionControlLeft+'px');
		$('#progreso').css('left', positionControlLeft+23+'px');
		
		moved = true;
			
		//positionNow = $('#control').position();
	});
	$('#control').Draggable(
		{
			//zIndex: 	1,
			ghosting:	true,
			opacity: 	1,
			containment : 'timeline',
			axis:	'horizontally',
			insideParent: true,
			onStart: function() {
				changeDragControl();
			},
			onStop: function() {
			
				clearInterval(intervalo);
				$('#progreso').css('width', '0');
				$('#timeline > div:first').css('display', 'none');
				//$('#wrapper-progreso').css('margin-left', '0');
				
				positionControl = $('#control').position();
				widthTimeline = $('#timeline').width() - 23;
				
				seconds = ((positionControl.left + 23) * getDuration()) / widthTimeline;
				//alert(seconds);
				seekTo(seconds);
				
				$('#control').css('left', positionControl.left+'px');
				$('#progreso').css('left', positionControl.left+23+'px');
					
				positionNow = $('#control').position();
				//alert("arrastrado hasta:" +(positionNow.left+23));
				changeDragControl();
				
				intervalo = setInterval(cronJob, 500);
				
				moved = true;
				
			}
		}
	);

});

function findPosX(obj)
{
      var curleft = 0;
      if (obj.offsetParent)
      {
              while (obj.offsetParent)
              {
                      curleft += obj.offsetLeft
                      obj = obj.offsetParent;
              }
      }
      else if (obj.x)
              curleft += obj.x;
      return curleft;
}