// Funcion que valida field segun el formato indicado por indice.
// Busca caracteres no validos con el formato indicado.
function isInString(field,indice) {
	exp= new Array();
	exp[0]= /[^0-9a-zA-Z]/				//Numeros, letras mayusculas y minusculas
	exp[1]= /[^0-9a-z]/				//Numeros y letras minusculas
	exp[2]= /[\D]/					//Numeros
 	exp[3]= /[^\w,;.:ªº@#$%&áéíóúÁÉÍÓÚ \/\-\_ñÑ]/	//Numeros, letras mayusculas y minusculas y otros caracteres
	exp[4]= /[^\w\_]/				//Numeros, letras mayusculas y minusculas y _
	exp[5]= /[^0-9a-z\_]/				//Numeros, letras minusculas y _
	exp[6]= /[^\d\_]/				//Numeros y _

	return !(exp[indice].test(field));		//false si no coincide con el formato
}

/**********
Checks if an email is correct
Input: Mail to validate
Output : True if email is correct. False otherwise.
******** */
function isMail(sMail) {

	var invalid = /(\.\.)|(@\.)|(\.@)|(^\.)|(á)|(é)|(í)|(ó)|(ú)/ // invalid characters
	var valid = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/; // valid characters
	var end = /\.[a-zA-Z]{2,4}$/; // end of email
	var vMail = sMail.split(";");
	var i, sMailAux;

	for (i=0;i<vMail.length;i++){
		sMailAux = vMail[i].replace(/[\s]+/g,"");
		var Pos    = sMailAux.indexOf('@')
		var Period   = sMailAux.lastIndexOf('.')
		var Space    = sMailAux.indexOf(' ')
		var Length   = sMailAux.length - 1   // Array is from 0 to length-1

		if ((Pos < 2) ||				// Must be atleast 2 characters before @ sign
			(Period <= Pos+1) ||        // Must be atleast one valid char btwn '@' and '.'
			(Period == Length ) ||      // Must be atleast one valid char after '.'
			(Space  != -1) ||           // No empty spaces permitted
			(invalid.test(sMailAux)) ||	// Mustn't contain invalid characters
			(!valid.test(sMailAux)) ||		// Must contain valid characters
			(sMailAux.search(end) == -1))  // Check email's end
		{  
		      return false;
		}
 		return true;
 	};
  }

function isMail2 (_email) {
   if (/\.[\wñÑ\-\_]+/.test(_email))
   {
   	re = /^[\wñÑ\-\_]{1,}@[\wñÑ\-\_]{1,}\.[\wñÑ\-\_]{1,}\.[\wñÑ\-\_]{2,3}$/
   }
   else
   {
	re = /^[\wñÑ\-\_]{1,}@[\wñÑ\-\_]{1,}\.[\wñÑ\-\_]{2,3}$/
   }

 return (re.test(_email))?true:false
}

// Checks if a character is numeric.
function isDigit(caracter) {
   return isInString(caracter,2)
}

// Checks is a string is numeric.
function isNumeric(cadena) {
   return isInString(cadena,2)
}

// Checks if a string is empty
function isEmpty(lstrcadena) {
   return (lstrcadena.length != 0)?false:true
}

// Creates an array
function makeArray (n) {
        this.length = n;
        for (var j = 1; j <= n; j++){
                this[j] = 0;
        }
        return this
}

//----------------------------------------------------------------------------
//	Function formatNIF
//	Input: NIF Field
//	OutPut:	True if correct, False otherwise
//----------------------------------------------------------------------------

function formatNIF(field) {
var nceros;
var ceros='';

	if (field.value.length >9)
		return false;
	nceros= parseInt(9 - field.value.length);
	
	field.value=field.value.toUpperCase();
	
	for (i=0;i<nceros;i++) {
		ceros+='0'; }
		
	if (isNaN(parseInt(field.value.charAt(0))))
		field.value = field.value.charAt(0) + ceros + field.value.substring(1,field.value.length)
    else
		field.value = ceros + field.value
		
	return (field.value.length != 9)?false:true;
}

//----------------------------------------------------------------------------
// Comprueba la letra que corresponde al dni correspondiente
//----------------------------------------------------------------------------
function NIFLetter(nif1)
{
   var cadena  = "";
   var letras='TRWAGMYFPDXBNJZSQVHLCKET'
   var NumDNI=0;
   var Indice=0;
   var divis = 0
   
   nif1 = nif1.toUpperCase();
   
   if( nif1.charAt(0) != 'X')	// Españoles
      cadena += nif1
   else 			// Extranjeros
      cadena += nif1.substring(1,11);
   
   
   correcto = cadena.charAt(cadena.length-1);
   correcto = correcto.toUpperCase();
   
   NumDNI = parseInt(cadena,10);
   
   divis = isNaN(parseInt(NumDNI/23,10))?0:parseInt(NumDNI/23,10);

   Indice = NumDNI - (23 * divis);
   
   if( (Indice >= 0) && (Indice < 24) ) {
      if( letras.charAt(Indice) == correcto) 
         return true
      else
         return false
   } 
   else
      return false;
}

//------------------------------------------------------------
// Retorna la letra correspondiente a un dni de una persona 
// juridica u organismo                  
//------------------------------------------------------------

function ValidateCIF(cif1)
{
   var Retorno = true;
   var Entidad;
   var StEntidad;
   var Provincia;
   var NumeroSec;
   var CaracterControl, CaracterControlEntrada;
   var TablaControl = 'JABCDEFGHI';
   var otras = 'ABCDEFGHSPQX';
   var numero = '0123456789';
   var Suma = 0;
   var Suma1 = 0;
   var Suma2 = 0;
   var nAux = 0;
   var tmp = '';
   tmp = "" + cif1;
   Entidad = tmp.charAt(0);
   Entidad = Entidad.toUpperCase();
   if( otras.indexOf( Entidad) == -1) {
      return false;
   }
   Provincia = tmp.substring(1,3);
   NumeroSec = tmp.substring(3,8);
   NumeroSec2 = tmp.substring(1,8);
   CaracterControlEntrada = tmp.substring( 8);
   CaracterControlEntrada = CaracterControlEntrada.toUpperCase();
   if( (Entidad >= "A") && (Entidad <= "H") ) {
         StEntidad = "JURIDICA";
   }
   else if( (Entidad == "S") || (Entidad == "Q") ) {
      StEntidad="ORGANISMO";
   }
   else if( Entidad == "X") //  Extranjero residente
   {
      return NIFLetter( tmp);
   }
   if( Retorno != false) {           // Entidad correcta
      for (var i = 0; i < NumeroSec2.length; i++) {
         if( numero.indexOf( NumeroSec2.charAt( i)) == -1) {
            return false;
         }
      }
      if( parseInt( NumeroSec, 10) == 0)
      {
         Retorno = false;
      }
      else if( (StEntidad == "JURIDICA") || (StEntidad == "ORGANISMO"))
      {
         Suma2 = 0;
         Suma1 = parseInt( NumeroSec2.charAt( 1), 10) + parseInt( NumeroSec2.charAt( 3), 10) + parseInt( NumeroSec2.charAt( 5), 10 );
         for( var i = 0; i < 7; i += 2) {
            nAux = parseInt( NumeroSec2.charAt( i), 10) * 2;
            if (nAux > 9) {
               Suma2 = Suma2 + parseInt( nAux / 10, 10) + nAux % 10;
            } else {
               Suma2 = Suma2 + nAux;
            }
         }
         Suma = Suma1 + Suma2;
         i = 10 - Suma % 10;
         if( i > 9) { 
            i = 0;
         };
         if( StEntidad == "JURIDICA") {
            CaracterControl = i;
         } else {
            CaracterControl = TablaControl.charAt( i);
         }
         if (CaracterControl != CaracterControlEntrada) {
            	CaracterControl = TablaControl.charAt( i);
         	if (CaracterControl != CaracterControlEntrada) 
  	     	 	  Retorno = false;                         
         };
      }
   }

   return Retorno;
}

//-----------------------------------------------------------
// Indica el tipo de CIF NIF pasado 
//-----------------------------------------------------------
// Returns:     0: No es ni NIF ni CIF
//		1: Es NIF
//		2: Es CIF
//		3: Es Tarjeta de residencia para extranjeros
//
function checkFiscalID(field) {

   var numero;
   var result;
   var no_zeros;
   var i;

   numero = '0123456789';
   result = 0;
  // Se descartan los ceros de la izquierda
  for( i = 0; i < field.value.length; i++)
    if( field.value.charAt(i) != "0")
     break;
  no_zeros = field.value.substring(i);

  if( numero.indexOf( no_zeros.charAt(0)) != -1) 
  {
      // Entra aquí cuando el primer caracter es un número
      if (NIFLetter(no_zeros)) result=1;
  } 
  else {
  	if (no_zeros.charAt(0) == "X"){
		no_zeros2 = no_zeros.substring(1);
	 	if (NIFLetter(no_zeros2)) result=3;
        }
	else  if (ValidateCIF( no_zeros)) result=2;
  };
  return(result);
}

//Añade ceros por la izquierda 
function putZeros (field, tam) {
	var aux = "";
	for (var i=field.length; i < tam; i++)
		aux += '0';

	aux += field;
	return aux;
}

// Estas funciones sirven para deshabilitar una select, 
// valen tanto para IE como Netscape
function skip () { this.blur(); }
function disableSelect (select, mydocument, enable) {
  if (!enable) {
    select.disabled = true;
    if (!mydocument.all && !mydocument.getElementById) {
      select.oldOnFocus = 
        select.onfocus ? select.onfocus : null;
      select.onfocus = skip;
    }
  }
  else {
    select.disabled = false;
    if (!mydocument.all && !mydocument.getElementById) {
      select.onfocus = select.oldOnFocus;
    }
  }
}

/**
	Devuelve true si el valor es un numero y false si no lo es
*/

function checknumber(pValue){

var anum=/(^\S(\d+$))|(^\S(\d+\.\d+$))/
if (anum.test(pValue))
testresult=true
else{
testresult=false
}
return (testresult)
}

// Quita los blancos iniciales y finales de un string
function QuitarBlancos(Cadena) {

   var iIni;
   var iLen;
   var iPos=0;

   // Quitar los blancos iniciales
   while ((iPos <= Cadena.length-1) && (Cadena.charAt(iPos) == ' '))
      iPos++;

   // Si la posición inicial es menor que la longitud (hay algún carácter no blanco)
   if (iPos <= Cadena.length - 1)   {
      // Tenemos la posición inicial
      iIni = iPos;
      // Quitar los blancos finales
      iPos = Cadena.length - 1;
      while ((iPos > iIni) && (Cadena.charAt(iPos) == ' ')){
         iPos--;
      }
      return Cadena.substring(iIni, iPos + 1);
   }
   else
      // Todos los caracteres son blancos
      return "";
}	

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s)
{   
    var i;
    var whitespace = " \t\n\r";
	

    // Is s empty?
    if (isEmpty(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;
}

// Function that checks if a bank number is correct
function checkCuenta(entidad,oficina,dc,ncuenta) {
	
      var control1 = "00"+entidad.value+oficina.value;
      var control2 = ncuenta.value;
      var digito1 = 0;
      var digito2 = 0;
      var vdc = "";
      var comprobacion = "";
      var multp= new Array(1,2,4,8,5,10,9,7,3,6);
      
      comprobacion = entidad.value+oficina.value+dc.value+ncuenta.value;

      if(comprobacion == "00000000000000000000") 
        return false;

      if( (entidad.value.length != 4) || (oficina.value.length != 4) || (dc.value.length != 2) || (ncuenta.value.length != 10) )
        return false;

      for (var i=0;i<10;i++) {
		digito1 += parseInt (control1.charAt(i),10) * parseInt(multp[i]);
      		digito2 += parseInt (control2.charAt(i),10) * parseInt(multp[i]);
      }

      digito1 = 11 - ( digito1 % 11 );
      digito2 = 11 - ( digito2 % 11 );

      if (digito1 == 11) digito1 = 0;
      if (digito1 == 10) digito1 = 1;
      
      if (digito2 == 11) digito2 = 0;
      if (digito2 == 10) digito2 = 1;
      
      vdc = "" + digito1 + digito2;

      return (vdc == dc.value)?true:false
      return false;
}

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);
    
  if (st.length < 12)    
    return (false);
	

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);
}

