/*------------------------------------------------------------------------
---------------- *Libreria de Funciones JavaScript*-----------------------
------------------------------------------------------------------------*/

/*************************Version 1.2 ***********************************************
- Descripcion: Funcion que revisa si un string contiene un float o un integer valido.
Revisando ademas que se encuentre dentro de los rangos definidos para este campo.
En el caso de que se intente validar un float, la definicion de la longitud de los
enteros y decimales que debe contener el numero se obtiene del numero maximo.

Restricciones:
- Considera como numeros  validos  solo aquellos que continen numeros y un punto.
No aceptando numeros con coma, ni con notacion decimal,ni negativos.

* @<autor>: Hugo Martinez
-parametros:
	* @rangoMax: String que contiene el Valor maximo permitido.
	* @rangoMin: Numero que contiene el Valor minimo permitido.
	* @str: String que contiene un posible numero.
- Retorna: un String
	- VACIO: indica que el string a validar es vacio.
 	- NUMERO_FLOAT: Indica que el string a validar es un float. Esto se arroja cuando 
			 se esta validando si el string es un entero permitido.
 	- NO_ES_NUMERO: Indica que no es numero valido.
 	- FUERA_DE_RANGO_ENTERO: La parte entera del numero no cumpe con los rangos dados.
 	- FUERA_DE_RANGO_DECIMAL: La parte decimal no cumple con los rangos dados.
 	- NUMERO_VALIDO: Cumple el string con las condiciones requeridas.
	- NUMERO_NEGATIVO: Indica que el string a validar es un numero negativo.

 	
# funciones Requeridas:				|  Archivo en que se encuentra
- isEmpty(str) 							- Validadores.js	
- esDigito(string)						- Validadores.js
- parteEntera(cadena)					- EfectosFuncionales.js
- Trim(inString) 						- EfectosFuncionales.js
*/
function ValidarNumero(rangoMax,rangoMin,objeto){
	if(objeto.value == "undefined"){
		str =objeto;
	}else
		str = objeto.value;

	
	if(isEmpty(str))
		return "VACIO";
	//Se eliminan los espacios demas (adornos).		
	str = Trim(str);
	if(objeto.value)
		objeto.value = str;
	
	if (isNaN(Number(str)) || (!esDigito(str) ) ) 
		return "NO_ES_NUMERO";

	if(str.indexOf('-',0) != -1)
		return "NUMERO_NEGATIVO";

	var parteEnteraPermitida = parteEntera(rangoMax);
	var parteEnteraStr = parteEntera(str);
//si la longitud de la parte entera de la definicion del dato es mayor a  15 validar los largos.

	if( ((parteEnteraPermitida.length > 15)? (parteEnteraStr.length > parteEnteraPermitida.length):(parseFloat(parteEnteraStr) > parseFloat(parteEnteraPermitida) ) )|| (parteEnteraStr < rangoMin))
	      return "FUERA_DE_RANGO_ENTERO";
	var parteEnteraPermitidaEsMayor = (parteEnteraPermitida.length > 15)? (parteEnteraStr.length < parteEnteraPermitida.length):(new Number(parteEnteraStr) < new Number(parteEnteraPermitida) );
	 //Si la definicion del dato es un decimal (Float)
	 if(rangoMax.indexOf(".",0) != -1 ) {
		var	numDecPermitido = rangoMax.length -(rangoMax.indexOf(".",0) + 1);
	 	if(str.indexOf(".",0) != -1){
			var decimalesStr = str.length - (str.indexOf(".",0) + 1);
			var punteroStr = str.length - 1; 
			while(str.indexOf(".",0)  < punteroStr){
				if(str.charAt(punteroStr)== '0'){
					decimalesStr--;
					punteroStr--;
					continue;
				}
			break
			}
			if( (parteEnteraPermitidaEsMayor)?(decimalesStr >  numDecPermitido):(parseFloat(str.substring(str.indexOf(".",0),str.length ) ) > parseFloat(rangoMax.substring(rangoMax.indexOf(".",0),rangoMax.length) )))
				return "FUERA_DE_RANGO_DECIMAL";
		}

	 }else{
	 	if(str.indexOf(".",0) != -1)
		  return "NUMERO_FLOAT";
	 
	 }
return "NUMERO_VALIDO";
}


