//=================================================
//= USUARIO LIBERACIÓN: BTORALV
//= FECHA/HORA LIBERACIÓN: 26/11/02 14:02
//=================================================
// ---------------------------------------------------------------------- //
//           FormCheq.js (c) ChaTo 1998,1999 [www.chato.cl]
//                           Basado en:
//           FormChek.js (c) Eric Krock (c) 1997 Netscape              
// ---------------------------------------------------------------------- //
// 18 Feb 97 creado por Eric Krock (c) 1997
//   Netscape Communications Corporation
// 18 Ago 98 modificado por Carlos Castillo (c) 1998 ChaTo
//   Los principales cambios son: esta version es simplificada, para
//   propositos de ensennanza y validacion basica de formularios, y esta
//   adaptada para recibir caracteres del alfabeto espannol (acentos, etc.)
// 20 Oct 99 modificado por Carlos Castillo (c) 1999 ChaTo
//   Se agrega la funcion isNice que ayuda a evitar comillas simples
//   o dobles que causan problemas con muchos CGIs
// 
// ---------------------------------------------------------------------- //
//                             RESUMEN                                    //
// ---------------------------------------------------------------------- //
// 
// El objetivo de las siguientes funciones en JavaScript es
// validar los ingresos del usuario en un formulario antes
// de que estos datos vayan al servidor.
//
// Varias de ellas toman un parametro opcional E.O.K (eok) (emptyOK
// - true si se acepta que el valor este vacio, false si no
// se acepta). El valor por omision es el que indique la
// variable global defaultEmptyOK definida mas abajo.
//
// ---------------------------------------------------------------------- //
//                      SINTAXIS DE LAS FUNCIONES                         //
// ---------------------------------------------------------------------- //
//
// FUNCION PARA CHEQUEAR UN CAMPO DE INGRESO:
//
// checkField (theField, theFunction, [, s] [,eok])
//        verifica que el campo de ingreso theField cumpla con la
//        condicion indicada en la funcion theFunction (que puede ser
//        una de las descritas en "FUNCIONES DE VALIDACION" o cualquier
//        otra provista por el usuario). En caso contrario despliega el
//        string "s" (opcional, hay mensajes por default para las
//        funciones de validacion provistas aqui).
//
// FUNCIONES DE VALIDACION:
//
// isInteger (s [,eok])                s representa un entero
// isNumber (s [,eok])                 s es entero o tiene punto decimal
// isAlphabetic (s [,eok])             s tiene solo letras
// isAlphanumeric (s [,eok])           s tiene solo letras y/o numeros
// isPhoneNumber (s [,eok])            s tiene solo numeros, (,),-
// isEmail (s [,eok])                  s es una direccion de e-mail
// isNIF (s [,eok])                  s es un NIF  //Belarmino 06/08/02
// isCIF (s [,eok])                  s es un CIF  //Belarmino 18/10/02
//
// FUNCIONES INTERNAS:
//
// isWhitespace (s)                    s es vacio o solo son espacios
// isLetter (c)                        c es una letra
// isDigit (c)                         c es un digito
// isLetterOrDigit (c)                 c es letra o digito
//
// FUNCIONES PARA REFORMATEAR DATOS:
//
// stripCharsInBag (s, bag)            quita de s los caracteres en bag
// stripCharsNotInBag (s, bag)         quita de s los caracteres NO en bag
// stripWhitespace (s)                 quita el espacio dentro de s
// stripInitialWhitespace (s)          quita el espacio al principio de s
//
// FUNCIONES PARA PREGUNTARLE AL USUARIO:
//
// statBar (s)                         pone s en la barra de estado
// warnEmpty (theField, s)             indica que theField esta vacio
// warnInvalid (theField, s)           indica que theField es invalido
//
// ---------------------------------------------------------------------- //
//                                VARIABLES                               //
// ---------------------------------------------------------------------- //

// Esta variable indica si está bien dejar las casillas
// en blanco como regla general
var defaultEmptyOK = false

// Esta variable indica si se debe verificar la presencia de comillas
// u otros símbolos extraños en un campo, por omisión no, porque
// siempre crea problemas con las bases de datos o programas CGI
var checkNiceness = true;

// listas de caracteres
var digits = "0123456789";
//var mixedLettersDigits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü_";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ_";
var whitespace = " \t\n\r";

// caracteres admitidos en nos de telefono
var phoneChars = "()-+ ";

