//<!-- JavaScript Document
var xmlHttp = null;
var nbsp = 160;
var node_text = 3;
var emptyString = /^\s*$/;
var glb_vfld; 
var proceed = 2;  

function obtenerDominio() {
    var dirhost = window.location.host;
    var frase = dirhost.substring(0,3);    
    var dominio = window.location.protocol + "//" + window.location.host;
    if ( frase != "www") 
        dominio = dominio +  "/cmacpiurawww";
    return dominio;
}

function ComprobarDatosIngresadosSimuladorCreditos (servicio) {
    var formu = window.document.frmsimcreditos;
    if ( formu.cbxtipcred.value == 0 ) {
        alert("Falta ingresar el tipo de credito");
        formu.cbxtipcred.focus();
        return false;
    }
    if ( formu.cbxmoneda.value == 0 ) {
        alert("Falta ingresar el tipo de moneda");
        formu.cbxmoneda.focus();
        return false;
    }
    if ( servicio == 70 ) {
        if ( formu.txtplazodias.value == 0 ) {
            alert("Falta ingresar el plazo");
            formu.txtplazodias.focus();
            return false;
        }
    } else {
        if ( formu.txtmonto.value == "" ) {
            alert("Falta ingresar el monto");
            formu.txtmonto.focus();
            return false;
        }

        var monto = 100;
        var montomax = 1000000000;
        if ( servicio == 94 ) {
            monto = 11000;
        }
        if ( parseFloat(formu.txtmonto.value) < monto ) {
            alert("El monto debe ser un numero mayor o igual a " + monto );
            formu.txtmonto.value = "";
            formu.txtmonto.focus();
            return false;
        }
        if ( parseFloat(formu.txtmonto.value) > montomax ) {
            alert("El monto no puede ser mayor a " + montomax );
            formu.txtmonto.value = "";
            formu.txtmonto.focus();
            return false;
        }

        if(jQuery('#txtnumcuotas')!=null){
            if ( jQuery('#txtnumcuotas').val() == "" ) {
                alert("Falta ingresar el numero de cuotas");
                jQuery('#txtnumcuotas').val('');
                jQuery('#txtnumcuotas').focus();
                return false;
            }
        }
        if(jQuery('#txtrecprom')!=null){
            if(parseInt(jQuery('#txtrecprom').val())<=0){
                alert("Ingresar Recorrido diferente de cero");
                jQuery('#txtrecprom').val('');
                jQuery('#txtrecprom').focus();
                return false;
            }
        }
        if(jQuery('#txtrengln')!=null){
            if(parseInt(jQuery('#txtrengln').val())<=0){
                alert("Ingresar Rendimiento diferente de cero");
                jQuery('#txtrengln').val('');
                jQuery('#txtrengln').focus();
                return false;
            }
        }

        if(servicio==998){
            if(formu.txtdiafac.value=="" || parseInt(formu.txtdiafac.value)<0 || parseInt(formu.txtdiafac.value)>31 ){
                alert("El día de facturación debe ser un valor entre [1-31]");
                formu.txtdiafac.focus();
                return false;
            }
            /*if(formu.txtdiapag.value=="" || parseInt(formu.txtdiapag.value)<0 || parseInt(formu.txtdiapag.value)>31 ){
                alert("El día de pago debe ser un valor entre [1-31]");
                formu.txtdiapag.focus();
                return false;
            }*/
            if(parseInt(formu.txtdiafac.value)==parseInt(formu.cbxfrecpago.value)){
                alert("El día de facturación y el día de pago no pueden ser iguales");
                formu.txtdiafac.focus();
                return false;
            }
        }
        if ( servicio != 94 ) {
            if(jQuery('#txtnumcuotas')!=null){
                if ( parseInt(jQuery('#txtnumcuotas').val()) < 1 || parseInt(jQuery('#txtnumcuotas').val()) > 240 ) {
                    alert("El numero de cuotas debe ser un valor entre [1-240]");
                    jQuery('#txtnumcuotas').val('');
                    jQuery('#txtnumcuotas').focus();
                    return false;
                }
            }
            if(jQuery('#cbxfrecpago')!=null ||jQuery('#cbxmodpago')!=null ){
                if ( jQuery('#cbxfrecpago').val() == "" || parseInt(jQuery('#cbxfrecpago').val()) < 0 ||
                    parseInt(jQuery('#cbxfrecpago').val()) > 31 ) {
                    if ( parseInt(jQuery('#cbxmodpago').val()) == 1 )
                        alert("La frecuencia de pagos debe ser un valor entre [1-31]");
                    jQuery('#cbxfrecpago').focus();
                    return false;
                }
            }
            
            if(jQuery('#cbxfrecpago')!=null && jQuery('#cbxmodpago')!=null ){
                if(!validarNumero(jQuery('#cbxfrecpago').val()) &&parseInt(jQuery('#cbxmodpago').val()) == 1){
                     alert("La frecuencia de pagos debe ser un valor entre [1-31]");
                     jQuery('#cbxfrecpago').focus();
                     return false;
                }
            }
            
            
        }
        
        if ( servicio == 22){
            var tasaMinima = parseInt(formu.txtTasaInteresMinima.value);
            if ( formu.txtTasaInteres.value == "" || parseInt(formu.txtTasaInteres.value) < tasaMinima ){
                alert("La tasa de interes debe estar en el rango de la mínima y máxima");
                return false;
            }
        }
        
    }
    return true;
}