/*************************Version 1.1 ***********************************************
- Descripcion: Valida que el String contiene solo numeros,negativo  y puntos.
* @<autor>: Hugo Martinez
- parametros:
* @str: cadena a validar
- Retorna un booleano:
		true: si el str es considerado digito.
		false: Si el str no es considerado como digito.
*/

function esDigito(str)
{
	 var ch
	 if (str.length == 0)
		 return false;
	 for (var i = 0 ; i < str.length ; i++) {
		 ch = str.charAt(i);
		 if ( (ch < '0' || ch > '9' ) && ch !='.' && ch != '-' )
				return false;
	 }
	 return true;    
}



/*************************Version 1.0 ***********************************************
* Descripcion: Funcion que revisa si un string esta vacio o nulo.

* @<autor>: ASP
- parametros:
	* @str: String validar .
- Retorna: un boolean
	- true: si el string  es vacio o nulo:
	- false: si el string  no es vacio ni nulo.
 	
*/
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}
/*************************Version 1.0 ***********************************************
* Descripcion: Funcion que valida que el campo valor corresponda con el 
rango de valores definidos por el usuario a traves de la caja se seleccion.
* @<autor>: Hugo Martinez
- parametros:
	* @campo: String a  validar .
	* @objSelected: Objeto selected.
- Retorna: un String
	- FUERA_RANGO_PORCENTAJE : si el string no cumple con el rango de porcentaje.
	- FUERA_RANGO_POR_MIL :  si el string no cumple con el rango de mil.
	- FUERA_RANGO_MONTO	: si el string no cumple con el rango de monto.
*/
function ValidarValor(valor,objSelected)
{

       if (objSelected.options[objSelected.selectedIndex].value == "P"){                               
                               if (valor < 0 || valor > 100){
                                       return "FUERA_RANGO_PORCENTAJE";
                                }
         }
//alert("pasa 2 ");
       if (objSelected.options[objSelected.selectedIndex].value == "L"){
                        
//                      alert("valor "+valor);
                                if ((valor < 0) || (valor > 1000)){
                                        return "FUERA_RANGO_POR_MIL";
                                }
           }
                        
           if (objSelected.options[objSelected.selectedIndex].value == "M"){
                               
                                if ((valor < 0) || (valor > 9999.999)){
                                        return "FUERA_RANGO_MONTO" ;                                    
                                }

           }       
        return "RANGO_PERMITIDO"
}

/*************************Version 1.0 ***********************************************
* Descripcion: Funcion que compara dos string que contiene numeros validos.
* @<autor>: Hugo Martinez
- parametros:
	* @ numeroUno: String uno a comparar.
	* @ numeroDos: String dos a comparar.
- Retorna: un numero.
	- 0 : Si el numeroUno es igual al numeroDos.
	- positivo: Si el numeroDos es mayor que el numeroUno.
	- negativo: Si el numeroDos es menor que el numeroUno 	
*/
function comparaNumeros(numeroUno,numeroDos){
	return parseFloat(numeroDos) - parseFloat(numeroUno); 
	
	}


/*************************Version 1.0 ***********************************************
* Descripcion: Funcion que compara dos string que contiene numeros validos.
* @<autor>: Hugo Martinez
- parametros:
	* @ fecha : objeto o String que contiene una fecha.
	* @ anioMax : es el año maximo valido.
	* @ aniMin : es el año minimo valido.
- Retorna: un String.
	- VACIO : Si la fecha validada es un string vacio .
	- ERROR_FORMATO_FECHA: Si la fecha validada no posee el formato dd/mm/aaaa
	- FECHA_VALIDA:Si la fecha validada es correcta. 
# Retorna los errores de:
	|Nombre de la funcion                               |Archivo en que se encuentra
	- ValidaDiaMesAnio(dia, mes, anio,anioMax,anioMin)	      - Validadores.js
# funciones Requeridas:								|  Archivo en que se encuentra
	- ValidaDiaMesAnio(dia, mes, anio,anioMax,anioMin)	      - Validadores.js	
	- isEmpty(str)											  - EfectosFuncionales.js
*/
function ValidarFecha( campoFecha, anioMax,anioMin){
	var fecha = campoFecha.value;

	if(isEmpty(campoFecha.value))
	return "VACIO";
	
	var expregFecha = /\d\d?(\/|-)\d\d?(\/|-)\d\d\d\d/;
//	alert(fecha.search(expregFecha));
	if( fecha.length > 10
	||fecha.search(expregFecha) == -1 )
	return "ERROR_FORMATO_FECHA";

	var diaMesanio;
	if(fecha.indexOf('/')!=-1 )
	 diaMesanio =  fecha.split('/');
			else
	 diaMesanio =  fecha.split('-');
	if(ValidarFecha.arguments.length == 1){	 
	//Se colocan por defecto los rangos anios.
	var anioMax = 3000;
	var anioMin = 1900;
	}
	var resultado = ValidaDiaMesAnio(new Number(diaMesanio[0]), new Number(diaMesanio[1]), new Number(diaMesanio[2]),anioMax,anioMin);
        if (resultado != "DIA_MES_ANO_VALIDO" ) 
	  	   return resultado;


	       return "FECHA_VALIDA";

}