// ---------------------------------------------------------------------- //
//                     TEXTOS PARA LOS MENSAJES                           //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
var mMessage = "Error: no puede dejar este campo vacio"

// p abrevia "prompt"
var pPrompt = "Error: ";
var pAlphanumeric = "Inserte un texto que contenga solo letras y/o números";
var pAlphabetic   = "Inserte un texto que contenga solo letras";
// ----------------------------------------------------------------------- //
//                  MODIFICACIÓN HECHA POR VERONICA                        //
// ----------------------------------------------------------------------- //
// var pInteger = "Inserte un número entero (-32768 a 32767)";
var pInteger = "Inserte un número entero";
// ----------------------------------------------------------------------- //
var pLong = "Inserte un número entero (-2147483648 a 2147483647)";
var pByte = "Inserte un número (0 a 255)";
var pDouble = "Inserte un número con decimales válido"
var pNumber = "Inserte un número";
var pPhoneNumber = "Inserte un número de teléfono";
var pEmail = "Inserte una dirección de correo electrónico válida";
var pName = "Inserte un texto que contenga solo letras, numeros, espacios o ´ ";
var pTelefono = "FORMATO DE TELÉFONO NO VÁLIDO.\n\nUn teléfono válido	está formado por:\n\n\t* un prefijo de tres dígitos (en el que el primer dígito es un 9, un 8 ó un 6)\n\t* un guión (-)\n\t* y seís dígitos más\n\t* A continuación puede ir un comentario libre.\n\n\n\tEjemplo de teléfono válido: 922-123456 (Abuela)\n\n\nNOTA: Para abandonar esta casilla, vacíe el teléfono o insértelo de forma correcta."
var pNice = "No puede utilizar comillas aqui";
var pNif = "Inserte un número de NIF correcto";
var pCIF = "Inserte un número de CIF correcto";
var pCIAL = "Inserte un número de CIAL correcto";

// ---------------------------------------------------------------------- //
//                FUNCIONES PARA MANEJO DE ARREGLOS                       //
// ---------------------------------------------------------------------- //

// JavaScript 1.0 (Netscape 2.0) no tenia un constructor para arreglos,
// asi que ellos tenian que ser hechos a mano. Desde JavaScript 1.1 
// (Netscape 3.0) en adelante, las funciones de manejo de arreglos no
// son necesarias.

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

// ---------------------------------------------------------------------- //
//                  CODIGO PARA FUNCIONES BASICAS                         //
// ---------------------------------------------------------------------- //


// s es vacio
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// s es vacio o solo caracteres de espacio
function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}

// Quita todos los caracteres que que estan en "bag" del string "s" s.
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;
}

// Lo contrario, quitar todos los caracteres que no estan en "bag" de "s"
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;
}

// Quitar todos los espacios en blanco de un string
function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

// La rutina siguiente es para cubrir un bug en Netscape
// 2.0.2 - seria mejor usar indexOf, pero si se hace
// asi stripInitialWhitespace() no funcionaria

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// Quita todos los espacios que antecedan al string
function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

// c es una letra del alfabeto espanol
function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

// c es un digito
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// c es letra o digito
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

// ---------------------------------------------------------------------- //
//                          NUMEROS                                       //
// ---------------------------------------------------------------------- //

// s es un numero entero (con o sin signo)
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;
        }
    }
	if (s>32767 || s<(-32768)) return false;
    return true;
}

// Belar 16/10/02
// s es un numero doble (con o sin signo) 
function isDouble (s)
{   var i;
	 var decimalseparator=false;
	 
    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 (c==',')
			{
				if (decimalseparator) 
					return false;
				else 
					decimalseparator=true;
			}
			else 	
				if (!isDigit(c))  return false;
        } 
        else  
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
    }
	return true;
}

// s es un Long (con o sin signo)
function isLong (s)
{   var i;
    if (isEmpty(s)) 
       if (isLong.arguments.length == 1) return defaultEmptyOK;
       else return (isLong.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;
        }
    }
	if (s>2147483647 || s<(-2147483648)) return false;
    return true;
}

// s es un Byte
function isByte (s)
{   var i;
    if (isEmpty(s)) 
       if (Byte.arguments.length == 1) return defaultEmptyOK;
       else return (Byte.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c)) return false;
        }
    }
	if (s>255 || s<0) return false;
    return true;
}



