var defaultEmptyOK = false
var checkNiceness = true;
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ"
var whitespace = " \t\n\r";
var phoneChars = "()-+ ";
var mMessage = "Error: no se puede dejar este campo vacío"
var pPrompt = "Error: ";
var pAlphanumeric = "Introduzca un texto que contenga letras y/o números";
var pAlphabetic   = "Introduzca un texto que contenga sólo letras";
var pInteger = "Introduzca un número entero";
var pNumber = "Introduzca un número";
var pPhoneNumber = "Introduzca un número de teléfono";
var pTelefono = "El número de teléfono fijo ha de tener 9 dígitos y empezar por 9";
var pTelefono2 = "El número de teléfono móvil ha de tener 9 dígitos y empezar por 6";
var pDirIP = "La dirección IP introducida no es válida";
var pEmail = "El formato del correo electrónico es: usuario(.algo)@subdominio.dominio";
var pName = "Introduzca un texto que contenga sólo letras, números o espacios";
var pNice = "No puede utilizar comillas aqui";
var pTexto = "Ha de introducirse un texto";
var pLargo = "El campo ha de tener un mínimo de 4 caracteres";
var pCaptcha6 = "El campo ha de tener 6 caracteres";
var pFormatoFecha = "La fecha ha de tener el formato dd/mm/aaaa";
var pFecha = "La fecha introducida no es correcta";
var pFechaNacAnt = "La fecha introducida debe ser anterior a la actual";
var pCodigoPostal = "Error: el código postal ha de tener 5 dígitos";
var pURL = "Error: la dirección introducida no es válida, ha de comenzar por http(s)://";
var pFormatoNIF = "Error: el NIF ha de ser el formato 12345678X";
var pLetraNIF = "Error: la letra introducida no se corresponde con el número";
var pFormatoCIF = "Error: el CIF ha de tener el formato B12345678";

function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this;
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0));
}

function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}


function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    // Buscar por el string, si el caracter no esta en "bag", 
    // agregarlo a returnString
    
    for (i = 0; i < s.length; i++)
    {   var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}


function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}


function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c)) return false;
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}


function isNumber (s)
{   var i;
    var dotAppeared;
    dotAppeared = false;
    if (isEmpty(s)) 
       if (isNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isNumber.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c)) return false;
        } else { 
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}

function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}


function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

function isPhoneNumber (s)
{   var modString;
    if (isEmpty(s)) 
       if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isPhoneNumber.arguments[1] == true);
    modString = stripCharsInBag( s, phoneChars );
    return (isInteger(modString))
}

function isEmail (s)
{
    if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;
    var i = 1;
    var sLength = s.length;
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isNice(s)
{
        var i = 1;
        var sLength = s.length;
        var b = 1;
        while(i<sLength) {
                if( (s.charAt(i) == "\"") || (s.charAt(i) == "'" ) ) b = 0;
                i++;
        }
        return b;
}

function statBar (s)
{   window.status = s;
}

function warnEmpty (theField, nameField)
{   theField.focus();
    if (nameField == "") {
    	alert("Error: el campo "+theField.name+" no puede estar vacío");
    } else {
    	alert("Error: el campo "+nameField+" no puede estar vacío");
    }
    return false;
}

function warnInvalid (theField, s)
{   
    if( (theField.name != "fecha_nacimiento") && (theField.name != "fecha_nac") )
    {
    	theField.focus();
    	theField.select();
    }
    alert(s);
    //statBar(pPrompt + s);
    return false;
}


function checkField (theField, nameField, theFunction, emptyOK, s)
{   
    var msg;
    if (checkField.arguments.length < 4) emptyOK = defaultEmptyOK;
    if (checkField.arguments.length == 5) {
        msg = s;
    } else {
        if( theFunction == isAlphabetic ) msg = pAlphabetic;
        if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
        if( theFunction == isInteger ) msg = pInteger;
        if( theFunction == isNumber ) msg = pNumber;
        if( theFunction == isEmail ) msg = pEmail;
        if( theFunction == isPhoneNumber ) msg = pPhoneNumber;
        if( theFunction == isTelefono ) msg = pTelefono;
        if( theFunction == isTelefono2 ) msg = pTelefono2;
        if( theFunction == isDirIP ) msg = pDirIP;
        if( theFunction == isTexto ) msg = pTexto;
        if( theFunction == isName ) msg = pName;
        if( theFunction == isLargo ) msg = pLargo;
        if( theFunction == isCaptcha6 ) msg = pCaptcha6;
        if( theFunction == isFormatoFecha ) msg = pFormatoFecha;
        if( theFunction == esFecha ) msg = pFecha;
        if( theFunction == esFechaNacAnt ) msg = pFechaNacAnt;
        if( theFunction == esCodigoPostal ) msg = pCodigoPostal;
        if( theFunction == esURL ) msg = pURL;
        if( theFunction == esFormatoNIF ) msg = pFormatoNIF;
        if( theFunction == esLetraNIF ) msg = pLetraNIF;
        if( theFunction == esFormatoCIF ) msg = pFormatoCIF;
    }
    
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;

    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField, nameField);

    if ( checkNiceness && !isNice(theField.value))
        return warnInvalid(theField, pNice);

    if (theFunction(theField.value) == true) 
        return true;
    else
        return warnInvalid(theField,msg);

}

