var LETRAS = "TRWAGMYFPDXBNJZSQVHLCKET"; // Tabla de letras para el N.I.F
var letrasInicialesCIF= "ABCDEFGHKLMPQSXZ"; // Tabla para el C.I.F
var mayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var digitos = "0123456789"; 

function validaNIF(nif) {
    var errores = "";
    var nif_dni   = nif; 
    var nomcamp = "NIF";
      
    if(nif_dni.length > 9) {
       errores += '\n'+nomcamp+': Maximo 9 caracteres.';
   }
			       
   if((nif_dni.charAt(nif_dni.length - 1).toUpperCase() < "A") || (nif_dni.charAt(nif.length - 1).toUpperCase() > "Z")) {
      errores += '\n'+nomcamp+': Ultimo caracter debe ser una letra.';
  }
					      
  if(isNaN(nif_dni.substr (0,nif_dni.length - 1))) {
     errores += '\n'+nomcamp+': Numero de digitos incorrecto.';
 }
						     
    dValor = nif_dni.substr (0,nif_dni.length - 1);
    iNumero = (dValor % 23);
						     
     if (LETRAS.charAt (iNumero) != nif_dni.charAt (nif_dni.length - 1).toUpperCase()) {
	errores = '\n'+nomcamp+': NIF incorrecto'; 
    }
    return errores;
}// fi_validaNIF 



function vEmail(casella) {

 var val = casella;
 var formatoMail = /^(.+)@(.+)$/ 
   
 var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
 var validChars   = "\[^\\s" + specialChars + "\]";
 var quotedUser   = "(\"[^\"]*\")" ;
 var atom         = validChars + '+';
 var word         = "(" + atom + "|" + quotedUser + ")";
       
 var formatoUsuario = new RegExp("^" + word + "(\\." + word + ")*$");
 var formatoDominio = new RegExp("^" + atom + "(\\." + atom +")*$");
	 
 var comprobar = val.match(formatoMail);
 var errormail = '';
	   
 if (casella.length > 75) errormail = 'EMAIL no puede superar los 75 caracteres.';
 if (comprobar == null)   errormail = 'EMAIL debe contener una direccion de email vlida.';
 else {
     var usuario = comprobar[1];
     var dominio = comprobar[2];

     if (usuario.match(formatoUsuario) == null) errormail = 'La direccion de EMAIL debe tener un usuario valido.';
     if (dominio.match(formatoDominio) == null) errormail = 'La direccion de EMAIL debe tener un dominio valido.';
     var atomPat = new RegExp(atom,"g");
     var domArr  = dominio.match(atomPat);
     if (domArr != null){
     if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) errormail='El dominio del EMAIL debe terminar con un minimo de 2 letras despues del punto.';
 }
}
							    
  if (errormail != '') {
       errores = errormail;
       return(errores);
  }
  else return("");
}// fi_vEmail 


function replaceBlanks(entry) {
 var errornif = '';
 var out = " "; // reemplazar espacios en blanco
 var add = ""; // por nada
 var temp = "" + entry;
 while (temp.indexOf(out)>-1) {
	pos= temp.indexOf(out);
	temp = "" + (temp.substring(0, pos) + add + 
	temp.substring((pos + out.length), temp.length));
 }
	if (temp.length<6 || temp.length>16){
 	errornif = 'El número de identificación debe tener entre 6 y 16 caracteres';
	}

  if (errornif != '') {
       errores = errornif;
       return(errores);
  }
  else return("");

} //fi_replace