// s es un numero (entero o flotante, con o sin signo)
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;
}

// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES                                 //
// ---------------------------------------------------------------------- //

// s tiene solo letras
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;
}


// s tiene solo letras y numeros
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;
}

// s no contiene comillas simple o doble
function isStringSinComillas (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 ((c=="'" || c=='"' || c=='<' || c=='>'))
        return false;
    }
    return true;
}

// s tiene solo letras, numeros o espacios en blanco
function isName (s)
{
	var tmp = "'";
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    return(isStringSinComillas(s))
    //return(isAlphanumeric( stripCharsInBag( s, whitespace ) ) || isAlphanumeric( stripCharsInBag( s, '´' ) )) ;
   
}

// ---------------------------------------------------------------------- //
//                           FONO o EMAIL                                 //
// ---------------------------------------------------------------------- //

// s es numero de telefono valido
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))
}

// s es una direccion de correo valida
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 isTelefono(s) {
	var i;
	
	if (! isStringSinComillas(s))
		return false;
	
	if (s.length < 10) 
		return false;
		
	//Comprobamos los 3 primeros dígitos (prefijo)
	//El primero debe ser un 9, un 8 ó un 6
	if ((s.charAt(0) != "9") && (s.charAt(0) != "8") && (s.charAt(0) != "6"))
		return false;
	//Los otros dos deben ser números.
	for (i = 1; i < 3; i++) {
		if (! isDigit(s.charAt(i)))
			return false;	
	}
	
	//Comprobamos el guión de separación
	if (s.charAt(3) != "-")
		return false;
		
	//Comprobamos los otros 6 dígitos
	for (i = 4; i < 10; i++) {
		if (! isDigit(s.charAt(i)))
			return false;	
	}
	
	//Comprobamos si ha introducido comentario malo	
	//Ej: 922-1234567				No es un comentario correcto: 
	//								Hay un nº en la posición 10.
	//Ej: 922-123456(abuela)		Sí es un comentario correcto.
	if (s.length > 10) {
		if (isDigit(s.charAt(10)))
			return false;
	}
		
	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;
}



//David 13/03/03
 function isNIF(s)
{
var NIF;
var NCaracteres;
var CadAux;
var i;

	NIF = s.value;	
	NCaracteres=NIF.length;
	
	if (isEmpty(NIF)) 
       if (isNIF.arguments.length == 1) return defaultEmptyOK;
       else return (isNIF.arguments[1] == true);
    if (isWhitespace(NIF)) return false;
    else
    {
		var Resto = 0;
		var aLetra = 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");
		var Letra;
		var Prefijo;
		
		if ((NIF.charAt(0)=='*') && (NIF.length<16)) return(true);		
		
		CadAux="";
		if ( ( (NIF.charAt(0).toUpperCase()=='X') || (NIF.charAt(0).toUpperCase()=='Y')) && (NCaracteres < 10)){
			for (i=0;i<10-NCaracteres;i++){
				CadAux += "0";				
			}	
			NIF= NIF.charAt(0).toUpperCase() + CadAux + NIF.substring(1,NCaracteres);
		}
		if ((NIF.charAt(0).toUpperCase()!='X') && (NIF.charAt(0).toUpperCase()!='Y') && (NCaracteres < 9)){
			for (i=0;i<9-NCaracteres;i++){
				CadAux += "0";				
			}	
			NIF= CadAux + NIF.substring(0,NCaracteres);
		}
					
		if (((NIF.charAt(0).toUpperCase()=='X') || (NIF.charAt(0).toUpperCase()=='Y')  || (NIF.charAt(0).toUpperCase()=='L') ) && ((NIF.length==10)))
		{
			Letra =  NIF.charAt(9);
			if ( (Letra.length==0) || isNaN(NIF.substring(1,9)) || !isLetter(Letra))
			{
				alert('El NIE para extranjeros debe empezar por X o Y, luego incluir  8 digitos numéricos y acabar en letra.');
				return false;
			}

			if ((NIF.charAt(0).toUpperCase()=='Y'))
				Resto = parseFloat( '1'+ NIF.substring(2,9)) % 23; 
			else
				Resto = parseFloat( NIF.substring(1,9)) % 23; 

		}
		else
		{
			Letra =  NIF.charAt(8);
			if (((Letra.length==0) && !(NIF.length==8)) || isNaN(NIF.substring(1,8)) || (NIF.length>9) || !isLetter(Letra))
			{
				alert('El NIF debe tener ocho cifras y acabar con una letra. \nEn el caso de NIE para extranjeros puede empezar por X o Y.\nPara pasaportes,etc debe comenzar por * y luego incluir un máximo de 14 caracteres.');
				return false;
			}
			if ((NIF.length < 10) && ((NIF.charAt(0).toUpperCase()=='X') || (NIF.charAt(0).toUpperCase()=='Y')) ) {
				alert('El  NIE para extranjeros puede empezar por X o Y seguida de ocho cifras y una letra.');
				return(false);
			}	

			if ((isLetter(NIF.charAt(0))) && (NIF.charAt(0).toUpperCase()!='X') && (NIF.charAt(0).toUpperCase()!='Y')) {
				alert('El NIF debe tener ocho cifras y acabar con una letra.');
				return(false);
			}	
			Resto = parseFloat(NIF.substring(0,8)) % 23; 
		}
		Letra = Letra.toUpperCase( );
		if (! (aLetra[Resto]==Letra))
		{
			alert('La letra introducida para este NIF no es correcta. Debería ser la ' + aLetra[Resto]);
			return false;
		}
		return(true);
	}
}


