/* ************************************
   Data Validation
   ************************************
*/  
//----------------------------------------- VALIDALONGITUD ------------------------------------------------------------
	  function longitud(stobj, li_lng) {
	    st_aux = stobj.value;
		if (st_aux.length > li_lng) {
		  stobj.value = st_aux.substring(0, li_lng);  
		}
	  }      
 
//----------------------------------------- VALIDA ------------------------------------------------------------     
            // valida( tipo,     objeto, etiqueta,   requerido, espacios,  es_llave,  con_hora,   longitud,  rango_inferior, rango_superior) 
      function valida( st_tp, stobj, st_etiq, bo_req, bo_esp, bo_key, bo_hora, li_lng, li_rinf,     li_rsup) { 
        var bo_valida = true;
        var bo_entero = bo_hora;
        switch (st_tp) {
          // Si el campo es del tipo texto 
          case 'tx' :
            var st_aux = stobj.value; 
            //Verifica si el valor no es nulo, solo si es requerido.
            if (bo_req && st_aux == ""){
              bo_valida = false; 
              st_msg = "Ingresa un valor en "  + st_etiq;
            }
            //Verifica si el valor no son solo espacios, solo si es requerido.
            if (bo_valida && bo_req && st_aux.indexOf(" ")!=-1){
              st_esp= st_aux;
              do {
                st_esp = st_esp.replace(" ","");      
              }  while (st_esp.length > 0 && st_esp.indexOf(" ")!=-1)
              if (st_esp == ""){
                bo_valida = false; 
                st_msg = "Ingresa un valor diferente de solo espacios en "  + st_etiq;
              }  
            }
            //Verifica si el valor tiene espacios, solo si no debe permitirlos.
            if (bo_valida && dt_aux != "" && bo_esp && st_aux.indexOf(" ")!=-1){
              bo_valida = false; 
              st_msg = "Elimina los espacios de "  + st_etiq;
            }
            //Verifica si el valor es de la longitud requerida, solo si es necesario.
            if (bo_valida && dt_aux != "" && bo_key && st_aux.length != li_lng){
              bo_valida = false; 
              st_msg = "Completa el valor de "  + st_etiq;
            }
            //Verifica si el valor contiene carácteres inválidos.
            if (bo_valida && dt_aux != "" && (st_aux.indexOf("&")!=-1 || st_aux.indexOf("'")!=-1 ) ) {
              bo_valida = false; 
              st_msg = "Elimina los caracteres especiales (&,') de "  + st_etiq;
            }
          break;

          // Si el campo es del tipo texto 
          case 'pw' :
            var st_aux = stobj.value; 
            //Verifica si el valor no es nulo, solo si es requerido.
            if (bo_req && st_aux == ""){
              bo_valida = false; 
              st_msg = "Ingresa un valor en "  + st_etiq;
            }
            //Verifica si el valor tiene espacios, solo si no debe permitirlos.
            if (bo_valida && dt_aux != "" && bo_esp && st_aux.indexOf(" ")!=-1){
              bo_valida = false; 
              st_msg = "Elimina los espacios de "  + st_etiq;
            }
            //Verifica si el valor es de la longitud requerida, solo si es necesario.
            if (bo_valida && dt_aux != "" && bo_key && st_aux.length != li_lng){
              bo_valida = false; 
              st_msg = "Completa el valor de "  + st_etiq;
            }
            //Verifica si el valor contiene carácteres inválidos.
            //if (bo_valida && dt_aux != "" && (st_aux.indexOf("&")!=-1 || st_aux.indexOf("'")!=-1 || st_aux.indexOf("0")!=-1 || st_aux.indexOf("1")!=-1 || st_aux.indexOf("2")!=-1 || st_aux.indexOf("3")!=-1 || st_aux.indexOf("4")!=-1 || st_aux.indexOf("5")!=-1 || st_aux.indexOf("6")!=-1 || st_aux.indexOf("7")!=-1 || st_aux.indexOf("8")!=-1 || st_aux.indexOf("9")!=-1 ) ) {
            if (bo_valida && dt_aux != "" && (st_aux.indexOf("&")!=-1 || st_aux.indexOf("'")!=-1)) {
              bo_valida = false; 
              //st_msg = "Elimina los caracteres especiales (&,') y números de "  + st_etiq;
              st_msg = "Elimina los caracteres especiales (&,',-) de "  + st_etiq;
            }
          break;

          //Si el campo es del tipo numérico
          case 'nu' :
            var li_aux = stobj.value;
            //Verifica si el valor no es nulo, solo si es requerido.
            if (bo_req && li_aux == "") {
              bo_valida = false; 
              st_msg = "Ingresa un valor en "  + st_etiq;
            }
            //Verifica que no sea decimal, solo si es entero.
            if (bo_valida && bo_entero && li_aux.indexOf(".")  != -1) {
              bo_valida = false; 
              st_msg = "Ingresa un valor entero en "  + st_etiq;
            }
            //Verifica si el valor es un numérico.
            if (bo_valida && isNaN(li_aux)){
              bo_valida = false; 
              st_msg = "Ingresa un número en "  + st_etiq;
            }
            //Verifica si el valor es mayor al rango inferior.
            if (bo_valida && li_aux < li_rinf) {
              bo_valida = false;
              st_msg = "Ingresa un número mayor a " + li_rinf + " en " + st_etiq;
            }  
            //Verifica si el valor es menor al rango superior.
            if (bo_valida && li_aux > li_rsup){
              bo_valida = false; 
              st_msg = "Ingresa un número menor a " + li_rsup + " en " + st_etiq;
            }
          break;

          // Si el campo es del tipo fecha
          case 'dt' :
            var dt_aux = stobj.value;
            //Verifica si el valor no es nulo, solo si es requerido.
            if (bo_req && dt_aux.length==0){
              bo_valida = false;
              st_msg = "Ingresa un valor en "  + st_etiq;
            } 
            //Verifica que el valor sea de la longitud requerida y este en el formato dd/mm/aaaa.
            if (bo_valida && dt_aux != "" && !bo_hora && (dt_aux.length != li_lng || dt_aux.substring(2,3) != "/" || dt_aux.substring(5,6) != "/")){
              bo_valida = false;
              st_msg = "Ingresa una fecha válida con el formato  \n 'dd/mm/aaaa' en "  + st_etiq;
            }
            
            //Verifica que el valor sea de la longitud requerida y este en el formato dd/mm/aaaa hh:mm.
            if (bo_valida && dt_aux != "" && bo_hora && (dt_aux.length != li_lng || dt_aux.substring(2,3) != "/" || dt_aux.substring(5,6) != "/" ||
                dt_aux.substring(10,11) != " " || dt_aux.substring(13,14) != ":")){
              bo_valida = false;
              st_msg = "Ingresa una fecha válida con el formato  \n 'dd/mm/aaaa hh:mm' en "  + st_etiq;
            }
            //Descompone la fecha para obtener el dia, mes, año y horas, minutos solo si contiene.
            //Verifica si el valor de día capturado es un numérico.
            if (bo_valida && dt_aux != "" && isNaN(dt_aux.substring(0,2))){
              bo_valida = false; 
              st_msg = "Ingresa un valor númerico para día con el formato  \n 'dd/mm/aaaa' en "  + st_etiq;
            }  
            else {  
              var li_dia = parseInt(dt_aux.substring(0,2),10);
            }  
            //Verifica si el valor de mes capturado es un numérico.
            if (bo_valida && dt_aux != "" && isNaN(dt_aux.substring(3,5))){
              bo_valida = false; 
              st_msg = "Ingresa un valor númerico para mes con el formato  \n 'dd/mm/aaaa' en "  + st_etiq;
            }  
            else {  
              var li_mes = parseInt(dt_aux.substring(3,5),10);
            }  
            //Verifica si el valor del año es un numérico.
            if (bo_valida && dt_aux != "" && isNaN(dt_aux.substring(6,10))){
              bo_valida = false; 
              st_msg = "Ingresa un valor númerico para año con el formato  \n 'dd/mm/aaaa' en " + st_etiq;
            }  
            else {  
              var li_anio = parseInt(dt_aux.substring(6,10),10);
            }            
            //Verifica si el valor de las horas capturadas es un numérico.
            if (bo_valida && dt_aux != "" && bo_hora && isNaN(dt_aux.substring(11,13))){
              bo_valida = false; 
              st_msg = "Ingresa un valor númerico para las horas con el formato  \n 'dd/mm/aaaa hh:mm' en " + st_etiq;
            }  
            else {  
              var li_hra = parseInt(dt_aux.substring(11,13),10);
            }
            //Verifica si el valor de los minutos capturados es un numérico.
            if (bo_valida && dt_aux != "" && bo_hora && isNaN(dt_aux.substring(14,16))){
              bo_valida = false; 
              st_msg = "Ingresa un valor númerico para los minutos con el formato  \n 'dd/mm/aaaa hh:mm' en " + st_etiq;
            }  
            else {  
              var li_min = parseInt(dt_aux.substring(14,16),10);
            }            
            //Verifica que el año capturado sea valido, es decir que sea mayor a 1900.
            if ( bo_valida && li_anio < 1900 ){
              bo_valida = false;
              st_msg = "Ingresa un valor de año válido con el formato \n 'dd/mm/aaaa' en " + st_etiq;
            }
            //Verifica que el mes capturado sea válido, es decir este entre 1 y 12.
            if ( bo_valida &&  (li_mes > 12 || li_mes < 1) ){
              bo_valida = false;
              st_msg = "Ingresa un valor de mes válido con el formato \n 'dd/mm/aaaa' en " + st_etiq;
            }
            //Obtiene el número de días por mes, de acuerdo al mes capturado.
            if (bo_valida && li_mes == 2 && (li_anio % 4)==0 ){ 
              var li_diasxmes = "312931303130313130313031";
              var li_dias = li_diasxmes.substring((li_mes-1)* 2, (li_mes-1)*2+2); 
            }   
            else {  
              var li_diasxmes = "312831303130313130313031";
              var li_dias = li_diasxmes.substring((li_mes-1)* 2, (li_mes-1)*2+2); 
            }  
            //Verifica que el día capturado sea válido, es decir este entre 1 y el número de días por mes.       
            if (bo_valida && (li_dia < 1 || li_dia > li_dias)){
              bo_valida = false;
              st_msg = "Ingresa un valor de día válido para el mes capturado  \n con el formato 'dd/mm/aaaa' en " + st_etiq;
            }
            //Verifica que las horas capturadas sean validas, es decir este entre 0 y 23.
            if ( bo_valida && bo_hora && (li_hra < 0 || li_hra > 23) ){
              bo_valida = false;
              st_msg = "Ingresa un valor de horas válido con el formato \n 'dd/mm/aaaa hh:mm' en " + st_etiq;
            }            
            //Verifica que los minutos capturados sean válidos, es decir este entre 0 y 59.
            if ( bo_valida && bo_hora && (li_min < 0 || li_min > 59) ){
              bo_valida = false;
              st_msg = "Ingresa un valor de minutos válido con el formato \n 'dd/mm/aaaa hh:mm' en " + st_etiq;
            }             
          break;            
        }
        if (!bo_valida ) {
          //alert(st_msg + ".\n\nPresiona el botón para continuar.");
          alert(st_msg + ".\n\nPresiona el botón para continuar.");

          //window.event.returnValue = false;
          //stobj.focus();          
        } 
        return bo_valida;
      }
      
