// Función para el funcionamiento de las pestañas
function muestraCapa(capaVisible,capaInv1,capaInv2){
	var cV = document.getElementById(capaVisible);
	var cI1 = document.getElementById(capaInv1);
	var cI2 = document.getElementById(capaInv2);
	var acV = document.getElementById('a'+capaVisible);
	var acI1 = document.getElementById('a'+capaInv1);
	var acI2 = document.getElementById('a'+capaInv2);
	acV.className = "activa";
	acI1.className = "";
	acI2.className = "";
	cI1.style.display = "none";
	cI2.style.display = "none";
	cV.style.display = "block";
}


//Función que desplega las listas
function visible(identificador){
		var nombre_btn = "btn_" + identificador;
		var objeto 	= document.getElementById(identificador);
		var boton	= document.getElementById(nombre_btn);
		if (objeto.style.display=="block"){
			objeto.style.display = "none";
			boton.src = "imagenes/botones/btn_abrir.gif";
		}
		else{
			objeto.style.display = "block";
			boton.src = "imagenes/botones/btn_cerrar.gif";
		}
}

// Elimina todas las opciones del select
function clearSelect(idSelect){
	var elSel = document.getElementById(idSelect);
    var i;
	for (i = elSel.length - 1; i>=1; i--) {
		elSel.remove(i);
	}	    
}

// comprueba los datos del formulario
function compruebaPromotora(){
	var msj = "";
	if (document.getElementById('promotora_nombre').value.length == 0) msj = '- Falta el nombre\n';

	if (msj.length == 0){
		return true;
	}else{
		alert('Error en los siguientes datos:\n'+msj);
		return false;
	}
}

// comprueba los datos del formulario
function compruebaPromocion(){
	var msj = "";
	
	if (document.getElementById('promocion_pais').value == 0) msj = msj + '- Falta el país\n';
	if (document.getElementById('promocion_provincia').value == 0) msj = msj + '- Falta la provincia\n';
	if (document.getElementById('promocion_nombre').value.length == 0) msj = msj + '- Falta el nombre\n';
	if (document.getElementById('promocion_descripcion').value.length == 0) msj = msj + '- Falta la descripción\n';
	if (document.getElementById('promocion_entrega').value.length == 0) msj = msj + '- Falta la fecha de entrega\n';
	if ((document.getElementById('promocion_precio_min').value.length >0)&&(document.getElementById('promocion_precio_min').value > 0)){
		if (isNaN(document.getElementById('promocion_precio_min').value)) {
			msj = msj + '- Precio mínimo incorrecto\n';
		}
		else{
			if (parseFloat(document.getElementById('promocion_precio_min').value)<9999) msj = msj + '- Precio mínimo incorrecto\n';
			if (parseFloat(document.getElementById('promocion_precio_min').value)>9999999) msj = msj + '- Precio mínimo incorrecto\n';
		}
	}
	if ((document.getElementById('promocion_precio_max').value.length >0)&&(document.getElementById('promocion_precio_max').value > 0)){
		if (isNaN(document.getElementById('promocion_precio_max').value)){
			msj = msj + '- Precio máximo incorrecto\n';
		}
		else{
			if (parseFloat(document.getElementById('promocion_precio_max').value)<9999) msj = msj + '- Precio máximo incorrecto\n';
			if (parseFloat(document.getElementById('promocion_precio_max').value)>9999999) msj = msj + '- Precio máximo incorrecto\n';
		}
	}
	
	// y pasa el valor del select del grupo al campo input hidden
	if ((parseInt(document.getElementById('select_promocion_grupo').value) != 0)
	  &&(parseInt(document.getElementById('select_promocion_grupo').value) != 1)){
		document.getElementById('promocion_grupo').value = document.getElementById('select_promocion_grupo').value
	}
	
	if (msj.length == 0){
		return true;
	}else{
		alert('Error en los siguientes datos:\n'+msj);
		return false;
	}
}