function isCIF(cif)
{
	var sPRI;
	var sULT;
	var sRESTO;
	var i;
	var iSUMA;
	var sIMPARES = new Array(4);
	var sCIF;
	var sPfx;
	var sTmp;
	var respuesta;
	
	sCIF =  cif.value.toUpperCase();	
	sCIF =stripCharsNotInBag( sCIF, digits+uppercaseLetters );
	if (isNaN(sCIF.charAt(0)) && !(sCIF.charAt(0)=='X') && !(sCIF.charAt(0)=='L')) // si es una Letra que no sea del NIF
	{
		if (sCIF.length==9)
		{
			sPRI = sCIF.charAt(0);
			sULT = sCIF.charAt(8);
			sRESTO = sCIF.substring(1,8);
			iSUMA = parseInt(sRESTO.charAt(1)) + parseInt(sRESTO.charAt(3)) + parseInt(sRESTO.charAt(5));
	
			if (( 2 * parseInt(sRESTO.charAt(0)))<10) sPfx = '0'; else      sPfx = '';
			sIMPARES[0] = sPfx + (2 * parseInt(sRESTO.charAt(0)));
			
			if (( 2 * parseInt(sRESTO.charAt(2)))<10) sPfx = '0'; else	sPfx = '';
			sIMPARES[1] = sPfx + (2 * parseInt(sRESTO.charAt(2)));
			
			if (( 2 * parseInt(sRESTO.charAt(4)))<10) sPfx = '0'; else	sPfx = '';
			sIMPARES[2] = sPfx + (2 * parseInt(sRESTO.charAt(4)));
			
			if (( 2 * parseInt(sRESTO.charAt(6)))<10) sPfx = '0'; else	sPfx = '';
			sIMPARES[3] = sPfx + (2 * parseInt(sRESTO.charAt(6)));
			
			
			for (i=0;i<4;i++)
			{
				iSUMA = iSUMA + parseInt(sIMPARES[i].charAt(0)) + parseInt(sIMPARES[i].charAt(1));
			}
			
			sTmp = '' + (10 - parseInt(('' + iSUMA).charAt(('' + iSUMA).length-1)));
			if ( !(sPRI =='X') && !(sPRI == 'P') && !(sPRI == 'S') && !(sPRI == 'Q')) //No es un ayuntamiento/extranjero
			 	respuesta = (sULT == sTmp.charAt(sTmp.length-1));
			else
				respuesta = (sULT == String.fromCharCode(64 + parseInt(sTmp)));
			
			if (!respuesta) alert('El CIF introducido parece ser incorrecto');
	
		}
		else alert('El CIF debe tener 9 caracteres');
	}
	else respuesta=isNIF(cif);// Si no es un CIF, se puede dar por válido un NIF para los autónomos
	
	return true;			
}

