var ratonElementoX = 0;
var ratonElementoY = 0;

function abrirEnlaceNueva(url) {
	window.open(url);

	return false;
}

function abrirEnlace(url) {
	window.location = url;

	return false;
}

function esExplorer() {
	if (navigator.appName == "Microsoft Internet Explorer") 
		return true;
	else
		return false;
}

// Añade eventos a los elementos de la página
function listen(event, elem, func) {
    if (elem.addEventListener) { // W3C DOM
        elem.addEventListener(event,func,false);
    } else if (elem.attachEvent) { // IE DOM
         var r = elem.attachEvent("on"+event, func);
	 return r;
    } else throw 'No es posible añadir evento';
}


function validaFormularioRegistro(freg) {
	expEmail = /^[\w-\.]+@\w[\w-\.]+\.[\w]{2,4}$/i;
	expUsu = /^[\wáéíóú]{4,16}$/i;
	expPass = /^[\w]{4,16}$/i;
	valido = true;
	error = 'ERRORES:<br />';
	
	if(!expUsu.test(freg.usuario.value)) {
		valido = false;
		error += 'El usuario debe tener entre 4 y 16 caracteres alfanuméricos (letras, números o _ )<br />';
	}
	if(!expPass.test(freg.password.value)) {
		valido = false;
		error += 'La contraseña debe tener entre 4 y 16 caracteres alfanuméricos (letras, números o _ )<br />';
	}
	if(!expEmail.test(freg.email.value)) {
		valido = false;
		error += 'La dirección de E-mail no tiene un formato correcto<br />';
	}
	if(freg.password.value != freg.password2.value) {
		valido = false;
		error += 'Las contraseñas no coinciden<br />';
	}

	if(!valido) {
		document.getElementById('m_error_reg').innerHTML = error;
		alert('Los valores de algunos campos no son correctos');
	}

	return valido;
}

function validaFormConcierto(fcon) {
	expFecha = /^\d{2}\/\d{2}\/\d{4}$/i;
	valido = true;
	error = 'ERRORES:<br />';
	
	if(fcon.lugar.value == '') {
		valido = false;
		error += 'No ha introducido el lugar del concierto<br />';
	}
	if(!expFecha.test(fcon.fecha.value)) {
		valido = false;
		error += 'No ha introducido la fecha del concierto o no tiene un formato válido (dd/mm/aaaa)<br />';
	}
	if(fcon.desc.value == '') {
		valido = false;
		error += 'No ha introducido una descripción para el concierto<br />';
	}

	if(!valido) {
		document.getElementById('m_error_con').innerHTML = error;
		alert('Los valores de algunos campos no son correctos');
	}

	return valido;
}

function validaFormFoto(ffoto) {
	if(ffoto.album.value == '' || ffoto.archivo.value == '') {
		alert('Faltan algunos campos obligatorios por rellenar.');
		return false
	}

	return true;
}

function validaFormBorraFoto(ffoto) {
	if(ffoto.album.value == '') {
		alert('Debe seleccionar un álbum primero.');
		return false;
	}

	return true;
}

function creaVentanaModal(titulo, divCont) {
	ventana =  document.createElement('div');
	ventana.id = 'ventanaModal';
	
	txtCabecera = document.createTextNode(titulo);
	cabecera = document.createElement('div');
	cabecera.id = 'cabeceraVModal';
	cabecera.appendChild(txtCabecera);
	cabecera.onmousedown = iniciarMovimiento;
	cabecera.onmouseup = pararMovimiento;

	ventana.appendChild(cabecera);
	ventana.appendChild(divCont);
	divCont.style.paddingBottom = '8px';

	tapar = document.createElement('div');
	tapar.id = "tapar_pagina";

	document.body.appendChild(tapar);
	document.body.appendChild(ventana);

	ventana.style.visibility = 'hidden';
	setTimeout("centrarVentanaModal()", 50);
}

