// whitespace characters
var whitespace = " \t\n\r";
var defaultEmptyOK = false;

function Vacio(s)
{   
	return ((s == null) || (s.length == 0))
}

function Fecha(dateStr)
{
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

// To require a 4 digit year entry, use this line instead:
// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
//alert("La fecha no está en un formato válido.")
return false;
}
month = matchArray[3]; // parse date into variables
day = matchArray[1];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
//alert("El mes debe estar entre 1 y 12.");
return false;
}
if (day < 1 || day > 31) {
//alert("El día debe estar entre 1 y 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
//alert("El mes "+month+" no tiene 31 dias!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
//alert("Febrero de " + year + " no tiene " + day + " dias!");
return false;
   }
}
return true;  // date is valid
}


function Hora(strHora)
{   
var horaPat = /^(\d{1,2})(\:)(\d{1,2})$/; //hh:mm
//var horaPat = /^(\d{1,2})(\:)(\d{1,2})(\:)(\d{1,2})$/; //hh:mm:ss
var res = strHora.match(horaPat); // is the format ok?
var arrHora
var hh
var mm
//var ss

	if (res == null) 
	{
		//alert("La hora no está en un formato válido.")
		return false;
	}
	arrHora=res[0].split(":")
	
	hh = parseInt(arrHora[0]);
	mm = parseInt(arrHora[1]);
//	ss = parseInt(arrHora[2]);
	
	//alert(hh+":"+mm+":"+ss)
	
	if (hh < 0 || hh > 23)
		return false;
	if (mm < 0 || mm > 59)
		return false;
//	if (ss < 0 || ss > 59)
//		return false;
		
	return true; //hora valida!
}

function HoraConSegs(strHora)
{   
var horaPat = /^(\d{1,2})(\:)(\d{1,2})(\:)(\d{1,2})$/; //hh:mm:ss
var res = strHora.match(horaPat); // is the format ok?
var arrHora
var hh
var mm
var ss

	if (res == null) 
	{
		//alert("La hora no está en un formato válido.")
		return false;
	}
	arrHora=res[0].split(":")
	
	hh = parseInt(arrHora[0]);
	mm = parseInt(arrHora[1]);
	ss = parseInt(arrHora[2]);
	
	//alert(hh+":"+mm+":"+ss)
	
	if (hh < 0 || hh > 23)
		return false;
	if (mm < 0 || mm > 59)
		return false;
	if (ss < 0 || ss > 59)
		return false;
		
	return true; //hora valida!
}

/****************************************************************/

// Returns true if string s is empty or 
// whitespace characters only.

function EnBlanco(s)