function ValidarBusqueda () {
    var formu = window.document.frmBusqueda;
    if ( formu.txtBuscar.value == "" ) {
        alert("Debe ingresar un criterio de busqueda");
    }    
    else {
        formu.submit();    
    }
}

function ventanaTasas(ref,targ,ancho,alto) {
    var l = (screen.width - ancho) - 30;    
    var t = 50;
    window.open(ref,targ,"width="+ancho+",height="+alto+",top="+t+",left="+l+",resizable=1");
}

function ventanaCronograma(ref,targ,ancho,alto) {
    var left = (screen.width - ancho) - 30;    
    var top = 40;
    if ( alto > screen.height-200 ) {
        alto = screen.height-200;
    }
    
    window.open(ref,targ,"width="+ancho+",height="+alto+",top="+top+",left="+left+",resizable=1,scrollbars=1");
}

function ComprobarDatosIngresadosSimuladorAhorros () {
    var formu = window.document.frmsimahorros;
	
    if ( formu.cbxtipahorro.value == 0 ) {
        alert("Falta ingresar el tipo de ahorro");
        formu.cbxtipahorro.focus();
        return false;
    }
    if ( formu.cbxmoneda.value == 0 ) {
        alert("Falta ingresar el tipo de moneda");
        formu.cbxmoneda.focus();
        return false;
    }
	
    if ( formu.txtmonto.value == "" ) {
        alert("Falta ingresar el monto");
        formu.txtmonto.focus();
        return false;
    }

    if ( parseFloat(formu.txtmonto.value)  < 100 ) {
        alert("El monto debe ser un numero mayor o igual a 100.00");
        formu.txtmonto.value = "";
        formu.txtmonto.focus();
        return false;
    }

    if ( formu.cbxplazo.value == 0 ) {
        alert("Falta ingresar el plazo");
        formu.cbxplazo.focus();
        return false;
    }

    return true;
}

function createXMLHttpRequest() {
    var objHttp;
    try {
        objHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(exception)   {
        try {
            objHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(exception)   {
            objHttp = false;
        }
    }
    if (window.XMLHttpRequest) {
        objHttp = new XMLHttpRequest();
    }
    return objHttp;
}            

//Nueva funcion de captura de ubigeo
function refreshListaUbigeo(listaOrigen, variable, listaDestino, listaDestino2){                    
    var origen = document.getElementById(listaOrigen);
    var valorOrigen = document.getElementById(listaOrigen).value;
        
    if (valorOrigen == ""){
        clearLista(listaDestino);
        clearLista(listaDestino2);
        return;
    }
    //var url = URL_Ubigeo +"?" +
    var url = obtenerDominio()  +"/controlUBIGEO?" +
    createQueryString(variable,valorOrigen);
    xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                actualizaListaUbigeo(listaDestino);
            }
        }
    }
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
            