// Función basada en la función SQL ALU_F_CIALValido del 13/06/2006
function isCIAL(s) {
var re;
var Letra;
var L1 = 'AB';
var L2 = 'BXGMPHTLRACF';
var L3 = 'TRWAGMYFPDXBNJZSQVHLCKE';
var Codigo;
var DigitCont;


  if (isEmpty(s.value)) 
         if (isCIAL.arguments.length == 1) return defaultEmptyOK;
       else return (isCIAL.arguments[1] == true);
    if (isWhitespace(s.value)) return false;
  else  {

  if (s.value.length==10) {     
     Letra = s.value.charAt(0); 
     re = new RegExp(Letra,"i") 
     if (L1.search(re) > -1) {           
        Letra = s.value.charAt(3);          
        re = RegExp(Letra,"i")         
        if (L2.search(re) > -1) {
           Letra = s.value.charAt(9); 
           re = RegExp(Letra,"i") 
           if (L3.search(re) > -1) {              
              if (!isNaN(s.value.substring(1,3)) && !isNaN(s.value.substring(4,9))) {
                 DigitCont = s.value.substring(9,10).toUpperCase();
                 Codigo = s.value.substring(0,9).toUpperCase();                                                                       
                 if (DigitoControlCIAL(Codigo) == DigitCont) {
                    //alert('Es correcto');
                    return(true);
                 }
                 else {
                    alert('El CIAL tiene un formato incorrecto. Letra de control erronea.');
                    return(false);          
                 }
              }
              else {
                 alert('El CIAL tiene un formato incorrecto. Las posiciones 2,3 y de la 5 a la 9 deben ser números.');
                 return(false);          
              }              
           }
           else {            
              alert('El CIAL tiene un formato incorrecto. Las última posición debe ser una letra correcta.');
              return(false);          
           }
        }
        else {
           alert('El CIAL tiene un formato incorrecto. La cuarta posición debe ser una letra correcta.');
           return(false);
        }  
     }
     else {            
        alert('El CIAL tiene un formato incorrecto. La primera posición debe ser una letra correcta.');
        return(false);
     }        
  }
  else {
     alert('El CIAL tiene un formato incorrecto. La logitud debe de ser de 10 caracteres.');
     return(false);
  }
  }
}


//FUnción basada en la función SQL ALU_F_DigitoControlCIAL del 13/06/2006
function DigitoControlCIAL(s) {
var Resto;
var Resultado;
var CIALNum;
var LetraCIAL;
var L1 = 'TRWAGMYFPDXBNJZSQVHLCKE';

  CIALNum = 0;
  if (parseInt(s.substring(6,9),10) < 100) {               
     CIALNum += parseInt(s.charCodeAt(0),10);           
     CIALNum += parseInt(s.charCodeAt(1),10);     
     CIALNum += parseInt(s.charCodeAt(2),10);     
     CIALNum += parseInt(s.charCodeAt(3),10);
     CIALNum += parseInt(s.charCodeAt(4),10);
     CIALNum += parseInt(s.charCodeAt(5),10);
     CIALNum += parseInt(s.charCodeAt(6),10);
     CIALNum += parseInt(s.charCodeAt(7),10);
     CIALNum += parseInt(s.charCodeAt(8),10);
  }
  else {               
     CIALNum += 1000000000 * (parseInt(s.charCodeAt(0),10) - 64);              
     CIALNum += 10000000 * parseInt(s.substring(1,3),10);           
     CIALNum += 100000 * (parseInt(s.charCodeAt(3),10) - 64);    
     CIALNum += parseInt(s.substring(4,9),10);    
  }           
  Resultado = CIALNum /23;
  Resultado = Math.floor(Resultado);  
  Resto = CIALNum -(Resultado*23);

  LetraCIAL = L1.substr(Resto, 1)
  //alert('Valores: ' + Resultado + ' Resto: '  + Resto);
  //alert('VALIDANDO LETRA DE CONTROL....LETRA = ' + LetraCIAL);
  return(LetraCIAL);
}


