
function registro1() {
	var f = document.formregistro;

    if ( f.nick.value == '' ) {
		alert('Tu nombre de usuario (nick) es obligatorio');
		f.nick.focus();
		return false;
	}
	
	if ( f.contrasena.value.length < 5 ) {
		alert('La contraseña tiene que ser de al menos 5 caracteres.');
		f.contrasena.focus();
		return false;
	}

	if ( f.contrasena.value != f.contrasena2.value ) {
		alert('Las contraseñas escritas no coinciden.');
		f.contrasena.focus();
		return false;
	}
    
    if ( eval("f.acFoto") ) {
		// Si existe este input radio, es que estamos modificando
		if ( f.acFoto[1].checked && f.imagen.value == '' ) {
			// Quiere cambiar la imagen y no está seleccionada
			alert('Selecciona la imagen nueva')
			f.imagen.focus()
			return false;
		}
	} 
    
    if ( f.imagen && f.imagen.value != '' ) {
		// nos han seleccionado una foto
		var extensionFichero = f.imagen.value.substring(f.imagen.value.lastIndexOf(".")+1,f.imagen.value.length).toLowerCase()
			
		if( extensionFichero != "jpg" && extensionFichero != "jpeg" && extensionFichero != "gif" && extensionFichero != "png" ) {
			alert('Las imágenes permitidas son: jpeg, jpg, gif, png')
			f.imagen.focus()
			return false;
		}

		if ( valorSeleccionado(f.derecho_foto) == false ) {
			alert("Tienes que aceptar las condiciones legales sobre tu foto.")
			f.derecho_foto.focus()
			return false;
		}

	}

	if ( f.nombre.value == '' ) {
		alert('Tu nombre es obligatorio');
		f.nombre.focus();
		return false;
	}

	if ( f.apellidos.value == '' ) {
		alert('Tus apellidos son obligatorios');
		f.apellidos.focus();
		return false;
	}

	if ( f.email.value == '' ) {
		alert('El email es obligatorio.');
		f.email.focus();
		return false;
	}

	if( !validamail(f.email.value) ) {
		alert("El e-mail parece incorrecto.");
	    f.email.focus();
		return false;
    }

	if ( f.fechanac.value == "" || f.fechanac.value == "dd/mm/aaaa" ) {
		alert("La fecha de nacimiento debe tener el formato dd/mm/aaaa.")
		f.fechanac.focus()
		return false;
	}

	if ( !es_fecha(f.fechanac.value) ) {
		alert("La fecha de nacimiento no es correcta.")
		f.fechanac.focus()
		return false;
	}
	
	if ( f.direccion && f.direccion.value == '' ) {
		alert('La dirección es obligatoria.');
		f.direccion.focus();
		return false;
	}

	if ( f.cp ) {	
		if ( f.cp.value == "" || isNaN(f.cp.value) ) {
			alert("El código postal es obligatorio y de 5 dígitos.")
			f.cp.focus()
			return false;
		} else {
			if ( f.cp.value.length < 5 || isNaN(f.cp.value) || 
		     	 f.cp.value.substring(0,2) < 1 || f.cp.value.substring(0,2) > 52 ) {
				alert("El código postal no es correcto.")
				f.cp.focus()
				return false;
			}	 
		}
	}
    /*
    if ( f.poblacion && f.poblacion.value == '' ) {
		alert('La población es obligatoria.');
		f.poblacion.focus();
		return false;
	}
*/
	/*
	if ( f.provincia.value == '' ) {
		alert('La provincia es obligatoria.');
		f.provincia.focus();
		return false;
	}	
	*/
	var sexo = valorSeleccionado(f.sexo)
	if ( sexo === false ) {
		alert("El sexo es obligatorio.")
		f.sexo[0].focus()
		return false;	
	}
	
	if ( valorSeleccionado(f.condiciones) == false ) {
		alert("Tienes que aceptar las condiciones legales.")
		f.condiciones.focus()
		return false;
	}
	return true;
}


