// Definición de variables
var digitos    = "0123456789";
var minusculas = "abcdefghijklmnopqrstuvwxyz";
var mayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var caracterestildados = "áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙñÑâêîôûÂÊÎÔÛäëïöüÄËÏÖÜ";
var caracteresLoginPassword = "._-";
var letrasNIF  = "TRWAGMYFPDXBNJZSQVHLCKET"; // Tabla predefinida de letras para el N.I.F
var letrasCIF  = "ABCDEFGHKLMPQSXZ";

// Valida una cadena vacía.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// Determina si un campo es nulo
function isNotBlank (field,fieldName){
  if (eval('document.'+field+'.'+fieldName+'.value') == "") {
    return false;
  }
  else
    return true;
}

// Determina si un caracter c pertenece a una cadena s
function perteneceA(c,s) {
  var result = false;

  for (var i = 0; i < s.length; i++) {
    if (c == s.charAt(i)) {
      result = true;
      break;
    }
  }
  return result;
}

// Determina si los caracteres de un campo de entrada equivalen a un número entero
function valV10(s) {
  var c;
  var result = true;

  for (var i = 0; i < s.length; i++) {
    c = s.charAt(i);
    if (!(perteneceA(c,digitos))) {
      result = false;
      break;
    }
  }
  return result;
}

//Convierte una cadena en minúsculas salvo el primer caracter
function toUpper(field,fieldName) {
  var index;
  var result;
  var tmpChar;
  var preString;
  var postString;
  var strlen;

  value = eval('document.'+field+'.'+fieldName+'.value');

  result = value.toLowerCase();

  strLen = result.length;
  if (strLen > 0)  {
    for (index = 0; index < strLen; index++)  {
      if (index == 0)  {
        tmpChar    = result.substring(0,1).toUpperCase();
        postString = result.substring(1,strLen);
        result     = tmpChar + postString;
      }
      else {
        tmpChar = result.substring(index, index+1);
        if ((!(perteneceA(tmpChar,minusculas) || perteneceA(tmpChar,mayusculas) || perteneceA(tmpChar,caracterestildados))) && index < (strLen-1)) {
          tmpChar    = result.substring(index+1, index+2).toUpperCase();
          preString  = result.substring(0, index+1);
          postString = result.substring(index+2,strLen);
          result     = preString + tmpChar + postString;
        }
      }
    }
  }
  return result;
}

// Valida un NIF
function isDNI (field,fieldName){
  isValid = true;
  key = " "
  value = eval('document.'+field+'.'+fieldName+'.value');
  
  // El NIF tiene como máximo 9 caracteres
  if (value.length > 9 )
	isValid = false;
	
  // El N.I.F. tiene como último caracter una letra
  if (value.charAt(value.length -1) <"A" || value.charAt(value.length -1) > "Z" )
	isValid = false;
	
  // El N.I.F. debe cumplir que todos sus caracteres excepto el último son dígitos
  if ( !valV10 (value.substr (0,value.length -1 )))
	isValid = false;
	
  // El N.I.F. tiene una letra asociada incorrecta
  if (isValid) {
	dValor =  value.substr (0, value.length -1);
	iNumero = (dValor %  23);
	if (letrasNIF.charAt (iNumero) != value.charAt(value.length-1))
	  isValid = false;
  }
  return isValid;
}