function ValidarCIF(cif)
{
	var sPRI;
	var sULT;
	var sRESTO;
	var i;
	var iSUMA;
	var sIMPARES = new Array(4);
	var sCIF;
	var sPfx;
	var sTmp;
	var respuesta;
	
	sCIF =  cif.value.toUpperCase();	
	sCIF =stripCharsNotInBag( sCIF, digits+uppercaseLetters );
	if (isNaN(sCIF.charAt(0)) && !(sCIF.charAt(0)=='X') && !(sCIF.charAt(0)=='L')) // si es una Letra que no sea del NIF
	{
		if (sCIF.length==9)
		{
			sPRI = sCIF.charAt(0);
			sULT = sCIF.charAt(8);
			sRESTO = sCIF.substring(1,8);
			iSUMA = parseInt(sRESTO.charAt(1)) + parseInt(sRESTO.charAt(3)) + parseInt(sRESTO.charAt(5));
	
			if (( 2 * parseInt(sRESTO.charAt(0)))<10) sPfx = '0'; else      sPfx = '';
			sIMPARES[0] = sPfx + (2 * parseInt(sRESTO.charAt(0)));
			
			if (( 2 * parseInt(sRESTO.charAt(2)))<10) sPfx = '0'; else	sPfx = '';
			sIMPARES[1] = sPfx + (2 * parseInt(sRESTO.charAt(2)));
			
			if (( 2 * parseInt(sRESTO.charAt(4)))<10) sPfx = '0'; else	sPfx = '';
			sIMPARES[2] = sPfx + (2 * parseInt(sRESTO.charAt(4)));
			
			if (( 2 * parseInt(sRESTO.charAt(6)))<10) sPfx = '0'; else	sPfx = '';
			sIMPARES[3] = sPfx + (2 * parseInt(sRESTO.charAt(6)));
			
			
			for (i=0;i<4;i++)
			{
				iSUMA = iSUMA + parseInt(sIMPARES[i].charAt(0)) + parseInt(sIMPARES[i].charAt(1));
			}
			
			sTmp = '' + (10 - parseInt(('' + iSUMA).charAt(('' + iSUMA).length-1)));
			if ( !(sPRI =='X') && !(sPRI == 'P') && !(sPRI == 'S') && !(sPRI == 'Q')) //No es un ayuntamiento/extranjero
			 	respuesta = (sULT == sTmp.charAt(sTmp.length-1));
			else
				respuesta = (sULT == String.fromCharCode(64 + parseInt(sTmp)));
			
			if (!respuesta){ 
				alert('El CIF introducido parece ser incorrecto');
				return false;
			}
		}
		else{ 
			alert('El CIF debe tener 9 caracteres');
			return false;	
		}	
	}
	else respuesta=isNIF(cif);// Si no es un CIF, se puede dar por válido un NIF para los autónomos
	cif.value=sCIF;
	return respuesta;		
}


// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA RECLAMARLE AL USUARIO                  //
// ---------------------------------------------------------------------- //

// pone el string s en la barra de estado
function statBar (s)
{   window.status = s
}

// notificar que el campo theField esta vacio
function warnEmpty (theField)
{   
	alert(mMessage)
	theField.focus()
    //statBar(mMessage)
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   alert(s)
	theField.focus()
    theField.select()
    //statBar(pPrompt + s)
    return false
}

// el corazon de todo: checkField
function checkField (theField, theFunction, emptyOK, s)
{   
    var msg;
    var TmpFldValue; //Belarmino 06/08/02
    TmpFldValue=theField.value; //Belarmino 06/08/02
    if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
    if (checkField.arguments.length == 4) {
        msg = s;
    } else {
        if( theFunction == isAlphabetic ) msg = pAlphabetic;
        if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
        if( theFunction == isInteger ) msg = pInteger;
		if( theFunction == isLong ) msg = pLong;
		if( theFunction == isByte ) msg = pByte;
        if( theFunction == isNumber ) msg = pNumber;
        if( theFunction == isNumber ) msg = pDouble;
        if( theFunction == isDouble ) msg = pDouble;
        if( theFunction == isEmail ) msg = pEmail;
        if( theFunction == isPhoneNumber ) msg = pPhoneNumber;
        if( theFunction == isName ) msg = pName;
        if( theFunction == isTelefono) msg = pTelefono;
        if( theFunction == isNIF ) { msg = pNif; TmpFldValue = theField;}
        if( theFunction == isCIF ){ msg = pCIF; TmpFldValue = theField;}
        if( theFunction == isCIAL ){ msg = pCIAL; TmpFldValue = theField;}
        
    }
    
    if ((emptyOK == true) && (isEmpty(theField.value))) {
		statBar('Listo');
		return true;
	}

    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField);

    if ( checkNiceness && !isNice(theField.value))
        return warnInvalid(theField, pNice);
	
	if (theFunction(TmpFldValue) == true) { //Belarmino 06/08/02
	    statBar('Listo');
		return true;
	}	
	else
	{
		if (emptyOK)
		{
			alert(msg);
			theField.focus();
			theField.select();
			return false;		
		}
		else
			return(warnInvalid(theField,msg));
   }
	
	

}


