// Copyright © 2001 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.

// This code was modified by Alejandro Tabares <webmaster@frikilandia.com> creating the function checkNif and translating the error messages to Spanish Language.

function checkEmail (strng,campo) {
var error="";
if (strng == "") {
   error = "No introdujo una dirección de email.\n\n";
}

    var emailFilter=/^.+@.+\..{2,4}$/;
    if (!(emailFilter.test(strng))) { 
       error = "La dirección de e-mail no es válida.\n\n";
    }
    else {
//test email for illegal characters
       var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
         if (strng.match(illegalChars)) {
          error = "La dirección que introdujo contiene caracteres no permitidos.\n\n";
       }
    }
return error;    
}


// phone number - strip out delimiters and check for 10 digits

function checkPhone (strng,campo) {
var error = "";

var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
document.getElementById(campo).value = stripped;


if (stripped == "" || stripped.length == 0) {
   error = "Debe introducir un número de TELEFONO.\n\n";
}

    if (isNaN(parseInt(stripped))) {
       error = "El teléfono sólo puede contener números.";
  
    }
    if (!(stripped.length == 9)) {
	error = "Introdujo 9 dígitos?.\n\n";
    } 
return error;
}


// password - between 6-8 chars, uppercase, lowercase, and numeral

function checkPassword (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a password.\n";
}

    var illegalChars = /[\W_]/; // allow only letters and numbers
    
    if ((strng.length < 6) || (strng.length > 8)) {
       error = "The password is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
      error = "The password contains illegal characters.\n";
    } 
    else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
       error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";
    }  
return error;    
}    


// username - 4-10 chars, uc, lc, and underscore only.

function checkUsername (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a username.\n";
}


    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if ((strng.length < 4) || (strng.length > 10)) {
       error = "The username is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
    error = "The username contains illegal characters.\n";
    } 
return error;
}       


// non-empty textbox

function isEmpty(strng,campo) {
var error = "";
  if (strng.length == 0) {
     error = "Campo obligatorio.\n\n"
  }
return error;	  
}

// was textbox altered

function isDifferent(strng) {
var error = ""; 
  if (strng != "Can\'t touch this!") {
     error = "You altered the inviolate text area.\n";
  }
return error;
}

// exactly one radio button is chosen

function checkRadio(checkvalue,campo) {
var error = "";
   if (!(checkvalue)) {
       error = "Porfavor selecciones una opcion del campo " + campo +".\n\n";
    }
return error;
}

// valid selector from dropdown list

function checkDropdown(choice,campo) {
var error = "";
    if (choice == "") {
    error = "Elija una opción para <b>"+  campo +"</b>.\n\n";
    }    
return error;
}

// Validate a NIF checing length, and the last character
function checkNif(nif){

	letras=["T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E","F"];
	
	//dado un NIF te devuelve si es o no correcto
	var error = "";			//texto que se mostraría en caso de error

	dni=nif.substring(0,nif.length-1);	//del NIF nos quedamos con el DNI
	dni=parseInt(dni);					//al convertirlo a entero, le quitamos los ceros de la izquierda
	letra=nif.charAt(nif.length-1);	//la letra que nos han pasado
	letra = letra.toUpperCase();
	letraCorrecta = letras[ dni % 23];	//la letra que debería ser para ese DNI

	if (dni > 99999999){ 
		error = "El DNI tiene a lo sumo 8 cifras\n\n";
		return error;
	}
	
	var chars= /\D/;
	if(!letra.match(chars)){
		error = "El último carácter del NIF debe ser una letra\n\n";
		return error;
	} 
	
	if(letra != letraCorrecta) {
		error = "La letra introducida no se corresponde con este DNI\n\n";
		return error;
	}
return error;
}

function checkCif(texto){
        
        var pares = 0;
        var impares = 0;
        var suma;
        var ultima;
        var unumero;
        var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I");
        var xxx;
        var error="";
        
        texto = texto.replace(" ","") ;
        texto = texto.replace("-","") ;
        texto = texto.toUpperCase();
        
        var regular = new RegExp(/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g);
         if (!regular.exec(texto))  error= "El formato del CIF no es correcto";
             
         ultima = texto.substr(8,1);

         for (var cont = 1 ; cont < 7 ; cont ++){
             xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0";
             impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
             pares += parseInt(texto.substr(cont,1));
         }
         xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0";
         impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
         
         suma = (pares + impares).toString();
         unumero = parseInt(suma.substr(suma.length - 1, 1));
         unumero = (10 - unumero).toString();
         if(unumero == 10) unumero = 0;
         
         if ((ultima == unumero) || (ultima == uletra[unumero])) {}
         else error= "El CIF introducido no es correcto\n\n";			 
return error;
}

function checkCajas(campos) {
var error ="";
var conteo=0;
	for (var i in campos) { 
    este = document.getElementById(campos[i]);
	if (este.checked == true) conteo++;
	}

	if(conteo == 0) error = "Debe seleccionar al menos una opción";
return error;
}

function suma100(campos,categoria){
	var error="";
	total = 0;

	for(i=0; i < campos.length;i++) total += parseInt(document.getElementById(campos[i]).value);

	if (total != 100) error = "El total debe sumar 100";
return error;
}

function checkNumero(numero,longitud){
var error="";
	if(isNaN(numero) || numero.length == 0) error = "Debe introducir un número";
	else 
		if (numero.length > longitud) error = "El número no puede ser mayor de " + longitud +" cifras";
return error;
}


function in_array(stringToSearch, arrayToSearch) {

	for (s = 0; s <arrayToSearch.length; s++) {

		thisEntry = arrayToSearch[s].toString();
		if (thisEntry == stringToSearch) return s;

	}
return false;
}