//Nueva funcion de captura de ubigeo
function refreshListaUbigeo2(listaOrigen1, variable1, listaOrigen2, variable2, listaDestino){
    var origen1 = document.getElementById(listaOrigen1);
    var valorOrigen1 = document.getElementById(listaOrigen1).value;
    if (valorOrigen1 == ""){
        clearLista(listaOrigen2);
        clearLista(listaDestino);
        return;
    }
    var origen2 = document.getElementById(listaOrigen2);
    var valorOrigen2 = document.getElementById(listaOrigen2).value;
    if (valorOrigen2 == ""){
        clearLista(listaDestino);
        return;
    }
    //var url = URL_Ubigeo +"?" + createQueryString2(variable1,valorOrigen1,variable2,valorOrigen2);
    var url = obtenerDominio() +"/controlUBIGEO?" + createQueryString2(variable1,valorOrigen1,variable2,valorOrigen2);
    xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                actualizaListaUbigeo(listaDestino);
            }
        }
    }
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
            
//Nueva funcion de actualizacion
function actualizaListaUbigeo(listaDestino){
    clearLista(listaDestino);
    var lista = document.getElementById(listaDestino);
    var resultados = xmlHttp.responseXML.getElementsByTagName("ubigeo");
    var option = null;
    option = document.createElement("option");
    option.appendChild
    (document.createTextNode("Escoja una opcion"));
    option.value = "";
    lista.appendChild(option);
    for (var i = 0; i < resultados.length; i++){
        var datos = resultados[i].childNodes;
        option = document.createElement("option");
        option.appendChild
        (document.createTextNode(datos[1].firstChild.nodeValue));
        option.value= datos[0].firstChild.data;
        lista.appendChild(option);
    }
}            
            
//nueva funcion de createQueryString
function createQueryString(variable, valorxEnviar) {
    var queryString = variable + "=" + valorxEnviar;
    return queryString;
}
            
//nueva funcion de createQueryString
function createQueryString2(variable1, valorxEnviar1, variable2, valorxEnviar2) {
    var queryString = variable1 + "=" + valorxEnviar1 + "&" + variable2 + "=" + valorxEnviar2;
    return queryString;
}
            
//nueva funcion de limpieza de lista
function clearLista(nombreLista){                                
    try{
        var lista = document.getElementById(nombreLista);
        lista.options.length = 0;
    }catch(exception){ }
}

function esSeleccionadoBotonRadio(ctrl){
    for(i=0;i<ctrl.length;i++)
        if(ctrl[i].checked) return true;
    return false    
}

function trim(str)
{
    return str.replace(/^\s+|\s+$/g, '')
}

function setFocusDelayed()
{
    glb_vfld.focus()
}

function setfocus(vfld)
{
    glb_vfld = vfld;
    setTimeout( 'setFocusDelayed()', 100 );
}

function msg(fld,     // id of element to display message in
    msgtype, // class to give element ("warn" or "error")
    message) // string to display
{
    var dispmessage;
    if (emptyString.test(message))
        dispmessage = String.fromCharCode(nbsp);
    else
        dispmessage = message;

    var elem = document.getElementById(fld);
    elem.firstChild.nodeValue = dispmessage;
  
    elem.className = msgtype;   // set the CSS class to adjust appearance of message
}
function commonCheck    (vfld,   // element to be validated
    ifld,   // id of element to receive info/error msg
    reqd)   // true if required
{
    if (!document.getElementById)
        return true;  // not available on this browser - leave validation to the server
    var elem = document.getElementById(ifld);
    if (!elem.firstChild)
        return true;  // not available on this browser
    if (elem.firstChild.nodeType != node_text)
        return true;  // ifld is wrong type of node

    if (emptyString.test(vfld.value)) {
        if (reqd) {
            msg (ifld, "error", "Informacion necesaria");
            setfocus(vfld);
            return false;
        }
        else {
            msg (ifld, "warn", "");   // OK
            return true;
        }
    }
    return proceed;
}


function validatePresent(vfld,   // element to be validated
    ifld,   // id of element to receive info/error msg
    reqd)   // true si es requerido
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;

    msg (ifld, "warn", "");
    return true;
}

function validateCadena(vfld,   // element to be validated
    ifld, // id of element to receive info/error msg
    reqd)  // si es requerido
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;

    var tfld = trim(vfld.value);  //Valor de la cadena
    var numdigits = 0;
    for (var j=0; j<tfld.length; j++)
        if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

    if (numdigits>0) {
        msg (ifld, "error", "ERROR: No debe haber numeros");
        setfocus(vfld);
        return false;
    }

    msg (ifld, "warn", "");
    return true;
}