//Añadida el 22/05/2002 para la comprobación de la clave introducida
function validar_clave (campo_orig,campo_rep)
{   
	if (campo_orig.value == campo_rep.value)
		return true;
	else
	{
		alert("Los campos clave y repetición de clave no coinciden");
		campo_rep.focus();
    	campo_rep.select();
		return false;
	}
}

//Añadida el 28/05/2002 para la comprobación del teléfono introducido (sólo fijos)
function isTelefono (s)
{   
	if (isEmpty(s)) 
       if (isTelefono.arguments.length == 1) return defaultEmptyOK;
       else return (isTelefono.arguments[1] == true);
	
    if (s.length != 9)
    	return false;
    else
    {
  	    var c = s.charAt(0);
        if( c != 9 )
		    return false;
        else
        	return (isInteger(s))
    }
}

//Añadida el 28/05/2002 para la comprobación del teléfono introducido (sólo móviles 28/11/2002)
function isTelefono2 (s)
{   
	if (isEmpty(s)) 
       if (isTelefono2.arguments.length == 1) return defaultEmptyOK;
       else return (isTelefono2.arguments[1] == true);
	
    if (s.length != 9)
    	return false;
    else
    {
  	    var c = s.charAt(0);
        if( c == 6)
		    return (isInteger(s));
        else
        	return false;
    }
}

//Añadida el 06/06/2002 para la comprobación de la dirección IP
function isDirIP (s)
{
	//alert("Ha entrado en la función isDirIP");
	//alert("La dirección es: "+s);
	
	if (isEmpty(s)) 
       if (isDirIP.arguments.length == 1) return defaultEmptyOK;
       else return (isDirIP.arguments[1] == true);
	
	// modifico el patrón para que coja guiones en vez de puntos
	// var ipDomainPat=/^(([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}))$/;
	var ipDomainPat=/^(([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}))$/;

	var IPArray=s.match(ipDomainPat);
	
	//alert("El octeto actual: "+IPArray);
	
	if (IPArray!=null)
	{
		//alert("Cumple el patrón");
		for (var i=2;i<=5;i++)
		{
			//alert("El octeto actual: "+IPArray[i]);
			if (IPArray[i]>255)
			{
			//alert("IP de destino no válida");
			return false;
			}
		}
	//alert("IP de destino válida");
	return true;
	}
}

//Añadida el 11/06 para que admita textos con caracteres "()-+ "
//Modificada el 14/06 para que admita todo
function isTexto (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return true;
}

//Añadida el 26/06 para comprobar que se introducen palabras de más de num caracteres
function isLargo (s)
{
    if (s.length<4)
    	return false;
    else
    	return true;
}

function isCaptcha6 (s)
{
    if (s.length!=6)
    	return false;
    else
    	return true;
}

//Añadidas el 16/10/2002 para la comprobación de fechas

function isFormatoFecha (s)
{
	if (isEmpty(s)) 
       if (isFormatoFecha.arguments.length == 1) return defaultEmptyOK;
       else return (isFormatoFecha.arguments[1] == true);
	
	var i;
	
	if (s.length!=10)
		return false;
	else
	    for (i = 0; i < s.length; i++)
	    {   
	        var c = s.charAt(i);
	        if ((i==2)||(i==5))
	        {
	        	if (c!="/")
	        		return false;
	        }
	        else
	        {
	        	if (!isDigit(c))
	        		return false;
	        }
	    }
	return true;
}