{   var i;
    
    // Is s empty?
    if (Vacio(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

/****************************************************************/

// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c ... in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function Email(s)
{   if (Vacio(s)) 
       if (Email.arguments.length == 1) return defaultEmptyOK;
       else return (Email.arguments[1] == true);
   
    // is s whitespace?
    if (EnBlanco(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function LongMax(objField, nLength, strWarning)
{
	var strField = new String(objField.value);

	if (strField.length > nLength) {
		alert(strWarning);
		return false;
	} else
		return true;
}

function digito(valor){
   numero=parseInt(valor);
   if (!(numero>=0 && numero<=9)){
	//alert("Introduzca un número entre 0 y 9");
	return(false);
   }
   return(true);
}


function Rango(valor,min,max){
   numero=parseInt(valor);
   if (!(numero>=min && numero<=max)){
	return(false);
   }
   return(true);
}

function entero(valor){
   nume=parseInt(valor);
   if ((nume != valor)){
	return(false);
   }
   return(true);
}

function numero(valor){
   nume=parseInt(valor);
   if ((nume != valor)){
	return(false);
   }
   return(true);
}

function Requerido(objField, FieldName)
{
	var strField = new String(objField.value);
	if (EnBlanco(strField)) {
		alert("Debe introducir " + FieldName);
		objField.focus();
		objField.select();
		return false;
	}

	return true;
}

function Decimal(valor){
	valor = valor.replace(",",".");
	num = parseFloat(valor)
	if (num!=valor){
		return(false)
	} else {
		return(true)
	}
}

function SonDigitos(cadena){
	var longitud = cadena.length
	var i
	var numero
	var ok=true
	i=0
	while ((i<longitud)&& (OK=true)) {
		numero=parseInt(cadena.charAt(i));		
		if (!(numero>=0 && numero<=9)){
			ok=false	
		}   
		i++;
	}
	return(ok)
}


function formatNum(num, numDecs) {
var valor
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10)
		cents = "0" + cents;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+ num.substring(num.length-(4*i+3));
	
	valor=((sign)?'':'-') + num
	if (numDecs > 0)
		valor = valor + ',' + cents
		
	return (valor);
}


function ConvertirFecha(dateStr)
{
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

// To require a 4 digit year entry, use this line instead:
// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

var matchArray = dateStr.match(datePat); // is the format ok?

month = matchArray[3]; // parse date into variables
day = matchArray[1];
year = matchArray[4];
return month+"/"+day+"/"+year
}

//Cada dígito de control valida una cosa. 
//El primero se encarga del banco y sucursal y el segundo del número de cuenta.
// Para validarlo otorgan a cada cifra un peso 
//(es decir, un número distinto por el que multiplicarla) 
//y suman los resultados. Luego, al número resultante le hacen una 
//serie de perrerías para convertirlo en una sola cifra.
//En definitiva, esta es la función que, a partir de una 
//cadena que contiene un número de diez cifras, devuelve el 
//dígito de control correspondiente:


function obtenerDigito(valor){
  valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
  control = 0;
  for (i=0; i<=9; i++)
    control += parseInt(valor.charAt(i)) * valores[i];
  control = 11 - (control % 11);
  if (control == 11) control = 0;
  else if (control == 10) control = 1;
  return control;
}


function validarCCC(CodEntidad,CodOficina,CodControl,NumCuenta)
{   
   if (!(obtenerDigito("00" + CodEntidad + CodOficina) == parseInt(CodControl.charAt(0))) 
        || !(obtenerDigito(NumCuenta) == parseInt(CodControl.charAt(1))))
	{        
		return false;
	}	
	else
	{
		return true;
    } 	
}
function validarNIFCIF(NumNifCif)
{
   var ch   
   
   ch = NumNifCif.charAt(0)
   if ( (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") )   
   {
		return validarCIF(NumNifCif)   
   }
   else
   {
		return validarNIF(NumNifCif)
   }   
}

function validarNIF(NumNif)
{
	var letra,letras=0;	
    var Numero
    var letraNif
    //alert("Longitud: " + NumNif.length)
    
    if (NumNif.length != 9) 
    {
      return false;
    }
    else	//Longitud correcta    
    {		
		for (var i=0; i<NumNif.length; i++) 
		{
			var ch = NumNif.substring (i, i+1);
			//Comprobación de los caracteres del NIF CIF
			
			if ( (ch < "0" || ch > "9") && (ch < "a" || ch > "z") && (ch < "A" || ch > "Z") )
		    {								
				return false;
			}
			
			if ( (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") )
			{
				letras++;
			}  
		}    
		//alert("Letras: " + letras)    
	    
	    if (letras != 1)
		{      		
			return false;
		}
		else	//Una sola letra
		{
			Numero = NumNif.substring(0,8)
			letra  = NumNif.substring(8,9)
			
			//alert(Numero)
			//alert(letra)			
			
			if (!isNaN(Numero)) // Es un numero
			{
				Numero = Numero % 23
				//alert(Numero)
				switch(Numero) 
				{
					case 0:
						letraNif="T";
						break;
					case 1:
						letraNif="R";
						break;
					case 2:
						letraNif="W";
						break;
					case 3:
						letraNif="A";
						break;
					case 4:
						letraNif="G";
						break;
					case 5:
						letraNif="M";
						break;
					case 6:
						letraNif="Y";
						break;
					case 7:
						letraNif="F";						
						break;
					case 8:
						letraNif="P";
						break;
					case 9:
						letraNif="D";
						break;
					case 10:
						letraNif="X";
						break;
					case 11:
						letraNif="B";
						break;
					case 12:
						letraNif="N";
						break;
					case 13:
						letraNif="J";
						break;
					case 14:
						letraNif="Z";
						break;
					case 15:
						letraNif="S";
						break;
					case 16:
						letraNif="Q";
						break;
					case 17:
						letraNif="V";
						break;
					case 18:
						letraNif="H";
						break;
					case 19:
						letraNif="L";
						break;
					case 20:
						letraNif="C";
						break;
					case 21:
						letraNif="K";
						break;
					case 22:
						letraNif="E";
						break;
					case 23:
						letraNif="R";
						break;						
				}				
				if (letra.toUpperCase () == letraNif)
				{
					return true
				}
				else
				{
					return false
				} 																
			}
			else
			{
				return false;
			}						
		}
    }
}

function validarCIF(NumCif)
{
	var letra,letras=0;	
    var Numero, control
    var letraCif
    var total,total1,total2
    var parcial, unidades
    var digito1,digito2
    var i
        
    
    if (NumCif.length != 9) 
    {
      return false;
    }
    else	//Longitud correcta    
    {		
		for (var i=0; i<NumCif.length; i++) 
		{
			var ch = NumCif.substring (i, i+1);
			//Comprobación de los caracteres del CIF			
			if ( (ch < "0" || ch > "9") && (ch < "a" || ch > "z") && (ch < "A" || ch > "Z") )
		    {								
				return false;
			}
			
			if ( (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") )
			{
				letras++;
			}  
		}    
		
	    if (letras > 2)
		{      		
			return false;
		}
		else	
		{
			letra   = NumCif.substring(0,1)
			Numero  = NumCif.substring(1,8)			
			control = NumCif.substring(8,9)
						
			if (!isNaN(Numero)) // Es un numero
			{
				//Suma de las posiciones pares
							
				total1 = parseInt(Numero.charAt(1)) + parseInt(Numero.charAt(3)) + parseInt(Numero.charAt(5))																
				total2 = 0				
				i=0
				while(i<=6)
				{
					digito1=0
					digito2=0
					parcial = parseInt(Numero.charAt(i))*2 									
					digito1 = parcial % 10
					digito2 = (parcial %100 - digito1) / 10
					total2  = parseInt(total2) + parseInt(digito1) + parseInt(digito2)
					i= i +2					
				}
															
				total = total1 + total2
				
				unidades = 10 - (total % 10)
				
				if (!isNaN(control)) //EsNumero
				{
					if (unidades=control)
					{				
						 return true
					}
					else 
					{				
						return false
					}
				}
				else	// Es Letra
				{
				
					switch(unidades) 
					{
						case 1:
							letraCif="A";
							break;
						case 2:
							letraCif="B";
							break;
						case 3:
							letraCif="C";
							break;
						case 4:
							letraCif="D";
							break;
						case 5:
							letraCif="E";
							break;
						case 6:
							letraCif="F";
							break;
						case 7:
							letraCif="G";
							break;
						case 8:
							letraCif="H";
							break;
						case 9:
							letraCif="I";
							break;												
						case 10:
							letraCif="J";
							break;
							
					}				
					if (control.toUpperCase()  == letraCif)
					{					
						return true
					}
					else
					{					
						return false					
					}
				}																
			}
			else
			{
				return false
			}
						
		}
    }
}