function validateEmail  (vfld,   // element to be validated
    ifld,   // id of element to receive info/error msg
    reqd)   // true if required
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;
    
    var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
    var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
    
    if (!email.test(tfld)) {
        
        msg (ifld, "error", "ERROR: e-mail incorrecto.");
        setfocus(vfld);
        return false;
    }

    var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
    if (!email2.test(tfld))
        msg (ifld, "warn", "Inusual e-mail. Revisar");
    else
        msg (ifld, "warn", "");
    return true;
}

function validateTelnr  (vfld,   // element to be validated
    ifld,   // id of element to receive info/error msg
    reqd)   // true if required
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;

    var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
    var telnr = /^\+?[0-9 ()-]+[0-9]$/
    if (!telnr.test(tfld)) {
        msg (ifld, "error", "N&uacute;mero incorrecto.");
        setfocus(vfld);
        return false;
    }

    var numdigits = 0;
    for (var j=0; j<tfld.length; j++)
        if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

    if (numdigits<6) {
        msg (ifld, "error", "S&oacute;lo " + numdigits + " d&iacute;gitos - muy corto.");
        setfocus(vfld);
        return false;
    }

    if (numdigits>24)
        msg (ifld, "warn", numdigits + " digitos - Revise si es correcto");
    else {
        if (numdigits<10)
            msg (ifld, "warn", "S&oacute;lo " + numdigits + " d&iacute;gitos. Revisar");
        else
            msg (ifld, "warn", "");
    }
    return true;
}

function validateAge    (vfld,   // element to be validated
    ifld,   // id of element to receive info/error msg
    reqd)   // true if required
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;

    var tfld = trim(vfld.value);
    var ageRE = /^[0-9]{1,3}$/
    if (!ageRE.test(tfld)) {
        msg (ifld, "error", "ERROR: edad incorrecta.");
        setfocus(vfld);
        return false;
    }

    if (tfld>=200) {
        msg (ifld, "error", "ERROR: Edad incorrecta");
        setfocus(vfld);
        return false;
    }

    if (tfld>110)
        msg (ifld, "warn", "Mayor que 110: Revise si es correcto");    
    else {
        if (tfld<7)
            msg (ifld, "warn", "Demasiado joven");
        else
            msg (ifld, "warn", "");
    }
    return true;
}

function validateCampoNumerico(vfld, ifld, llong, reqd){
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;

    var tfld = trim(vfld.value);

    var numRE = /\d/
    if (!numRE.test(tfld)) {
        msg (ifld, "error", "Valor incorrecto.");
        setfocus(vfld);
        return false;
    }

    if (tfld.length != llong){
        msg (ifld, "error", "Revisar # d&iacute;gitos.");
        setfocus(vfld);
        return false;
    }

    if (llong == 11){
        var rucOk = valruc(tfld);
        if (!rucOk){
            msg (ifld, "error", "RUC incorrecto.");
            setfocus(vfld);
            return false;
        }
    }
    msg (ifld, "warn", "");
    return true;
}

function validateCampoNumerico2(vfld, ifld, reqd){
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;

    var tfld = trim(vfld.value);

    var numRE = /^([0-9])*$/
    if (!numRE.test(tfld)) {
        msg (ifld, "error", "Valor incorrecto.");
        setfocus(vfld);
        return false;
    }

    msg (ifld, "warn", "");
    return true;
}

function validateNumero(vfld, ifld, reqd){
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) return stat;

    var tfld = trim(vfld.value);

    if (isNaN(tfld)){
        msg (ifld, "error", "Valor incorrecto.");
        setfocus(vfld);
        return false;
    }
  
    msg (ifld, "warn", "");
    return true;
}

//Validacion de RUC segun SUNAT
function valruc(valor){
    valor = trim(valor);
    if ( valor.length == 8 ){
        suma = 0
        for (i=0; i<valor.length-1;i++){
            digito = valor.charAt(i) - '0';
            if ( i==0 ) suma += (digito*2)
            else suma += (digito*(valor.length-i))
        }
        resto = suma % 11;
        if ( resto == 1) resto = 11;
        if ( resto + ( valor.charAt( valor.length-1 ) - '0' ) == 11 ){
            return true
        }
    } else if ( valor.length == 11 ){
        suma = 0
        x = 6
        for (i=0; i<valor.length-1;i++){
            if ( i == 4 ) x = 8
            digito = valor.charAt(i) - '0';
            x--
            if ( i==0 ) suma += (digito*x)
            else suma += (digito*x)
        }
        resto = suma % 11;
        resto = 11 - resto
      
        if ( resto >= 10) resto = resto - 10;
        if ( resto == valor.charAt( valor.length-1 ) - '0' ){
            return true
        }
    }  
    return false
}