//*********************************************************************************
// ESTAS TRES FUNCIONES SE UTILIZA PARA DIVIDIR UN CADENA DE CARACTERES
// EN LOS CAMPOS QUE LA COMPONEN (UTILIZANDO sep COMO SEPARADOR)
// POR MOTIVOS QUE NO VIENEN AL CASO, EL PRIMER PARÁMETRO ES EL DE ÍNDICE 2
//*********************************************************************************
function addItem(newItem) 
{ 
	this.length += 1; 
	this[(this.length-1)] = newItem; 
}
function ParametrosCrear(firstItem) { 
	this.length = 2; 
	this.addItem = addItem; 
	this[(this.length-1)] = firstItem; 
}
function ParametrosTratar(Parametros,s,sep) {
	var pos=-1;
	s=s.substring(pos+1,s.length);
	do {
		pos=s.indexOf(sep);
                
		if (pos<=0) {
			if (s.length>0) Parametros.addItem(s);
			break;
		}
		else 	
			Parametros.addItem (s.substring(0,pos));
		s=s.substring(pos+1,s.length);
	} while (0==0);
}

//***************************************************************************
// UTILIZA LAS FUNCIONES ANTERIORES PARA OBTENER LOS TRES CAMPOS DE UNA FECHA
// A PARTIR DE ELLOS, PUEDE COMPROBAR SI ES UNA FECHA VÁLIDA
//***************************************************************************
function esFecha (fecha) {
	
	if (isEmpty(fecha)) 
       if (esFecha.arguments.length == 1) return defaultEmptyOK;
       else return (esFecha.arguments[1] == true);
	
	var Parametros;
	var dia,mes,ano;
			
	Parametros=new ParametrosCrear("");

	// MEJORAS: SE PUEDE INTENTAR VER SI LA FECHA TIENE "/", SI LAS TIENES SE USA COMO
	// SEPARADOR, SI NO LAS TIENE, SE PUEDE INTENTAR BUSCAR "-" Y ASÍ CON OTROS SEPARADORES
	ParametrosTratar(Parametros,fecha,"/");

	// LA FECHA DEBE TENER TRES PARÁMETROS
	if (Parametros.length<3) return (false);
	
	// COMPROBAMOS CADA PARÁMETRO
	dia=Parametros[2];
	mes=Parametros[3];
	ano=Parametros[4];
	if (ano<1900)
		return false;
   
    //alert("El día: "+dia+", mes: "+mes+" y el año: "+ano);

	if (!(DiaCorrecto(dia, mes, ano)))
   	return(false);
	
	return(true);
}
function CuantosDias(mes,ano){
   var n_dias;
   mes = parseInt(mes,10);
   switch (mes) {
      case 1:      
      case 3:       
      case 5:
      case 7:      
      case 8:      
      case 10:
      case 12:
         n_dias = 31;      break;
      case 4:      
      case 6:      
      case 9:
      case 11:
         n_dias = 30;      break;
      case 2:         
         n_dias=bisiesto(mes, ano);       break;
   }
   return n_dias;   

}


function DiaCorrecto(dia, mes, ano){
   var salida;
   salida = true;
   var n_dias;
   
   n_dias = CuantosDias(mes, ano);
   if (dia>0 && dia<=n_dias)     
      salida = true;
   else 
      salida = false;
   return salida;   
}



function bisiesto(mes, anio) {
	var es_bisiesto = false;
	
	if (anio % 4 == 0)
		es_bisiesto = true;
	if (anio % 100 != 0) {
		if (anio % 400 == 0) 
			es_bisiesto = true;
		else 
			es_bisiesto = false;
	}
	if (es_bisiesto) 
		dias = 29;
	else 
		dias = 28;
	return(dias);
}