function isFecha(objName) 
{
//var strDatestyle = "US"; //Estilo de Fecha de Estados Unidos
var strDatestyle = "EU";  //Estilo de fecha Europeo
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Ene";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Abr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Ago";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dic";
strDate = datefield.value;

if (strDate.length < 1) {
	return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
	if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
		strDateArray = strDate.split(strSeparatorArray[intElementNr]);
		if (strDateArray.length != 3) {
			err = 1;
			return false;
		}
		else {
			strDay = strDateArray[0];
			strMonth = strDateArray[1];
			strYear = strDateArray[2];
		}
		booFound = true;
   	}
}
if (booFound == false) {
	if (strDate.length>5) {
		strDay = strDate.substr(0, 2);
		strMonth = strDate.substr(2, 2);
		strYear = strDate.substr(4);
   	}
}
if (strYear != null && strYear.length == 2) {
	intYear = parseInt(strYear, 10);
	if (intYear < 51)
		strYear = '20' + strYear;
	else
		strYear = '19' + strYear;
}
// US style
if (strDatestyle == "US") {
	strTemp = strDay;
	strDay = strMonth;
	strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
	err = 2;
	return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
	for (i = 0;i<12;i++) {
		if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
			intMonth = i+1;
			strMonth = strMonthArray[i];
			i = 12;
   		}
	}
	if (isNaN(intMonth)) {
		err = 3;
		return false;
   	}
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
	err = 4;
	return false;
}
if (intMonth>12 || intMonth<1) {
	err = 5;
	return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
	err = 6;
	return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
	err = 7;
	return false;
}
if (intMonth == 2) {
	if (intday < 1) {
		err = 8;
		return false;
	}
if (SaltaAnio(intYear) == true) {
	if (intday > 29) {
		err = 9;
		return false;
	}
}
else {
	if (intday > 28) {
		err = 10;
		return false;
	}
}
}
if (strDatestyle == "US") {
	datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
	//datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
	datefield.value = intday + "-" + intMonth + "-" + strYear;
}
return true;
}