//----------------------------------------- OBTENFECHA ------------------------------------------------------------        
      function obtenFechaHoy(bo_time) {
        dt_act = new Date();
        li_dia = dt_act.getDate() ;
        if ( li_dia < 10) {
          st_fecha = "0" + li_dia + "/"; 
        }
        else {
          st_fecha = ""  + li_dia + "/"; 
        } 
        li_mes = dt_act.getMonth() + 1 ;
        if ( li_mes < 10) {
          st_fecha = st_fecha + "0" + li_mes + "/"; 
        }
        else {
          st_fecha = st_fecha + li_mes + "/"; 
        } 
        st_fecha = st_fecha + dt_act.getYear(); 
        if (bo_time) {
          li_hora = dt_act.getHours();
          if ( li_hora < 10) {
            st_fecha = st_fecha + " 0" + li_hora + ":"; 
          }
          else {
            st_fecha = st_fecha + " "  + li_hora + ":"; 
          } 
          li_min = dt_act.getMinutes();
          if ( li_min < 10) {
            st_fecha = st_fecha + "0" + li_min; 
          }
          else {
            st_fecha = st_fecha + ""  + li_min; 
          } 
        }
        return(st_fecha);
      }
  
      function obtenEnteroFecha(dt_aux,bo_time) {
        if (bo_time) {
          st_fecha  = dt_aux.substring(6,10) + dt_aux.substring(3,5) + dt_aux.substring(0,2) + dt_aux.substring(11,13) + dt_aux.substring(14,16)
        }
        else {
          st_fecha  = dt_aux.substring(6,10) + dt_aux.substring(3,5) + dt_aux.substring(0,2)
        }  
        return(parseInt(st_fecha));
      }   
      
