function xmlhttpPost(str,Url,tipo) {
	var xmlHttpReq = false;
	var self = this;
	var strURL = Url;
	self.opt=tipo;
	if (window.XMLHttpRequest) {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		try
	    {
	        self.xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
	    }   
	    catch (err)
	    {
	        try
	        {
	            self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	        }
	        catch (err2)
	        {
	        }
	    }
	}
	self.xmlHttpReq.open('POST', strURL, true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function(tipo) {
		if (self.xmlHttpReq.readyState == 4) {

			switch (self.opt){
				case 1:
					updatepage(self.xmlHttpReq.responseText);
				break;
				case 2:
					updateVotos(self.xmlHttpReq.responseText);
				break;
				case 3:
					updateSuscrito(self.xmlHttpReq.responseText);
				break;
				case 4:
					updateFormAgregarVideoAGrupo(self.xmlHttpReq.responseText);
				break;
				case 5:
					updateGrafica(self.xmlHttpReq.responseText);
				break;
			}
		}
	}
	self.xmlHttpReq.send(str);
}

function updatepage(str){
	document.getElementById("DIV-videoFavorito").innerHTML = str;
}

function updateSuscrito(str){
	document.getElementById("DIV-suscribirse").innerHTML = str;
}

function updateVotos(str){
	if (str=='Error') alert("ERROR");// document.getElementById("DIV-ERRORVOTACION").style.display='block';
	else {
		document.getElementById("DIV-NVOTOS").innerHTML = str;
		var noVotar='';
		noVotar+='<strong>¡Votado!</strong>&nbsp;';
		noVotar+='<a href="javascript:yaVotado();" alt="Voto negativo"><img src="/img/ico_voto_menos_off.gif" alt="Voto negativo"></a>&nbsp;';
		noVotar+='<a href="javascript:yaVotado();" alt="Voto negativo"><img src="/img/ico_voto_mas_off.gif" alt="Voto positivo"></a>';
		document.getElementById("DIV-VOTAR").innerHTML = noVotar;
		document.getElementById("DIV-VOTOS").className = 'votosvideo_votado';
	}
}

function videoFavorito(codVideo){
	qstr = 'codVideo=' + codVideo + '&tipo=1';  
	xmlhttpPost(qstr,"/verVideo/videosFavorito.phtml",1);
}
function quitarVideoFavorito(codVideo){
	qstr = 'codVideo=' + codVideo + '&tipo=2';  
	xmlhttpPost(qstr,"/verVideo/videosFavorito.phtml",1);
}
function suscribirse(codUsuario){
	qstr = 'codUsuario=' + codUsuario + '&tipo=1';  
	xmlhttpPost(qstr,"/verVideo/suscribirse.phtml",3);
}
function verGrafica(codVideo){
     if (document.getElementById("capagrafica").style.display == "none") {
		document.getElementById("lista_enlazan").style.display = "none";
		qstr = 'codVideo=' + codVideo;
		xmlhttpPost(qstr,"/verVideo/grafica.phtml",5);
     } else {
        document.getElementById("capagrafica").style.display="none";
     }
}
function quitarSuscrito(codUsuario){
	qstr = 'codUsuario=' + codUsuario + '&tipo=2';  
	xmlhttpPost(qstr,"/verVideo/suscribirse.phtml",3);
}
function votoPlus(codVideo){
	qstr = 'codVideo='+codVideo+'&voto=1';
	xmlhttpPost(qstr,"/verVideo/votoVideo.phtml",2);
}
function votoMinus(codVideo){
	qstr = 'codVideo='+codVideo+'&voto=0';
	xmlhttpPost(qstr,"/verVideo/votoVideo.phtml",2);
}


function estilos(num){
	switch (num) {
		case 1:
			document.getElementById("relacionados").className = 'selected';
			document.getElementById("masdelusuario").className = '';
			document.getElementById('relacionados2').style.display='block';
			document.getElementById('masdelusuario2').style.display='none';		
			break;
		
		case 2:
			document.getElementById("relacionados").className = '';
			document.getElementById("masdelusuario").className = 'selected';
			document.getElementById('relacionados2').style.display='none';
			document.getElementById('masdelusuario2').style.display='block';		
			break
		
		case 3:
			document.getElementById("relacionados").className = '';
			document.getElementById("masdelusuario").className = '';
			document.getElementById('relacionados2').style.display='none';
			document.getElementById('masdelusuario2').style.display='none';		
			break
		
		default:
			document.getElementById("relacionados").className = 'selected';
			document.getElementById("masdelusuario").className = '';
			document.getElementById('relacionados2').style.display='block';
			document.getElementById('masdelusuario2').style.display='none';
			break;
	}
}

var codVideo;
var enlace;
var registrado;
var pagina=1;

function init(video, enlaceComentarios, codUsuario) {
	codVideo=video;
	enlace=enlaceComentarios;
	OcultarTodosSubOpciones();
	ResetEstilosMenuSubOpciones();
	// capa de enviar visible por defecto
	document.getElementById('comparte_videos').style.display = '';
	document.getElementById('ln_enviar').className = 'mv_enviar selected';
	document.getElementById('marcador-seccion').className = 'seleccion_compartir';
	getXMLget("/verVideo/comentarios.phtml");
	if(codUsuario > 0) MostrarFormAnadirAgrupo(codUsuario, codVideo);
	estilos();
}

function OcultarTodosSubOpciones() {
	var capas = document.getElementsByClassName('subopciones');
	for (i=0; i<capas.length; i++) {
		capas[i].style.display = "none";
	}
	document.getElementById('marcador-seccion').className = 'seleccion_ninguna';
	document.getElementById('ln_blog').href = "javascript:insertarVideo('ponervideo');";
}

function ResetEstilosMenuSubOpciones() {
	document.getElementById("ln_enviar").className = 'mv_enviar';
	document.getElementById("ln_blog").className = 'mv_blog';
	if (document.getElementById("ln_grupos")) document.getElementById("ln_grupos").className = 'mv_grupos';
	document.getElementById("ln_denunciar").className = 'mv_denunciar';
}

function getXMLget(url) {
	if (url=="undefined") exit();

	var querystring = crearQueryString();
	var myAjax = null;

	myAjax = new Ajax.Request(
	url,
	{
		method: 'get',
		asynchronous: true,
		parameters: querystring,
		onComplete: processXML
	});

}


function crearQueryString(){
	var str;
	str="coments=1";
	str+="&codVideo="+codVideo;
	str+="&pag="+pagina;
	return str;
}
function crearQueryStringPost(padre,comentario){
	var str;
	//comentario=comentario.replace("ñ","HV_ENE"); 
	str="codPadre="+padre;
	str+="&comentario="+encodeURIComponent(comentario);
	str+="&codVideo="+codVideo;
	//str=str.replace("HV_ENE","ñ"); 
	return str;
}
function crearQueryStringEliminar(cod){
	var str;
	str="id="+cod;
	return str;
}

function paginar(num){
	pagina = num;
	getXMLget("/verVideo/comentarios.phtml");
}

function lTrim(sStr){
 while (sStr.charAt(0) == " ") 
  sStr = sStr.substr(1, sStr.length - 1);
 return sStr;
}

function rTrim(sStr){
 while (sStr.charAt(sStr.length - 1) == " ") 
  sStr = sStr.substr(0, sStr.length - 1);
 return sStr;
}

function Trim(sStr){
 return rTrim(lTrim(sStr));
} 

function avisoDenuncia(){
	alert('Gracias, pero ya has denunciado el contenido de este video');
}


var denuncia = new Array(0);

var codTipoDenuncias = new Array(0);
var nombreDenuncias = new Array(0);

var videoDenuncia;

function obtenerTipoDenuncias(){
	var url = "/verVideo/denunciar.phtml";
	var querystring = "recogerTipo=1";
	var myAjax = null;

	myAjax = new Ajax.Request(
	url,
	{
		method: 'post',
		asynchronous: true,
		parameters: querystring,
		onComplete: processXMLdenuncias
	});
}

function denunciar(video){
	if (document.getElementById("formDenunciarVideo").style.display == "") {
		OcultarTodosSubOpciones();
		ResetEstilosMenuSubOpciones();
	}
	else {
		OcultarTodosSubOpciones();
		ResetEstilosMenuSubOpciones();
		document.getElementById("formDenunciarVideo").style.display = "";
		document.getElementById('ln_denunciar').className = 'mv_denunciar selected';
		document.getElementById('marcador-seccion').className = 'seleccion_denunciar';
	}
}

function processXMLdenuncias(request) {
	var denuncias;

	try {
		denuncias = request.responseXML.getElementsByTagName("denuncias")[0];
		denuncia = denuncias.getElementsByTagName("denuncia");
	}
	catch (e) {
		setTimeout("getXMLget('/verVideo/comentarios.phtml')", 10000);
		return;
	}
	for (i = 0; i < denuncia.length; i++) {

		codTipoDenuncias[i] = denuncia[i].getElementsByTagName("codTipoDenuncia")[0].firstChild.nodeValue;

		nombreDenuncias[i] = denuncia[i].getElementsByTagName("nombreDenuncia")[0].firstChild.nodeValue;
	}
	pushDenuncias();
}
function pushDenuncias() {
	var text = "";

	text +='<form name="denunciar">';
	text +='<select name="denuncia" id="denuncia" style="width:100px;" onChange="javascript:enviarDenuncia('+videoDenuncia+')">';
	text +='<option value=0">[ Selecciona ]</option>';
	for(i=0; i<denuncia.length; i++){
		text +='<option value="'+codTipoDenuncias[i]+'">'+nombreDenuncias[i]+'</option>';
	}
	text +='</select>';
	text +='</form>';
	document.getElementById("DIV-denunciar").innerHTML = text;
}


function enviarDenuncia(video){
	var url = "/verVideo/denunciar.phtml";

	var querystring = "codVideo="+video+"&tipoDenuncia="+document.getElementById("denuncia").value;
	var myAjax = null;

	myAjax = new Ajax.Request(
	url,
	{
		method: 'post',
		asynchronous: true,
		parameters: querystring,
		onComplete: limpiarDenuncia
	});
}

function limpiarDenuncia(request){
	OcultarTodosSubOpciones();
	ResetEstilosMenuSubOpciones();
	document.getElementById("ln_denunciar").href = "javascript:avisoDenuncia();";
}

function yaVotado(registrado){
	if (registrado){
		alert('Ya has votado este video');
	}
	else{
		alert("Registrate o logueate si deseas volver a votar.");
	}
}

function copyit(theField) {
	alert(theField);
	theField.focus();
	theField.select();
	therange=theField.createTextRange();
	therange.execCommand("Copy");
}

function noActivadoVotar(){
	if(confirm("Para poder votar un video tienes que activar el usuario.\n¿Quieres activarlo ahora?")){
		location.href="/usuario/subirVideo/";
	}
}

function noActivadoComentar(){
	if(confirm("Para poder comentar un video tienes que activar el usuario.\n¿Quieres activarlo ahora?")){
		location.href="/usuario/subirVideo/";
	}
}

function processDeleteRecord(){
	getXMLget("/verVideo/comentarios.phtml");
}

function popUp(URL) {
	id = "popUpVideo";
	window.open(URL,  id , 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=620,height=440');
}

function mostrarEnlazan(){
	if(document.getElementById("lista_enlazan").style.display == "block"){
		document.getElementById("lista_enlazan").style.display = "none";
	}else{
		document.getElementById("lista_enlazan").style.display = "block";
		document.getElementById("capagrafica").style.display="none";
	}
}
// Jordi: Funciones para añadir video a grupo en visualizacion de video
function MostrarFormAnadirAgrupo(codUsuario, codVideo){
	qstr = 'codUsuario=' + codUsuario + '&codVideo=' + codVideo;  // NOTE: no '?' before querystring
	xmlhttpPost(qstr,"/usuario/mostrarFormAnadirVideoAGrupo/formGrupos.phtml",4);
}

function MostrarOcultarCapaFormAnadirVideoAGrupos(codUsuario, codVideo){
	if(document.getElementById("formAnadirVideoAGrupos").style.display == ""){
		OcultarCapaFormAnadirVideoAGrupos(codUsuario, codVideo);
	}else{
		MostrarCapaFormAnadirVideoAGrupos(codUsuario, codVideo);
	}
}

function MostrarCapaFormAnadirVideoAGrupos(codUsuario, codVideo){
	OcultarTodosSubOpciones();
	ResetEstilosMenuSubOpciones();
	document.getElementById("formAnadirVideoAGrupos").style.display = "";
	if (document.getElementById("ln_grupos")) document.getElementById('ln_grupos').className = 'mv_grupos selected';
	document.getElementById('marcador-seccion').className = 'seleccion_grupos';
	MostrarFormAnadirAgrupo(codUsuario, codVideo);
}

function OcultarCapaFormAnadirVideoAGrupos(codUsuario, codVideo){
	OcultarTodosSubOpciones();
	ResetEstilosMenuSubOpciones();
	MostrarFormAnadirAgrupo(codUsuario, codVideo);
}

function updateFormAgregarVideoAGrupo(str){
	document.getElementById("formAnadirVideoAGrupos").innerHTML = str;
}

function AgregarVideoAGrupos(codVideo, codUsuario, numGrupos){
	var checked = 0;
	var checkbox = 0;
	var qstrAux = '';
	for(i=0;i<document.getElementById("formGrupos").elements.length;i++){
		if(document.getElementById("formGrupos").elements[i].type == "checkbox"){
			if(document.getElementById("formGrupos").elements[i].checked == 1){
				if(document.getElementById("formGrupos").elements[i].disabled == 0){// Si el check esta desabilitado y seleccionado
					checked = checked + 1;
					//alert('&codGrupo_'+checkbox+'='+document.getElementById("CHECKGRUPOHIDDEN_"+checkbox).value);
					qstrAux = qstrAux + '&codGrupo_'+checkbox+'='+document.getElementById("CHECKGRUPOHIDDEN_"+checkbox).value;
				}
			}
			checkbox = checkbox + 1;
		}
	}
	if(checked > 0){
		qstr = 'codUsuario='+codUsuario+'&codVideo='+codVideo+'&numGrupos='+numGrupos+qstrAux;
		xmlhttpPost(qstr,"/usuario/mostrarFormAnadirVideoAGrupo/anadirVideos.phtml",4);
	}
	/*
	else{// Es '0'
		alert('¡Debes seleccionar al menos un Grupo al que añadir el vídeo!');	
	}
	*/
	
}
/*                            INSERTAR VIDEO EN BLOG 							*/

var capa;
function insertarVideo(id){
	capa = id;
	if(codVideo != undefined){
		if(document.getElementById(id).style.display=="none" || document.getElementById(id).innerHTML.lenght!=0){
			OcultarTodosSubOpciones();
			ResetEstilosMenuSubOpciones();
			document.getElementById(id).style.display = "block";
			document.getElementById(id).innerHTML ='';
			document.getElementById('ln_blog').className = 'mv_blog selected';
			document.getElementById('ln_blog').href = 'javascript:cerrarPonerVideo();';
			document.getElementById('marcador-seccion').className = 'seleccion_blog';
			getHTML_seleccionarBlog();		
		}else{
			document.getElementById(id).style.display = "none";
		}
	}else{
		setTimeout("insertarVideo('"+capa+"');",5000);
	}
}
function cerrarPonerVideo(){
	OcultarTodosSubOpciones();
}
function nuevoBlog(){
	var querystring = '?p=1&codVideo='+codVideo+'&nuevoBlog=1';
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';

	myAjax = new Ajax.Request(
	url,
	{
		method: 'get',
		asynchronous: true,
		parameters: querystring,
		onComplete: processHTML_seleccionarBlog
	});
}
function getHTML_seleccionarBlog(param) {
	var querystring = '?p=1&codVideo='+codVideo;
	if(param!=undefined){
		querystring += '&b='+ param;
	}
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';

	myAjax = new Ajax.Request(
	url,
	{
		method: 'get',
		asynchronous: true,
		parameters: querystring,
		onComplete: processHTML_seleccionarBlog
	});
}

function processHTML_seleccionarBlog(request){
	if(request.responseText){
		document.getElementById(capa).innerHTML = request.responseText;
	}else{
		alert('Ha ocurrido un error');
	}
}

function tipoBlogSeleccionado(valor){
	getHTML_seleccionarBlog(valor);
}

function getHTML_datosBlog(valor){
	var querystring = '?p=2&codVideo='+codVideo+'&tb='+valor;
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';

	myAjax = new Ajax.Request(
	url,
	{
		method: 'get',
		asynchronous: true,
		parameters: querystring,
		onComplete: processHTML_datosBlog
	});
}

function processHTML_datosBlog(request){
	if(request.responseText){
		document.getElementById(capa).innerHTML = request.responseText;
	}else{
		alert('Ha ocurrido un error');
	}
}

function crearCuenta(){
	var querystring = crearQueryStringCuenta();
	
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';

	myAjax = new Ajax.Request(
	url,
	{
		method: 'post',
		asynchronous: true,
		parameters: querystring,
		onComplete: processNuevaCuenta
	});
}

function eliminarCuenta(cuenta){
	var querystring = '?p=5&cuenta='+cuenta;
	
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';

	myAjax = new Ajax.Request(
	url,
	{
		method: 'post',
		asynchronous: true,
		parameters: querystring,
		onComplete: processEliminarCuenta
	});
}

function processEliminarCuenta(request){
	setTimeout("getHTML_seleccionarBlog()",1000);
}

function crearQueryStringCuenta(){
	var send_url = document.getElementById('send_url').value;
	var username = document.getElementById('usernameb').value;
	var password = document.getElementById('passwordb').value;
	var account_name = document.getElementById('account_name').value;
	var type = document.getElementById('type').value;
	return ('?p=2&cp=1&codVideo='+codVideo+'&username='+username+'&password='+password+'&account_name='+account_name+'&type='+type+'&send_url='+send_url);
}

function processNuevaCuenta(request){
	if(request.responseText){
		document.getElementById(capa).innerHTML = request.responseText;
	}else{
		alert('Ha ocurrido un error');
	}
}

function blogLogin(cuenta){
	if(cuenta!=undefined){
		getHTML_login(cuenta);
	}else{
		getHTML_seleccionarBlog();
	}
}
function getHTML_login(cuenta){
	
	var querystring = '?p=3&codVideo='+codVideo+'&cuenta='+cuenta;
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';

	myAjax = new Ajax.Request(
	url,
	{
		method: 'post',
		asynchronous: true,
		parameters: querystring,
		onComplete: processHTML_datosBlog
	});
}

function publicar(num){
	var querystring = crearQueryStringPublicar();
	if(num!=undefined){
		querystring+='&publicar='+num;
	}
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';

	myAjax = new Ajax.Request(
	url,
	{
		method: 'post',
		asynchronous: true,
		parameters: querystring,
		onComplete: processPublicar
	});
}

function crearQueryStringPublicar(){
	
	var send_url = document.getElementById('send_url').value;
	var username = document.getElementById('usernameb').value;
	var password = document.getElementById('passwordb').value;
	var account_name = document.getElementById('account_name').value;
	var type = document.getElementById('type').value;
	var categories = document.getElementById('categories').value;
	var title = document.getElementById('title').value;
	var description = document.getElementById('description').value;
	if(type == 'ot'){
		return ('?p=4&codVideo='+codVideo+'&NOMBRE='+document.getElementById('NOMBRE').value+'&MAIL='+document.getElementById('MAIL').value+'&ASUNTO='+document.getElementById('ASUNTO').value+'&COMENTARIO='+document.getElementById('COMENTARIO').value+'&TEXTOCAP='+document.getElementById('TEXTOCAP').value);
	}else{
		if(document.getElementById('mostrardescripcion').checked){
			return ('?p=4&codVideo='+codVideo+'&username='+username+'&password='+password+'&account_name='+account_name+'&type='+type+'&categories='+categories+'&title='+title+'&description='+description+'&send_url='+send_url+'&mostrardescripcion=1');
		}else{
			return ('?p=4&codVideo='+codVideo+'&username='+username+'&password='+password+'&account_name='+account_name+'&type='+type+'&categories='+categories+'&title='+title+'&description='+description+'&send_url='+send_url);
		}
	}
}

function processPublicar(request){
	if(request.responseText){
		document.getElementById(capa).innerHTML = request.responseText;
	}else{
		alert('Ha ocurrido un error');
	}
}

function comprobarErroresFormulario(){
	var querystring = crearQueryStringErroresFormulario();
	
	var myAjax = null;
	var url = '/verVideo/insertarVideo.phtml';
	
	myAjax = new Ajax.Request(
	url,
	{
		method: 'post',
		asynchronous: true,
		parameters: querystring,
		onComplete: processErroresFormulario
	});
}
 
function processErroresFormulario(request){
 	if(request.responseText){
 		eval(request.responseText);
	}else{
		document.getElementById('btanadirvideo').disabled = true;
		document.getElementById('cargandoblog').style.display = "block";
		publicar(1);
 	}
}
 
function crearQueryStringErroresFormulario(){
 	var send_url = document.getElementById('send_url').value;
	var username = document.getElementById('usernameb').value;
	var password = document.getElementById('passwordb').value;
	var account_name = document.getElementById('account_name').value;
	var type = document.getElementById('type').value;
	var categories = document.getElementById('categories').value;
	var title = document.getElementById('title').value;
	var description = document.getElementById('description').value;
	return ('?p=4&codVideo='+codVideo+'&username='+username+'&password='+password+'&account_name='+account_name+'&type='+type+'&categories='+categories+'&title='+title+'&description='+description+'&send_url='+send_url);
}

// popUp de enviar video
function popEnviar(codVideo,proc){
	if (!proc) proc='web';
	window.open("/go/?proc="+proc+"&url=/enviarVideo/index.phtml?codVideo="+codVideo,"EnviarVideo","width=780,height=780,resizable=no,scrollbars=no,status=0");
}

function deshabilitado(){
	alert('Función deshabilitada por tareas de mantenimiento.');
}

function MostrarCapaCompartir() {
	if (document.getElementById('comparte_videos').style.display == '') {
		OcultarTodosSubOpciones();
		ResetEstilosMenuSubOpciones();
	}
	else {
		OcultarTodosSubOpciones();
		ResetEstilosMenuSubOpciones();
		document.getElementById('comparte_videos').style.display = '';
		document.getElementById('ln_enviar').className = 'mv_enviar selected';
		document.getElementById('marcador-seccion').className = 'seleccion_compartir';
	}
}

function mostrarCapaEnviarMas(){
	document.getElementById('comparte_videos_despegable').style.display='';	
	document.getElementById('masEnviar').style.display='none';	
	document.getElementById('menosEnviar').style.display='';	
}

function ocultarCapaEnviarMas(){
	document.getElementById('comparte_videos_despegable').style.display='none';	
	document.getElementById('masEnviar').style.display='';	
	document.getElementById('menosEnviar').style.display='none';	
}

function updateGrafica(texto){
	document.getElementById('capagrafica').innerHTML='<img src="'+texto+'" />';
	document.getElementById('capagrafica').style.display='block';
}

function enviarATwitter(){
	popUp('/go/?url=http://twitter.com/intent/tweet?text=Mira este video+-+'+document.title+'+'+window.location);
}

function enviarAFaceBook(){
	popUp('/go/?url=http://www.facebook.com/sharer.php?u='+window.location+'%26t='+document.title);
}