function centrarVentanaModal() {
	ventana = document.getElementById('ventanaModal');

	izq = ((document.documentElement.clientWidth/2) - (ventana.clientWidth/2));
	arr = ((document.documentElement.clientHeight/2) - (ventana.clientHeight/2));
	ventana.style.left = izq < 0? "0px":izq + "px";
	ventana.style.top = arr < 0? "0px":arr + "px";

	ventana.style.visibility = 'visible';
}

function cierraVentanaModal() {
	ventana = document.getElementById('ventanaModal');
	tapar =  document.getElementById('tapar_pagina');

	document.body.removeChild(tapar);
	document.body.removeChild(ventana);

	ventana = null;
}

function iniciarMovimiento(e) {
	if (esExplorer()) {
		ratonElementoX = event.offsetX;
		ratonElementoY = event.offsetY;
	} else { 
		ratonElementoX = e.layerX;
		ratonElementoY = e.layerY;
	}

	this.onmousemove = moverElemento;
}

function pararMovimiento(e) {
	this.onmousemove = null;
}

function moverElemento(e) {
	if (esExplorer()) {
		this.parentNode.style.left = String(event.clientX + document.body.scrollLeft - ratonElementoX) + 'px';
		this.parentNode.style.top = String(event.clientY + document.body.scrollLeft - ratonElementoY) + 'px';
	} else { 
		this.parentNode.style.left = String(e.pageX - ratonElementoX) + 'px';
		this.parentNode.style.top = String(e.pageY - ratonElementoY) + 'px';
	}
}

function muestraFormAlbum(valor) {
	if (valor !== 'nuevo' || document.getElementById('ventanaModal'))
		return

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	} 

	var contenido = document.createElement('div');
	contenido.id = 'contenido_form_album';

	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 1) {
			contenido.innerHTML = '<p>Espere un momento por favor...</p>';
		} else if(xmlHttp.readyState == 4) {
			contenido.innerHTML = xmlHttp.responseText;
  		}
	   }

	xmlHttp.open("GET",'inc/aux/crear_album.php',true);
	xmlHttp.send(null);

	creaVentanaModal("Crear Nuevo Álbum", contenido);
}

function enviaFormAlbum(formu) {
	nombre = formu.nombre.value;
	desc = formu.desc.value;

	if(nombre == '' || desc == '') {
		alert('No has rellenado los campos obligatorios!');
		return false;
	}

	var contenido = document.getElementById('contenido_form_album');

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	} 
	
	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 1) {
			contenido.innerHTML = '<p>Espere un momento por favor...</p>';
		} else if(xmlHttp.readyState == 4) {
			contenido.innerHTML = xmlHttp.responseText;
  		}
	   }

	xmlHttp.open("POST",'inc/aux/crear_album.php',true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	xmlHttp.send('nombre='+nombre+'&desc='+encodeURIComponent(desc));

	return false;
}

function cierraFormAlbum() {
	cierraVentanaModal();

	formFoto = document.getElementById('form_nueva_foto');
	formFoto.album.selectedIndex = 0;

	return false;
}

function anyadeAlbumSelect(id, nombre) {
	selectAlbum = document.getElementById('form_nueva_foto').album;
	selectAlbum2 = document.getElementById('form_borrar_foto').album;

	var nuevo = document.createElement('option');
	nuevo.value = String(id);
	var nuevo2 = document.createElement('option');
	nuevo2.value = String(id);

	nombreAlbum = document.createTextNode(nombre);
	nombreAlbum2 = document.createTextNode(nombre);

	nuevo.appendChild(nombreAlbum);
	nuevo2.appendChild(nombreAlbum2);
	selectAlbum.appendChild(nuevo);
	selectAlbum2.appendChild(nuevo2);
}

function getDescripcionAlbum(album, formu) {
	if (album == "" ) {
		formu.desc.value = '';
		document.getElementById('info_desc').innerHTML = '';
		return;
	}

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	} 

	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 1) {
			formu.desc.value = '';
			document.getElementById('info_desc').innerHTML = "Cargando descripción...";
		} else if(xmlHttp.readyState == 4) {
			formu.desc.value = xmlHttp.responseText;
			document.getElementById('info_desc').innerHTML = "Puede modificar la descripción.";
  		}
	   }

	xmlHttp.open("POST",'inc/aux/funciones_php_ajax.php',true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	xmlHttp.send('funcion=descAlbum&album=' + album);
}