//----------------------------------------- COMPARARFECHA ------------------------------------------------------------  
      function compararFecha(dt_fecha1, st_operador, dt_fecha2, bo_time) {
        switch (st_operador) {
          case "==" :
            if (obtenEnteroFecha(dt_fecha1,bo_time) == obtenEnteroFecha(dt_fecha2,bo_time)) { return true; }
            else { return false; }
          case "<" :
            if (obtenEnteroFecha(dt_fecha1,bo_time) <  obtenEnteroFecha(dt_fecha2,bo_time)) { return true; }
            else { return false; }
          case "<=" :
            if (obtenEnteroFecha(dt_fecha1,bo_time) <= obtenEnteroFecha(dt_fecha2,bo_time)) { return true; }
            else { return false; }         
          case ">" :
            if (obtenEnteroFecha(dt_fecha1,bo_time) >  obtenEnteroFecha(dt_fecha2,bo_time)) { return true; }
            else { return false; }         
          case ">=" :
            if (obtenEnteroFecha(dt_fecha1,bo_time) >= obtenEnteroFecha(dt_fecha2,bo_time)) { return true; }
            else { return false; }
          case "mes" :
            var anio2= dt_fecha2.substring(6,10);
            var anio1= dt_fecha1.substring(6,10);
            var mes2= dt_fecha2.substring(3,5);
            var mes1= dt_fecha1.substring(3,5);

            if ((parseInt(mes1)==12 && parseInt(mes2)==1) && (parseInt(anio1)< parseInt(anio2)))
            {
                //alert("fin de año");
                return false;
            }
			else
			{
				if (obtenEnteroFecha(dt_fecha2,bo_time) - obtenEnteroFecha(dt_fecha1,bo_time) > 99)
				{ 
				  //alert(obtenEnteroFecha(dt_fecha2,bo_time));
				  //alert(obtenEnteroFecha(dt_fecha1,bo_time));
				  //alert(obtenEnteroFecha(dt_fecha2,bo_time) - obtenEnteroFecha(dt_fecha1,bo_time));
				  return true; 
				}
				else { return false; }                    
			}	
        } 
      }
      