// comprueba los datos del formulario
function compruebaVivienda(){
	var msj = '';
	
	if (document.getElementById('vivienda_descripcion').value.length == 0) msj = msj + '- Falta la descripción\n';
	if (document.getElementById('vivienda_tipo').value == '--') msj = msj + '- Falta el tipo\n';
	if (document.getElementById('vivienda_precio').value.length >0){
		if (isNaN(document.getElementById('vivienda_precio').value)) {
			msj = msj + '- Precio incorrecto\n';
		}
		else{
			if (parseFloat(document.getElementById('vivienda_precio').value)<9999) msj = msj + '- Precio incorrecto\n';
			if (parseFloat(document.getElementById('vivienda_precio').value)>9999999) msj = msj + '- Precio incorrecto\n';
		}
	}
	if (isNaN(document.getElementById('vivienda_habitaciones').value)) msj = msj + '- Número de habitaciones incorrecto\n';
	if (isNaN(document.getElementById('vivienda_banos').value))  msj = msj + '- Número de baños incorrecto\n';
	if (isNaN(document.getElementById('vivienda_m2').value)) msj = msj + '- Número de m2 incorrecto\n';
	if (isNaN(document.getElementById('vivienda_terraza_m2').value)) msj = msj + '- Número de m2 de la terraza incorrecto\n';
	if (msj.length == 0){
		return true;
	}else{
		alert('Error en los siguientes datos:\n'+msj);
		return false;
	}	
}

/*
 * Galería imágenes
 */	
function muestraImagen(imagen,ruta,ancho){
	document[imagen].src = ruta;
	document[imagen].width = ancho;
}

function compruebaNoticia(){
	var msj = "";
	
	if (document.getElementById('noticia_titulo').value == 0) msj = msj + '- Falta el título\n';
	if (document.getElementById('noticia_fecha_creacion').value.length == 0) msj = msj + '- Falta la fecha de creación\n';
	if (document.getElementById('noticia_fecha_caducidad').value.length == 0) msj = msj + '- Falta la fecha de caducidad\n';
	if (document.getElementById('noticia_descripcion').value == 0) msj = msj + '- Falta la descripción\n';
	if (document.getElementById('noticia_contenido').value.length == 0) msj = msj + '- Falta el contenido\n';
	if (document.getElementById('noticia_fecha_creacion').value.length > 0){	
		if (isDate(document.getElementById('noticia_fecha_creacion').value) == false) msj = msj + '- La fecha de creación no es válida\n';
	}
	if (document.getElementById('noticia_fecha_caducidad').value.length > 0){	
		if (isDate(document.getElementById('noticia_fecha_caducidad').value) == false) msj = msj + '- La fecha de caducidad no es válida\n';
	}
	if (msj.length == 0){
		return true;
	}else{
		alert('Error en los siguientes datos:\n'+msj);
		return false;
	}
}

function compruebaSuscripcion(){
	var msj = "";	
	if (document.getElementById('suscripcion_nombre').value.length == 0) msj = msj + '- Falta el nombre\n';
	if (document.getElementById('suscripcion_apellidos').value.length == 0) msj = msj + '- Faltan los apellidos\n';
	if (document.getElementById('suscripcion_email').value.length == 0) msj = msj + '- Falta el e-mail\n';
	if (document.getElementById('suscripcion_email').value.length > 0) {
		if (emailCheck(document.getElementById('suscripcion_email').value.length.value) == false) mensaje = mensaje + '\n El e-mail no es correcto';
	}	
	if (msj.length == 0){
		return true;
	}else{
		alert('Error en los siguientes datos:\n'+msj);
		return false;
	}
}

function emailCheck (emailStr) {
	/* Verificar si el email tiene el formato user@dominio. */
	var emailPat=/^(.+)@(.+)$/

	/* Verificar la existencia de caracteres. ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

	/* Verifica los caracteres que son válidos en una dirección de email */
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"

	/* Verifica si la dirección de email está representada con una dirección IP Válida */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

	/* Verificar caracteres inválidos */
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// Si el user "user" es valido 
	if (user.match(userPat)==null) {
		// Si no
		return false
	}

	/* Si la dirección IP es válida */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				return false
			}
		}
		return true
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		return false
	}

	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
		return false
	}

	if (len<2) {
		return false
	}

	// La dirección de email ingresada es Válida
	return true;
}

function obriFinestra(ruta){
	var direccio = document.getElementById(ruta).src;
	imatge = document.createElement('img');
	imatge.setAttribute("src",direccio);
	var finestra = window.open(direccio,'',"width="+imatge.width+",height="+imatge.height+",scrollbars=NO");
}

function email() {
	// Completamos el nombre de usuario y el dominio del email
	usuario = "info";
	dominio = "obradirecta.com";
	
	// Imprimimos el email uniendo las cadenas
	document.write("<a class=mail href=\"mailto:" + usuario + "@" + dominio + "\">" + usuario + "@" + dominio + "</a>")
}