function IsAlphaNum( str ) {
// Return immediately if an invalid value was passed in
if (str+"" == "undefined" || str+"" == "null" || str+"" == "") 
return false;
var isValid = true;
var num = false;

// convert to a string for performing string comparisons.
str += ""; 

// quito los espacios en blanco antes de mirar si es numero
 var out = " "; // reemplazar espacios en blanco
 var add = ""; // por nada
 var temp = "" + str;
 while (temp.indexOf(out)>-1) {
	pos= temp.indexOf(out);
	temp = "" + (temp.substring(0, pos) + add + 
	temp.substring((pos + out.length), temp.length));
 }
str = temp;

// Loop through length of string and test for any alpha numeric 
// characters
for (i = 0; i < str.length; i++)
{
// Alphanumeric must be between "0"-"9", "A"-"Z", or "a"-"z"
if (!(((str.charAt(i) >= "0") && (str.charAt(i) <= "9")) || 
((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
((str.charAt(i) >= "A") && (str.charAt(i) <= "Z"))))
{
isValid = false;
break;
} 
// hay algun numero
if ((str.charAt(i) >= "0") && (str.charAt(i) <= "9")) num = true;
} // END for 

if (!num) isValid = false;  //si no hay ningun numero en la cadena
return isValid;
} // end IsAlphaNum


function IsNum( numstr ) {
// Return immediately if an invalid value was passed in
if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "") 
return false;
var isValid = true;
var decCount = 0; // number of decimal points in the string
// convert to a string for performing string comparisons.
numstr += ""; 

// quito los espacios en blanco antes de mirar si es numero
 var out = " "; // reemplazar espacios en blanco
 var add = ""; // por nada
 var temp = "" + numstr;
 while (temp.indexOf(out)>-1) {
	pos= temp.indexOf(out);
	temp = "" + (temp.substring(0, pos) + add + 
	temp.substring((pos + out.length), temp.length));
 }
strnum = temp;

// Loop through string and test each character. If any
// character is not a number, return a false result.
// Include special cases for negative numbers (first char == '-')
// and a single decimal point (any one char in string == '.'). 
for (i = 0; i < numstr.length; i++) {
// track number of decimal points
if (numstr.charAt(i) == ".")
decCount++;
if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9") || 
(numstr.charAt(i) == "-") || (numstr.charAt(i) == "."))) {
isValid = false;
break;
} else if ((numstr.charAt(i) == "-" && i != 0) ||
(numstr.charAt(i) == "." && numstr.length == 1) ||
(numstr.charAt(i) == "." && decCount > 1)) {
isValid = false;
break;
} 

} // END for 

return isValid;
} // end IsNum


function verificarFormulari(){
    fer=true;
    if(document.mp.NOMBRE.value=="" || document.mp.NIF.value=="" || document.mp.DIRECCION.value=="" || document.mp.POBLACION.value=="" || document.mp.CP.value=="" || document.mp.PROVINCIA.value=="" || document.mp.PAIS.value=="" || document.mp.TELEFONO1.value=="" || document.mp.MAIL.value=="" || document.mp.ACTIVIDAD.value==""){
	alert("Todos los campos marcados con asterisco (*) son obligatorios.");
	fer=false;
    }else{

	if(replaceBlanks(document.mp.NIF.value)!='') {
		alert(replaceBlanks(document.mp.NIF.value));
		document.mp.NIF.focus();
	    exit;
	    fer=false;
   }

	if ((IsAlphaNum(document.mp.NIF.value)==false) && (IsNum(document.mp.NIF.value)==false)){
		alert("El número de identificación debe estar formado por números y letras o números");
		document.mp.NIF.focus();
	    exit;
	    fer=false;	
	}

	if(document.mp.DIRECCION.value.length<5){
	    alert("La direccion tiene que tener mas de 5 caracteres.");
	    document.mp.DIRECCION.focus();
	    exit;
	    fer=false;	
	}

//	if(document.mp.POBLACION.value.length<0){
//	    alert("La poblacion no puede estar vacia.");
//	    document.mp.POBLACION.focus();
//	    exit;
//	    fer=false;	
//	}

//	if(document.mp.PROVINCIA.value.substr (0,2) !=document.mp.CP.value.substr (0,2)){
//	    alert("El codigo postal no corresponde a esta provincia");
//	    document.mp.PROVINCIA.focus();
//	    exit;
//	    fer=false;	
//	}

	if(document.mp.TELEFONO1.value.length<8 || document.mp.TELEFONO1.value.length>16){
	    alert("El telefono tiene que tener entre 9 y 15 caracteres");
	    document.mp.TELEFONO1.focus();
	    exit;
	    fer=false;	
	}	
	
	if(vEmail(document.mp.MAIL.value)!=""){
	    alert(vEmail(document.mp.MAIL.value));
	    document.mp.MAIL.focus();
	    exit;
	    fer=false;	
	}

	if(document.mp.ACTIVIDAD.value.length<5){
	    alert("La actividad tiene que tener mas de 5 caracteres.");
	    document.mp.ACTIVIDAD.focus();
	    exit;
	    fer=false;	
	}
	
	if(document.mp.contrasenya_1.value!="" && document.mp.contrasenya_1.value!=document.mp.contrasenya_2.value){
	    alert("Las contrase&ntildeas; tienen que ser iguales.");
	    document.mp.contrasenya_1.focus();
//	    exit;
	    fer=false;	
	}

    }
    
    if(fer){
	document.mp.submit();	
    }


}