/******************************************
* Descripcion:  Valida dias, meses y años.
* @<autor>: Hugo Martinez
- parametros:
	* @ dia : dia a validar.
	* @ mes : mes a validar.
	* @ anio : año a validar.		
	* @ anioMax : es el año maximo valido.
	* @ aniMin : es el año minimo valido.	
- Retorna: un String.
	- NO_ES_DIA: Indica que el parametro dia no contiene un numero de dia valido. 
	- NO_ES_MES: Indica que el parametro mes no contiene un numero de mes valido. 
	- DIA_INVALIDO : Indica que el parametro dia no contiene un numero de dia valido para el numero del mes dado.  
	- ANO_NO_BISIESTO : Indica que el año no es bisiesto.
	- DIA_MES_ANO_VALIDO : indica que el dia,el mes y el año son validos.
# Retorna los errores de:
	|Nombre de la funcion                   |Archivo en que se encuentra
	- ValidaAnio(anio,anioMax,anioMin)	      - Validadores.js
*/

function ValidaDiaMesAnio(dia, mes, anio,anioMax,anioMin)
{
	// Valida cantidad maxima de dias
	if (dia > 31||dia < 1) 
		return "NO_ES_DIA";
	// Valida cantidad maxima de meses
	if (mes > 12||mes < 1)
		return "NO_ES_MES";
	// Valida los meses de 30 dias
	if ((mes==4||mes==6||mes==9||mes==11)&&(dia>30))
		return "DIA_INVALIDO";

	// Valida febrero
	if (mes==2 && dia>28 && anio%4!=0) 
		return "ANO_NO_BISIESTO";
	if(mes ==2 && dia > 29)
		return "NO_ES_DIA";
var resultado = ValidaAnio(anio,anioMax,anioMin);
	if(resultado != "ANIO_VALIDO" )
		return	resultado;
	return "DIA_MES_ANO_VALIDO";
}
/*************************Version 1.0 ***********************************************
* Descripcion:  Valida si un año es valido. 
* @<autor>: Hugo Martinez
- parametros:
	* @ anio : número que contiene el año a validar.		
	* @ anioMax : número que contiene el año maximo valido.
	* @ aniMin : número que contiene el año minimo valido.	
- Retorna: un String.
	- ANIO_VACIO: Indica que el parametro año es vacio. 
	- ANIO_MAYOR:  Indica que el parametro año es mayor que el permitido. 
	- ANIO_MENOR : Indica que el parametro año es menor que el permitido. 
	- ANIO_VALIDO : Indica que el parametro año es valido .
# Funciones Utilizadas:
	|Nombre de la funcion                   |Archivo en que se encuentra
	- isEmpty(str)						      - EfectosFuncionales.js
# Funciones Requeridas: 				    |Archivo en que se encuentra	
	- isEmpty(str)						      - EfectosFuncionales.js	-
*/
function ValidaAnio(anio,anioMax,anioMin){
if(isEmpty(anio))
	return "ANIO_VACIO"
else if(anio > anioMax)
	return "ANIO_MAYOR";
else if(anio < anioMin)
	return "ANIO_MENOR";
return"ANIO_VALIDO"
}
/*************************Version 1.0 ***********************************************
* Descripcion: Funcion que valida un rut de acuerdo al algoritmo del digito verificador.
* @<autor>: Hugo Martinez
- parametros:
	* @rut: String o cadena que contine el rut a validar.
	* @dv: String que contiene el digito verificador del rut.
- Retorna: un booleano .
	* true: si es un rut valido.
	* false : no es un rut valido.
*/
function ValidarRut(rut, dv) {
    var suma = 0;
    var mul = 2;
    var i = 0;
    for (i = rut.length-1; i >= 0; i--) {
        suma = suma + rut.charAt(i) * mul;
        mul = mul==7 ? 2 : mul+1;
    }
    var dvr = '' + (11 - suma % 11);
    if (dvr == '10')
        dvr = 'K';
    else if (dvr=='11')
        dvr = '0';
    if (dvr != dv.toUpperCase() )
        return false;
    else
        return true;
}
/*************************Version 1.0 ***********************************************
* Descripcion: Funcion que valida un direccion de correo electronico.
* @<autor>: Hugo Martinez
- parametros:
	* @src: String o cadena que el rut a validar.
- Retorna: un booleano .
	* true: si es correo valido.
	* false : no es correo valido.
*/
function isEmail(str) {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}