// Comprueba la visibilidad segun la acción a realizar en la foto del usuario
function visibilidadFoto(c) {

	if ( c.value=='nc' && c.checked ) {
		document.getElementById('spFileFoto').style.display = 'none';
	} else if ( c.value=='ch' && c.checked ) {
		document.getElementById('spFileFoto').style.display = 'block';	
	} else if ( c.value=='de' && c.checked ) {
		document.getElementById('spFileFoto').style.display = 'none';	
	}
}

// nos da el value del radio seleccionado o false si no hay ninguno seleccionado
function valorSeleccionado(ar_valores) {

	if ( ar_valores.length ) {
	
		for(var i=0; i < ar_valores.length; i++) {
			if ( ar_valores[i].checked ) {
				return ar_valores[i].value;
			}
		}

	// Si sólo hay un elemento
	} else {
		if ( ar_valores.checked ) {
			return ar_valores.value;
		}
	}
	
	return false;
}

/**
*	Chequea si la fecha es válida segun el formato dd/mm/yyyy
*
*	@param		string		indate		Fecha a comprobar
*	@param		string		indate		año mínimo correcto (por defecto 1900)
*
*	@return		boolean					True  -> fecha correcta
*										False -> fecha incorrecta
*/
function es_fecha(indate,anomin) {
	
	if ( indate.length != 10 ) return false
	var anom = anomin || 1900;
	
    var sdate = indate.split("/")
    var chkDate = new Date(Math.abs(sdate[2]),(Math.abs(sdate[1])-1),Math.abs(sdate[0]))
    var cmpDate = (chkDate.getDate())+"/"+(chkDate.getMonth()+1)+"/"+(chkDate.getFullYear())
    var indate2 = (Math.abs(sdate[0]))+"/"+(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[2]))
    if (Math.abs(sdate[2]) < anom)  return false
    if (indate2 != cmpDate || cmpDate == "NaN/NaN/NaN") return false
    else return true;
}

/**
*  Válida la sintaxis del email
*
*  Comprobaciones :
*    - Mínimo de 5 caracteres
*    - Caracteres no permitidos : ;:[](){}=+<>\/&*¿?¡!%$#|`´', ñçàèìòùáéíóúâêîôûäëïöüÑÇÀÈÌÒÙÁÉÍÓÚÂÊÎÔÛÄËÏÖÜ"
*    - Que la @ tenga algún caracter delante y alguno detrás
*    - Que exista '.' a partir del cuarto carácter (x@x.x)
*    - Que no acabe en '.'
*    - Que el punto esté detrás de la @
*/
function validamail(email){

	// Mínimo de 5 caracteres
	if (email.length < 5)
		return false
		
	// Cadena de caracteres no permitidos
	var iChars = ";:[](){}=+<>\/&*¿?¡!%$#|`´', ñçàèìòùáéíóúâêîôûäëïöüÑÇÀÈÌÒÙÁÉÍÓÚÂÊÎÔÛÄËÏÖÜ\"";	
	
	// Primero comprobamos que en el email no haya algún 
	// caracter no permitido
	var eLength = email.length;	
	for (var i=0; i < eLength; i++)	{		
		if (iChars.indexOf(email.charAt(i)) != -1)
			return false
	}	
	
	// Comprobamos que la @ tenga algún caracter delante y alguno detrás
	var atIndex = email.lastIndexOf("@");	
	if(atIndex < 1 || (atIndex == eLength - 1))
		return false

	// Comprobamos que exista '.' a partir del cuarto carácter, pero
	// que no acabé en '.'
	var pIndex = email.lastIndexOf(".");	
	if(pIndex < 3 || (pIndex == eLength - 1))	
		return false;	

	// Por último, comprobamos que el punto esté detrás de la @
	if(atIndex > pIndex)	
		return false	

	return true
}