function modificaDescAlbum(album, desc, formu) {
	if (album == "" ) {
		formu.desc.value = '';
		document.getElementById('info_desc').innerHTML = 'No has seleccionado un álbum!';
		return;
	}

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	} 

	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 1) {
			document.getElementById('info_desc').innerHTML = "Modificando descripción...";
		} else if(xmlHttp.readyState == 4) {
			document.getElementById('info_desc').innerHTML = xmlHttp.responseText;
  		}
	   }

	xmlHttp.open("POST",'inc/aux/funciones_php_ajax.php',true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	xmlHttp.send('funcion=modAlbum&album=' + album + '&desc=' + encodeURIComponent(desc));
}

function borraAlbum(album) {
	if (album == "" ) {
		alert('Debe seleccionar un álbum primero.');
		return false;
	} else if (!confirm("¡¡Atención!!\nEsta accion borrará tanto el álbum como todas sus fotos, ¿está seguro?")) {
		return false;
	}

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	} 

	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 4) {
			alert(xmlHttp.responseText);
			document.getElementById('form_borrar_foto').submit();
  		}
	   }

	xmlHttp.open("POST",'inc/aux/funciones_php_ajax.php',true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	xmlHttp.send('funcion=borraAlbum&album=' + album);

	return false;
}

function enviaComentario(usuario, comentario, noticia, pass, idComent) {
	if (comentario == "" ) {
		alert('No puede enviar un comentario vacío.');
		return false;
	}

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	} 

	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 1) {
			document.getElementById('div_comentarios').innerHTML = '<p>Espere un momento por favor...</p>';
		} else if(xmlHttp.readyState == 4) {
			document.getElementById('div_comentarios').innerHTML = xmlHttp.responseText;
  		}
	   }

	xmlHttp.open("POST",'inc/aux/muestra_comentarios.php?id=' + noticia + '&accion=anyadir',true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	xmlHttp.send('comentario=' + encodeURIComponent(comentario) + '&usuario=' + usuario + '&password=' +
		     pass + '&idComent=' + idComent);
}

function modificarComentario(id) {
	if (id == "" ) {
		alert('Comentario no válido');
		return false;
	}

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	} 

	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 4) {
			document.getElementById('area_comentario').value = xmlHttp.responseText;
  		}
	   }

	xmlHttp.open("POST",'inc/aux/funciones_php_ajax.php#escribir_comentario',true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	xmlHttp.send('funcion=getComentario&id=' + id);

	document.getElementById('form_comentario').env_coment.innerHTML = 'Modificar';
	document.getElementById('form_comentario').bt_cancel.style.display = 'inline';
	document.getElementById('form_comentario').id_comentario.value = id;

	return false;
}

function cancelaModComent() {
	document.getElementById('form_comentario').env_coment.innerHTML = 'Nuevo';
	document.getElementById('form_comentario').bt_cancel.style.display = 'none';
	document.getElementById('form_comentario').id_comentario.value = '';
	document.getElementById('area_comentario').value = '';
}

function eliminarComentario(idComent, idNoticia) {
	if(!confirm('¿Está seguro de eliminar este comentario?')) {
		return false;
	}

	if (idComent == "" ) {
		alert('Comentario no válido');
		return false;
	}

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
  		alert ("¡Tu navegador no soporta AJAX!. Actualizaló.");
  		return;
  	}

	xmlHttp.onreadystatechange=function()
	   {
		if(xmlHttp.readyState == 1) {
			document.getElementById('div_comentarios').innerHTML = '<p>Espere un momento por favor...</p>';
		} else if(xmlHttp.readyState == 4) {
			document.getElementById('div_comentarios').innerHTML = xmlHttp.responseText;
  		}
	   }

	xmlHttp.open("POST",'inc/aux/muestra_comentarios.php?id=' + idNoticia + '&accion=borrar',true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	xmlHttp.send('idComent=' + idComent);
}