// Ultimate client-side JavaScript client sniff. Version 3.03
// (C) Netscape Communications 1999-2001.  Permission granted to reuse and distribute.
// Revised 17 May 99 to add is.nav5up and is.ie5up (see below).
// Revised 21 Nov 00 to add is.gecko and is.ie5_5 Also Changed is.nav5 and is.nav5up to is.nav6 and is.nav6up
// Revised 22 Feb 01 to correct Javascript Detection for IE 5.x, Opera 4, 
//                      correct Opera 5 detection
//                      add support for winME and win2k
//                      synch with browser-type-oo.js
//                      add is.aol5, is.aol6
// Revised 26 Mar 01 to correct Opera detection
// Revised 02 Oct 01 to add IE6 detection

// Everything you always wanted to know about your JavaScript client
// but were afraid to ask ... "Is" is the constructor function for "is" object,
// which has properties indicating:
// (1) browser vendor:
//     is.nav, is.ie, is.opera, is.hotjava, is.webtv, is.TVNavigator, is.AOLTV
// (2) browser version number:
//     is.major (integer indicating major version number: 2, 3, 4 ...)
//     is.minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is.nav2, is.nav3, is.nav4, is.nav4up, is.nav6, is.nav6up, is.gecko, is.ie3, 
//     is.ie4, is.ie4up, is.ie5, is.ie5up, is.ie5_5, is.ie5_5up, is.ie6, is.ie6up, is.hotjava3, is.hotjava3up,
//     is.opera2, is.opera3, is.opera4, is.opera5, is.opera5up, is.aol3, is.aol4, is.aol5, is.aol6
// (4) JavaScript version number:
//     is.js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is.win, is.win16, is.win32, is.win31, is.win95, is.winnt, is.win98, is.winme, is.win2k
//     is.os2
//     is.mac, is.mac68k, is.macppc
//     is.unix
//     is.sun, is.sun4, is.sun5, is.suni86
//     is.irix, is.irix5, is.irix6
//     is.hpux, is.hpux9, is.hpux10
//     is.aix, is.aix1, is.aix2, is.aix3, is.aix4
//     is.linux, is.sco, is.unixware, is.mpras, is.reliant
//     is.dec, is.sinix, is.freebsd, is.bsd
//     is.vms
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.
//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when Nav5 and IE5 (or later) are released, so
// in conditional code forks, use is.nav4up ("Nav4 or greater")
// and is.ie4up ("IE4 or greater") instead of is.nav4 or is.ie4
// to check version in code which you want to work on future
// versions.