//Validacion de select
function validarSelect(vfld, ifld){      
    if (vfld.selectedIndex < 1) {
        msg (ifld, "error", "Escojer una opci&oacute;n.");
        setfocus(vfld);
        return false;    
    }     
    msg (ifld, "warn", "");  
    return true;  
}

function validaIngresoFecha() {
    /*
    var key=String.fromCharCode(e.which);
    //alert(e.which);
    if (((key<"0")||(key>"9"))&&(key!="/")&&(e.which!=8)&&(e.which!=0)){
        return false;
    }
    */
    return true;
}

function validaNumero() {
    /*
    var key=String.fromCharCode(e.which);
    //alert(e.which);
    if (((key<"0")||(key>"9"))&&(e.which!=8)&&(e.which!=0)){
        return false;
    }
    */
    return true;
}

function validaNumeroDecimal() {
    /*
    var key=String.fromCharCode(e.which);
    //alert(e.which);
    if (((key<"0")||(key>"9"))&&(e.which!=8)&&(e.which!=0)&&(key!=".")){
        return false;
    }
    */
    return true;
}    

// nueva funcion para abrir ventana maximizada
//var wOpen;
function abreventanaMax( aURL, aWinName )
{
   
    var wOpen;
    var sOptions;

    sOptions = 'directories=no,status=yes,toolbar=no,menubar=no,scrollbars=yes';
    sOptions = sOptions + ',resizable=yes,location=no,maximize=yes';
    //sOptions = sOptions + ',width=' + (screen.availWidth - 12).toString();
    //sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
   
    sOptions = sOptions + ',width=' + (screen.availWidth).toString();
    sOptions = sOptions + ',height=' + (screen.availHeight).toString();
 
    sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';

    //wOpen = window.open( '', aWinName, sOptions );
    window.open( aURL, aWinName, sOptions );
   
/*
   if (wOpen.location!=""){
	wOpen.close();
	wOpen = window.open( '', aWinName, sOptions );
	
   }  
   */
//wOpen.location = aURL;
//wOpen.focus();
//wOpen.moveTo( 0, 0 );
//wOpen.resizeTo( screen.availWidth, screen.availHeight );
//return wOpen;
}

function ValidaSeleccionCredito () {
    var formu = window.document.frmSelecCredito;

    if ( formu.cbxtipcred.value == 0 ) {
        alert("Por favor seleccione un tipo de credito");
        formu.cbxtipcred.focus();
        return false;
    }
    return true;
}
//-->
/*
 * validar fecha
 */
function esFechaValida(fecha){
	if (fecha != undefined && fecha.value != "" ){
		if (!/^\d{2}\/\d{2}\/\d{4}$/.test(fecha.value)){
			alert("formato de fecha no válido (dd/mm/aaaa)"+fecha);
			return false;
		}
		var dia = parseInt(fecha.value.substring(0,2),10);
		var mes = parseInt(fecha.value.substring(3,5),10);
		var anio = parseInt(fecha.value.substring(6),10);
	switch(mes){
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			numDias=31;
			break;
		case 4: case 6: case 9: case 11:
			numDias=30;
			break;
		case 2:
			if (comprobarSiBisisesto(anio)){numDias=29}else{numDias=28};
			break;
		default:
			alert("Fecha introducida errónea");
			return false;
	}
		if (dia>numDias || dia==0){
			alert("Fecha introducida errónea");
			return false;
		}
		return true;
	}
        return false;
}
function comprobarSiBisisesto(anio){
if ( ( anio % 100 != 0) && ((anio % 4 == 0) || (anio % 400 == 0))) {
	return true;
	}
else {
	return false;
	}
}
//validar Numeros
function validarNumero(tuCampoTexto){
if(/^[0-9]+$/.test(tuCampoTexto)) return true
return false;
}