//Añadida el 27/XI/2002 para comprobar que una fecha introducida es anterior a la actual
function esFechaNacAnt (fecha)
{
	
	if (isEmpty(fecha)) 
       if (esFechaNacAnt.arguments.length == 1) return defaultEmptyOK;
       else return (esFechaNacAnt.arguments[1] == true);
	
	var Parametros;
	var dia_nac,mes_nac,ano_nac;
			
	Parametros=new ParametrosCrear("");

	// MEJORAS: SE PUEDE INTENTAR VER SI LA FECHA TIENE "/", SI LAS TIENES SE USA COMO
	// SEPARADOR, SI NO LAS TIENE, SE PUEDE INTENTAR BUSCAR "-" Y ASÍ CON OTROS SEPARADORES
	
	ParametrosTratar(Parametros,fecha,"/");

	// LA FECHA DEBE TENER TRES PARÁMETROS
	if (Parametros.length<3) return (false);
	
	// COMPROBAMOS CADA PARÁMETRO
	dia_nac=Parametros[2];
	mes_nac=Parametros[3];
	ano_nac=Parametros[4];
	
	//alert("La fecha de nacimiento: "+dia_nac+"/"+mes_nac+"/"+ano_nac);
	
	//primero cojo la fecha de hoy
	hoy = new Date();
	dia = hoy.getDate();
	mes = hoy.getMonth()+1;
	anno = hoy.getYear()+1900;
	//alert("La fecha de hoy: "+dia+"/"+mes+"/"+anno);
	
	//comparo si la fecha introducida es anterior o no
	if (ano_nac > anno)
		return false
	else
		if (ano_nac < anno)
			return true;
		else //es el mismo año
			if (mes_nac > mes)
				return false;
			else
				if (mes_nac < mes)
					return true;
				else //es el mismo mes
					if (dia_nac < dia)
						return true
					else
						return false; // no se admiten personas que hayan nacido hoy
}

//Añadida el 02/12/2002 para la comprobación del Código Postal
function esCodigoPostal (s)
{
	if (isEmpty(s)) 
       if (esCodigoPostal.arguments.length == 1) return defaultEmptyOK;
       else return (esCodigoPostal.arguments[1] == true);
	
	if ((!isNumber(s)) || (s.length!=5))
		return false;
	else
		return true;
}

//Añadida el 03/12/2002 para verificar que la URL empieza por "http[s]://..."
function esURL (s)
{
	//alert("Ha entrado en la función esURL");
	
	if (isEmpty(s)) 
       if (esURL.arguments.length == 1) return defaultEmptyOK;
       else return (esURL.arguments[1] == true);
	
	var urlDomainPat=/^(http[s]?:\/\/)/;

	var URLArray=s.match(urlDomainPat);
	
	if (URLArray!=null)
	{
		//alert("URL válida");
		return true;
	}
	else
	{
		//alert("URL no válida");
		return false;
	}
}

// Las siguientes funciones comprueban tanto el formato como la letra del NIF
// añadidas el 18/12/2002

function esFormatoNIF (nif)
{
	//alert("Ha entrado en la función esFormatoNIF "+nif);
	
	if (isEmpty(nif)) 
       if (esFormatoNIF.arguments.length == 1) return defaultEmptyOK;
       else return (esFormatoNIF.arguments[1] == true);
	
	var nifDomainPat=/^[0-9]{1,8}[a-zñA-ZÑ]$/;

	var NIFArray=nif.match(nifDomainPat);
	
	if (NIFArray!=null)
	{
		//alert("NIF válido");
		return true;
	}
	else
	{
		//alert("NIF no válido");
		return false;
	}	
}

function esLetraNIF (nif)
{
	//alert("Ha entrado en la función esLetraNIF");
	
	if (isEmpty(nif)) 
       if (esLetraNIF.arguments.length == 1) return defaultEmptyOK;
       else return (esLetraNIF.arguments[1] == true);
	
	var arrayLetraNIF = new Array ("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");
	while (nif.length<9)
		nif = "0" + nif;	
		
	// Desglosamos el NIF
	letraControl=nif.substring(8,9).toUpperCase();
	//alert("La letra introducida: "+letraControl);
	numero=nif.substring(0,8);
	
	//Comprobamos la letra
	letraCalculada=arrayLetraNIF [((parseFloat(numero)%23))]; //El algoritmo dice que al resto hay que 
														//sumarle 1, eso lo hacemos al indexar el 
														//array ya que los indices empiezan en 0
	//alert("La letra calculada: "+letraCalculada);
	if (letraCalculada == letraControl)				  
	{
		//alert("Letra válida");
		return true;
	}
	else
	{
		//alert("Letra no válida");
		return false;
	}	
}

// Las siguientes funciones comprueban tanto el formato como la letra del CIF
// añadidas el 19/12/2002

function esFormatoCIF (cif)
{
	//alert("Ha entrado en la función esFormatoCIF");
	
	if (isEmpty(cif)) 
       if (esFormatoCIF.arguments.length == 1) return defaultEmptyOK;
       else return (esFormatoCIF.arguments[1] == true);
	
	var cifDomainPat=/^[a-zA-Z][0-9]{1,8}$/;

	var CIFArray=cif.match(cifDomainPat);
	
	if (CIFArray!=null)
	{
		//alert("CIF válido");
		return true;
	}
	else
	{
		//alert("CIF no válido");
		return false;
	}	
}