// Valida un CIF y si no lo es, si es NIF
function isCIF (field,fieldName){
  isValid = true;
  key = " "
  value = eval('document.'+field+'.'+fieldName+'.value');
  
  // El CIF tiene como máximo 9 caracteres
  if (value.length > 9 ) {
	isValid = false;
	sErrorCausa = "El C.I.F. debe contener un máximo de 9 caracteres.";
  }
	
  // El CIF no empezar por una letra cualquiera
  if (!(perteneceA(value.charAt(0),letrasCIF))) {
	isValid = false;
	sErrorCausa = "El C.I.F. comienza por una letra no valida.";
  }
	
  // El CIF debe cumplir que todos sus caracteres excepto el primer y el último (pueder serlo o no) son dígitos
  if ( !valV10 (value.substr(1,value.length -2 ))) {
	isValid = false;
	sErrorCausa = "El C.I.F. contiene un valor no válido.";
  }
  
  if (isValid) {
    // Eliminamos la primera letra y el dígito de control
	var Valor = value.substr(1,value.length - 2);
	// Si no son 7 dígitos añadimos ceros
	var cerosAdicionales = 7 - Valor.length;
	for ( i=0 ; i < cerosAdicionales ; i++) {
	  Valor = "0" + Valor;
	  }
	// Obtenemos el dígito de control
	var DC = value.charAt(value.length-1);
	// Operación con los pares
	var sumaA = Number(Valor.charAt(1)) + Number(Valor.charAt(3)) + Number(Valor.charAt(5));
	// Operación con los impares
	var sumaB = 0;
	for (i = 0 ; i < 8 ; i = i + 2) {
	  aux1 = String(Number(Valor.charAt(i)) * 2);
	  if (aux1.length > 1) {
	    aux2 = Number(aux1.charAt(0)) + Number(aux1.charAt(1));
	  }
	  else {
	    aux2 = Number(aux1);
	  }
	  sumaB = sumaB + aux2;
	}
	// Continúa el algoritmo para obtener el dígito de control
	var sumaC= String(sumaA + sumaB);
	
	var DCbis;
	DCbis = 10 - Number(sumaC.charAt(1));
	if (sumaC.length > 1) {
	  if (sumaC.charAt(1) == "0") {
	    DCbis = 10 - Number(sumaC.charAt(1));
	  }
	  else {
	    DCbis = 10 - Number(sumaC.charAt(1));
	  }
	}
	else {
	  DCbis = 10 - Number(sumaC);
	}
	
	// Validamos el dígito de control obtenido
	if (perteneceA(DC,mayusculas)) {
	  if (DCbis != (mayusculas.indexOf(DC)+1))
	    isValid = false;
	}
	else
	  if (perteneceA(DC,digitos)) {
	    if (DCbis != DC)
	      isValid = false;
	    }
	  else
	    isValid = false;
	}
  
  // comprobamos que no se haya metido un NIF
  if (!isValid)
    isValid = isDNI (field,fieldName)
  return isValid;
}

// Valida un e-mail
function isEMAIL (field,fieldName){
  isValid = false;
  
  value = eval('document.'+field+'.'+fieldName+'.value');
  atPos = value.indexOf("@");
  
  if (atPos != -1 && atPos > 0 ) {
    dotPos = value.substring(atPos+1, value.length).indexOf(".");
    if (dotPos != -1 && (atPos + dotPos + 2) != value.length)
	  isValid = true;
  }
  return isValid;
}

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
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

// Valida el login: Determina si los caracteres de una cadena son números, letras, guión bajo "_" o punto "."
function isUserName(s) {
  var c;
  var result = true;

  for (var i = 0; i < s.length; i++) {
    c = s.charAt(i);
    if (!(perteneceA(c,minusculas) || perteneceA(c,mayusculas) || perteneceA(c,caracteresLoginPassword) || 
                      perteneceA(c,digitos))) {
      result = false;
      break;
    }
  }
  return result;
}

// Valida un año. Ha de ser de 2 ó 4 dígitos sólo.
function isYear (s) {
  var result = true;
  if (isEmpty(s) || (!(isInteger(s))) || s==0)
    result = false;
  if (!((s.length == 2) || (s.length == 4)))
    result = false;  
  return result;
}

// Valida si es un entero.
function isInteger (s)
{   var i;
    if (isEmpty(s)) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (!perteneceA(c,digitos)) return false;
    }
    // All characters are numbers.
    return true;
}

// Valida si un entero está dentro de un rango.
function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) return False;

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

// Valida un mes
function isMonth (s)
{   if (isEmpty(s)) return false;
    return isIntegerInRange (s, 1, 12);
}

// iValida un día
function isDay (s)
{   if (isEmpty(s)) return false;
    return isIntegerInRange (s, 1, 31);
}

// Valida días de Febrero de un año determinado
function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

// Valida una fecha
function isDate (year, month, day)
{   // valida año, mes y día.
    if (! (isYear(year) && isMonth(month) && isDay(day))) return false;
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear  = parseInt(year);
    var intMonth = parseInt(month);
    var intDay   = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

// Valida número de cuenta
function isCCC (field,fieldName, pos){
  value = eval('document.'+field+'.'+fieldName+'.value');

  if (pos == 1 && !isNaN(value) & value.length == 4)
    return true;
  if (pos == 2 && !isNaN(value) & value.length == 4)
    return true;
  if (pos == 3 && !isNaN(value) & value.length == 2)
    return true;
  if (pos == 4 && !isNaN(value) & value.length == 10)
    return true;
	
  return false;
}

// Valida un Código Postal
function isZIP (field,fieldName){
  value = eval('document.'+field+'.'+fieldName+'.value');
  
  if (!isNaN(value) & value.length == 5)
    return true;
	
  return false;
}

// Valida un número de teléfono
function isPhoneNumber (field,fieldName){
  value = eval('document.'+field+'.'+fieldName+'.value');
  if (value.length > 8)
    return true;
  return false;
}