function ObtieneInfoCliente()
{   // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();

    // *** BROWSER VERSION ***
    // Note: On IE5, these return 4, so use is.ie5up to detect IE5
    // or is.ie6up to detect IE6.

    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);

    // Note: Opera and WebTV spoof Navigator.  We do strict client detection.
    // If you want to allow spoofing, take out the tests for opera and webtv.
    this.nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    this.nav2 = (this.nav && (this.major == 2));
    this.nav3 = (this.nav && (this.major == 3));
    this.nav4 = (this.nav && (this.major == 4));
    this.nav4up = (this.nav && (this.major >= 4));
    this.navonly      = (this.nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );
    this.nav6 = (this.nav && (this.major == 5));
    this.nav6up = (this.nav && (this.major >= 5));
    this.gecko = (agt.indexOf('gecko') != -1);


    this.ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    this.ie3    = (this.ie && (this.major < 4));
    this.ie4    = (this.ie && (this.major == 4) && (agt.indexOf("msie 4")!=-1) );
    this.ie4up  = (this.ie  && (this.major >= 4));
    this.ie5    = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.0")!=-1) );
    this.ie5_5  = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.5") !=-1));
    this.ie5up  = (this.ie  && !this.ie3 && !this.ie4);
    this.ie5_5up =(this.ie && !this.ie3 && !this.ie4 && !this.ie5);
    this.ie6    = (this.ie && (this.major == 4) && (agt.indexOf("msie 6.")!=-1) );
    this.ie6up  = (this.ie  && !this.ie3 && !this.ie4 && !this.ie5 && !this.ie5_5);

    // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // variables is.aol, is.aol3, and is.aol4 aren't 100% reliable.
    this.aol   = (agt.indexOf("aol") != -1);
    this.aol3  = (this.aol && this.ie3);
    this.aol4  = (this.aol && this.ie4);
    this.aol5  = (agt.indexOf("aol 5") != -1);
    this.aol6  = (agt.indexOf("aol 6") != -1);

    this.opera = (agt.indexOf("opera") != -1);
    this.opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
    this.opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
    this.opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
    this.opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
    this.opera5up = (this.opera && !this.opera2 && !this.opera3 && !this.opera4);

    this.webtv = (agt.indexOf("webtv") != -1); 

    this.TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1)); 
    this.AOLTV = this.TVNavigator;

    this.hotjava = (agt.indexOf("hotjava") != -1);
    this.hotjava3 = (this.hotjava && (this.major == 3));
    this.hotjava3up = (this.hotjava && (this.major >= 3));

    // *** JAVASCRIPT VERSION CHECK ***
    if (this.nav2 || this.ie3) this.js = 1.0;
    else if (this.nav3) this.js = 1.1;
    else if (this.opera5up) this.js = 1.3;
    else if (this.opera) this.js = 1.1;
    else if ((this.nav4 && (this.minor <= 4.05)) || this.ie4) this.js = 1.2;
    else if ((this.nav4 && (this.minor > 4.05)) || this.ie5) this.js = 1.3;
    else if (this.hotjava3up) this.js = 1.4;
    else if (this.nav6 || this.gecko) this.js = 1.5;
    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.
    else if (this.nav6up) this.js = 1.5;
    // note ie5up on mac is 1.4
    else if (this.ie5up) this.js = 1.3

    // HACK: no idea for other browsers; always check for JS version with > or >=
    else this.js = 0.0;

}

function ofCheckData(theForm)
{
	var lsEmail=theForm.elements["email"].value;
	lsEmail=ofTrim(lsEmail);
	if (lsEmail!=null && lsEmail!='') {
		if (ofEMailCheck(lsEmail)==false) {
			alert('La direccion de Correo Electronico ha sido mal especificada');
			theForm.elements["email"].focus();
			return false;
		}
	} else {
		alert('No ha especificado un correo electronico al cual notificar');
		theForm.elements["email"].focus();
		return false;
	}
	return true;
}

function buscar2(formulario){   
							varDia=formulario.dia.value; 
							varMes=formulario.mes.value; 
							varAgno=formulario.agno.value;
							formulario.FECHA.value=varDia+"/"+varMes+"/"+varAgno
							if (ValidarFecha(formulario.FECHA) != "FECHA_VALIDA"){
								alert("Ingrese una fecha valida");
								return;
							}                            
					formulario.action="InfoFinanciera?indice=4.2.1&FECHA="+varDia+"/"+varMes+"/"+varAgno;
					formulario.submit();
}

function buscar3(formulario){   
							varMonto=parseInt(formulario.monto.value); 
							varPlazo=parseInt(formulario.plazo.value); 
							varRango=0;
							if (varMonto==1 && varPlazo==1)
							varRango=1;
							else if (varMonto==1 && varPlazo==2)
							varRango=2;
							else if (varMonto==2 && varPlazo==1)
							varRango=3;
							else if (varMonto==2 && varPlazo==2)
							varRango=4;
							else if (varMonto==3 && varPlazo==1)
							varRango=5;
							else if (varMonto==3 && varPlazo==2)
							varRango=6;
							
					formulario.action="BFPublicacion?indice=B.F.I.1&rango="+varRango;
					formulario.submit();
}