//----------------------------------------- CUENTACHAR ------------------------------------------------------------
	  function cuentaChar(st_campo, st_campodecuenta, li_limitemax) {
		if (st_campo.value.length > li_limitemax)
		    st_campo.value = st_campo.value.substring(0, li_limitemax);
		else 
		    st_campodecuenta.value = li_limitemax - st_campo.value.length;
	  }      
	  
	  
function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	var tmpNumStr2 = new String(tmpNum);	
	var letra='';
	var decimal1='';
	var decimal2='';
	var sindecimal='false';
	for (var m=0;m<tmpNumStr2.length;m++)
	{
      letra=tmpNumStr2.substring(m,m+1);
      if (letra=='.')
      {
        decimal1=tmpNumStr2.substring(m+1,m+2);
        decimal2=tmpNumStr2.substring(m+2,m+3);
        entero=tmpNumStr2.substring(0,m);
        break;
      }
      else
      {
        decimal1='';
        decimal2='';
        entero=tmpNumStr2;
      } 
	}

    if (decimal1=='')
       tmpNumStr2= entero + ".00";
    else
    {
      if (decimal1!='' && decimal2=='')
        tmpNumStr2= entero + "."  + decimal1 + "0";        
    }   

	// Create a string object to do our formatting on
	//var tmpNumStr = new String(tmpNum);
	var tmpNumStr = new String(tmpNumStr2);	

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}
	  


/**********************************************************************
	IN:
		emailStr - the string to check
	RETVAL:
		alert
 **********************************************************************/

function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

alert("El E-mail no es válido");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
//alert("Ths username contains invalid characters.");
alert("El E-mail no es válido (el nombre contiene caracteres inválidos)");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
//alert("Ths domain name contains invalid characters.");
alert("El E-mail no es válido (el dominio contiene caracteres inválidos)");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

//alert("The username doesn't seem to be valid.");
alert("El E-mail no es válido (nombre)");
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
//alert("Destination IP address is invalid!");
alert("El E-mail no es válido (IP)");
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
//alert("The domain name does not seem to be valid.");
alert("El E-mail no es válido (dominio)");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
//alert("The address must end in a well-known domain or two letter " + "country.");
alert("El E-mail no es válido (terminación)");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
//alert("This address is missing a hostname!");
alert("El E-mail no es válido (no hay dominio)");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

//  End -->