function SaltaAnio(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	}
	else {
		if ((intYear % 4) == 0) { return true; }
	}
	return false;
}

//*************************************************************
//* Validar una fecha con formato (DD/MM/AAAA)
//*************************************************************
function bFechaValida(Fecha)
{
   var sDiaAux;
   var sMesAux;
   var sDia;
   var sMes;
   var sAnno;
   var iIniMes;
   var iFinMes;
   var iIniAnio;
   var iFinAnio;
   var iLongitud;
   var iPos;
   var iCar;
   
   // Si la fecha no se ha completado
   if (Fecha.length == 0)
      return(true); 

  // Inicializar variables

   iIniMes = 3;       // El mes comenzará en carácter 3
   iFinMes = 5;       // El mes finaliza antes del carácter 5
   iLongitud = 10;    // La longitud de la fecha será de 10 caracteres


   // Comprobar que todos los caracteres sean numéricos o "/"
   for (iPos = 0; iPos <= Fecha.length-1; iPos++)
   {
      iCar = Fecha.charAt(iPos);
      if ((iCar < "0" || iCar > "9") && (iCar !="/")) 
         return false;	
   }

   // Obtener el día
   sDiaAux = Fecha.substring (0,2);

   // El primer carácter del día no puede ser "/"
   if (sDiaAux.charAt(0) == "/")
      return false;

   // Si el segundo carácter del día es "/"
   if (sDiaAux.charAt(1) == "/")
   {
      // El día es menor de 10 y se le añade "0"
      sDia = "0" + sDiaAux.charAt(0);
      iIniMes = iIniMes - 1;
      iFinMes = iFinMes - 1;
      iLongitud = iLongitud - 1;
   }
   else
   {
      // El día es de dos caracteres

      // Si el tercer caracter no es "/"
      if (Fecha.charAt(2) != "/")
         return (false);

      sDia = sDiaAux;
   }

   // Si el día no es correcto
   if (sDia < "01" || sDia > "31")
      return (false);


   // Inicializar las posiciones de inicio y fin del año
   iIniAnio = iIniMes + 3;
   iFinAnio = iFinMes + 5;

   // Obtener el mes
   sMesAux = Fecha.substring (iIniMes,iFinMes);

   // El primer carácter del mes no puede ser "/"
   if (sMesAux.charAt(0) == "/")
      return false;

   // Si el segundo carácter del mes es "/"
   if (sMesAux.charAt(1) == "/")
   {
      // El mes es menor de 10 y se le añade "0"
      sMes = "0" + sMesAux.charAt(0);
      iIniAnio = iIniAnio - 1;
      iFinAnio = iFinAnio - 1;
      iLongitud = iLongitud - 1;
   }
   else
   {
      // El mes es de dos caracteres
      sMes = sMesAux;
   }

   // Si el mes no es correcto
   if (sMes < "01" || sMes > "12")
      return (false);

   // Si la fecha no se ha completado
   if (Fecha.length > iLongitud)
      return(false);

   // Obtener el año
   sAnno = Fecha.substring (iIniAnio,iFinAnio);

   // Ningún carácter del año puede ser "/"
   if ((sAnno.charAt(0) == "/") || (sAnno.charAt(1) == "/") || (sAnno.charAt(2) == "/") || (sAnno.charAt(3) == "/"))
      return false;

   // Si el año no es de 4 dígitos
   if (sAnno.length < 4)
	 return (false);

   // Validar si es un mes de 30 días
   if (((sMes == "04") || (sMes == "06") || (sMes == "09") || (sMes == "11")) && (sDia > "30"))
   {
      return (false);
   }
   else
   {
      // Si es febrero
      if ((sMes == "02"))
      {
         // El día no puede ser mayor que 29
         if (sDia > "29")
         {
            return (false);
         }
         else
         {
            // Si el día es 29
            if (sDia == "29")
            {
               // Debe ser un año bisiesto
               // Son bisiestos los divibles entre 4 pero no entre 100, pero sí entre 400

               resto = sAnno % 4;
               if (resto != 0)
               {
                  return (false);
               }
               else
               {
                  resto = sAnno % 100;
                  if (resto == 0)
                  {
                     resto = sAnno % 400;
                     if (resto != 0)
                     {
                        return (false);
                     }
                  }
               }
            }
         }
      } 
   }


   if (sAnno < "1900" | sAnno > "2078")

   {
    return (false);

   } 
   // La fecha es correcta
   return (sDia+"/"+sMes+"/"+sAnno);
}


//*************************************************************
//* Reemplaza el caracter ' por el `
//*************************************************************
function sReemplazaComillas(cadena)
{
  var iPos;
  var sal = "";
  var car;

  for (iPos = 0; iPos <= cadena.length-1; iPos++)
   {
      car = cadena.charAt(iPos);
      if (car == "'")
	sal += car.replace("'","`");
      else
	sal += car;
   }
   return sal;
}

//*******************************************************************
//customSplit
//Split the argument string into an array of strings.
//Syntax
//customSplit(strValue, separator, strArrayName)
//strValue is the string to be splited with separator as the delimeter. 
//After spliting, array of strings are stored in new "Array" object, strArrayName. 
//*******************************************************************

function customSplit(strvalue, separator, arrayName) {
  var n = 0;

  if (separator.length != 0) {
    while (strvalue.indexOf(separator) != -1) {
      eval("arr"+n+" = strvalue.substring(0, strvalue.indexOf(separator));");
      strvalue = strvalue.substring(strvalue.indexOf(separator)+separator.length,
          strvalue.length+1);
      n++;
    }
    eval("arr" + n + " = strvalue;");
    arraySize = n+1;
  }
  else {
    for (var x = 0; x < strvalue.length; x++) {
      eval("arr"+n+" = \"" + strvalue.substring(x, x+1) + "\";");
      n++;
    }
    arraySize = n;
  }

  eval(arrayName + " = new makeArray(arraySize);");

  for (var i = 0; i < arraySize; i++)
    eval(arrayName + "[" + i + "] = arr" + i + ";");

  return arraySize;
}

// BrowserCheck Object
function BrowserCheck() {
	var b = navigator.appName
	if (b=="Netscape") this.b = "ns"
	else if (b=="Microsoft Internet Explorer") this.b = "ie"
	else this.b = b
	this.version = navigator.appVersion
	this.v = parseInt(this.version)
	this.ns = (this.b=="ns" && this.v>=4)
	this.ns4 = (this.b=="ns" && this.v==4)
	this.ns5 = (this.b=="ns" && this.v==5)
	this.ie = (this.b=="ie" && this.v>=4)
	this.ie4 = (this.version.indexOf('MSIE 4')>0)
	this.ie5 = (this.version.indexOf('MSIE 5')>0)
	this.min = (this.ns||this.ie)
}
is = new BrowserCheck()

function VerificarImprimir(){
  if (is.ie4) 
   {alert("Debido a la versión de su navegador deberá imprimir a través del botón 'imprimir' de su navegador");}
  else
   {window.print();}
}

function textClear (input) {

	if ( input.value == input.defaultValue ) input.value = "";
	return;	
		 
};
		 
function textRestore (input) {
	
	if ( input.value == "" ) input.value = input.defaultValue;
	return;
			 
};	
