var ventana=null;
function abrirVentanaEmergente() {
    var args=abrirVentanaEmergente.arguments;
    if(args.length==0)
        ventana=window.open('');
    else if(args.length==1)
        ventana=window.open(args[0]);
    else if(args.length==2)
        ventana=window.open(args[0],args[1]);
    else if(args.length==3)
        ventana=window.open(args[0],args[1],args[2]);
    chequearVentanaCerrada();
}

function chequearVentanaCerrada() {
    if(window.closed)
        ventana=null;
    else
        setTimeout('chequearVentanaCerrada()','3000');
}

function esNumero(numStr) {
    var i,a,num;
    for (i=1;i<=numStr.length;i++) {
        a = numStr.substring(i-1,i)
        num = parseInt(numStr);
        if (isNaN(a)) {
            //alert('Formato num&eacute;rico no valido en '+numStr);
            return false;
        }
    } 
    return (true);
}

function formatoEspaciosBlancos(cantidadBlancos){
    for (i=0;i<cantidadBlancos;i++){
        document.write("&nbsp;");
    }
}

function isPlaca(objetoPlaca,placaStr){
    
    var pla0=/^[A-Z][A-Z][A-Z][0-9][0-9][0-9]$/;
    var pla1=/^[A-Z][A-Z][0-9][0-9][0-9][0-9]$/;
    var pla2=/^[A-Z][0-9][0-9][0-9][0-9][0-9]$/;
    var pla3=/^[A-Z][A-Z][A-Z][0-9][0-9]$/;
    var pla4=/^[A-Z][A-Z][0-9][0-9][0-9]$/;
    var pla5=/^[0-9][0-9][0-9][0-9][0-9]$/;
    var pla6=/^[0-9][0-9][0-9][0-9]$/;
    var pla7=/^[A-Z][A-Z][A-Z][0-9][0-9][A-Z]$/;
    var pla8=/^[0-9][0-9][0-9][A-Z]$/;
    var pla9=/^[0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/;
    var pla10=/^[0-9][0-9][0-9][A-Z][A-Z]$/;
    var pla11=/^[S][I][N]$/;
    
    placaStr=placaStr.toUpperCase();
    
    var m= placaStr.match(pla0);
    //alert(placaStr+"..."+m)
    if (m==null)
        m= placaStr.match(pla1);
    if (m==null)
        m= placaStr.match(pla2);
    if (m==null)
        m= placaStr.match(pla3);
    if (m==null)
        m= placaStr.match(pla4);
    if (m==null)
        m= placaStr.match(pla5);
    if (m==null)
        m= placaStr.match(pla6);
    if (m==null)
        m= placaStr.match(pla7);
    if (m==null)
        m= placaStr.match(pla8);
    if (m==null)
        m= placaStr.match(pla9);
    if (m==null)
        m= placaStr.match(pla10);
    if (m==null)
        m= placaStr.match(pla11);
    
    if ((m == null) || (!placaStr) || (placaStr="")) {
        alert("Formato de placa no valido")
        objetoPlaca.value="";
        objetoPlaca.focus();
        return false;
    }
    else
        return true;
}
function esFecha(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 esta en un formato valido.")
        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&iacute;na 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
        //alert("Estoy en febrero")
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day>29 || (day==29 && !isleap)) {
            alert("Febrero " + year + " no tiene " + day + " dias!");
            return false;
        }
    }
    return true;  // date is valid
}

function isHora(objetoHora,timeStr) {
    
    
    var timePat = /^(\d{1,2})(:)(\d{1,2})/;
    var matchArray = timeStr.match(timePat); // is the format ok?
    if (matchArray == null) {
        alert("La hora no esta en un formato valido.")
        eval("document.form1."+objetoHora+".value=''");
        eval("document.form1."+objetoHora+".focus()");
        return false;
    }
    minutos = matchArray[3]; // parse date into variables
    horas = matchArray[1];
    
    if (horas < 0 || horas > 23) { // check horas range
        alert("La hora debe estar entre 0 y 23.");
        eval("document.form1."+objetoHora+".value=''");
        eval("document.form1."+objetoHora+".focus()");
        return false;
    }
    if (minutos < 0 || minutos > 59) {
        alert("Los minutos deben estar entre 0 y 59.");
        eval("document.form1."+objetoHora+".value=''");
        eval("document.form1."+objetoHora+".focus()");
        return false;
    }
    return true;  // date is valid
}


function fechaMenor(fmenor,fmayor) {
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
    var fechaMenor = fmenor.match(datePat); 
    var fechaMayor = fmayor.match(datePat);  
    
    
    if(fechaMenor!=null) {
        month = parseInt(fechaMenor[3]); // parse date into variables
        day =   parseInt(fechaMenor[1]);
        year =  parseInt(fechaMenor[4]);
        
        mh =	 parseInt(fechaMayor[3]); // parse date into variables
        dh =	 parseInt(fechaMayor[1]);
        yh =	 parseInt(fechaMayor[4]);
        
        alert(dh+"/"+mh+"/"+yh+"----"+day+"/"+month+"/"+year)
        if(year<=yh) {
            if(month<=mh) {
                if(day>dh) {
                    return false;
                }
            }
            else {
                if(month > mh) {
                    return false;
                } 
            }
            
        }
        else {
            if(year>yh) {
                return false;
            }
        }	  
    }
    return true
}



function toDate(fecini, Fecfin) {
    var FEC;
    FEC = split(Fecfin,"/");
    var fechaFinal=new Date(parseInt(FEC[2],10),parseInt(parseInt(FEC[1],10)-1),parseInt(FEC[0],10));
    uf=Date.parse(fechaFinal.toString());
    FEC = split(fecini,"/");
    var fechaInicial=new Date(parseInt(FEC[2],10),parseInt(parseInt(FEC[1],10)-1),parseInt(FEC[0],10));
    fi=Date.parse(fechaInicial.toString());
    if (fi>uf) {
        alert('La fecha no puede ser mayor a hoy');
        
    }
    else{
        return true;
        
    }
    
    
}

function split(source,separator) {
    var oldOffset,newOffset,i;
    temp = new Array;
    source = source+""
    for (i = 0,oldOffset = 0; oldOffset < source.length; ++i) {
        newOffset = source.indexOf(separator, oldOffset)
        if (newOffset == -1)
            newOffset = source.length
            temp[i] = source.substring(oldOffset, newOffset)
            oldOffset = newOffset + 1
    }
    return temp
}

function EstaVacio(Dato){
    for (var i=0;i<Dato.length;i++){
        if (Dato.substring(i,i+1)!= " ")
            return(false);
    }
    return(true)
}

function retornaNumero(valor) {
    var num="";
    var i,a;
    for (i=1;i<=valor.length;i++) {
        a = valor.substring(i-1,i);
        if (!isNaN(a)) {
            num=num+a;
        }
    } 
    return num;
}

// identificacion del usuario
function validarTipoDocumento(documento,tipoDocumento) {  
    var tamano=documento.length;
    if (tipoDocumento==2){
        if (tamano==10 || tamano==11){
            return(true) 
        }else{
            return(false) 
        }
    }else if (tipoDocumento==4){
        if (tamano>=9 && tamano<=10){
            return(true) 
        }else{
            return(false) 
        }
    }else if (tipoDocumento==3){
        if (tamano<=6){
            return(true) 
        }else{
            return(false) 
        }
    }else if (tipoDocumento==1){
        if (tamano>2){
            return(true) 
        }else{
            return(false) 
        }
    }else if (tipoDocumento==7){
        return validarCarnetDiplomatico(documento)
    }else{
        return(true) 
    }
}

// identificacion del usuario
function validarTipoDocumentoDiplomatico(documento,tipoDocumento) {  
    var tamano=documento.length;
    if (tipoDocumento==2){
        if (tamano==10 || tamano==11){
            return(true) 
        }else{
            return(false) 
        }
    }else if (tipoDocumento==4){
        if (tamano>=9 && tamano<=10){
            return(true) 
        }else{
            return(false) 
        }
    }else if (tipoDocumento==3){
        if (tamano<=6){
            return(true) 
        }else{
            return(false) 
        }
    }else if (tipoDocumento==1){
        if (tamano>2){
            return(true) 
        }else{
            return(false) 
        }
    }else{
        return(true) 
    }
}

function validar(valor) {
    var numero;
    numero=valor.length;
    
    if (numero==1 && valor==0){
        document.form1.identificacion.value="";
    }
    var estado=0;
    for (i=0; i<valor.length;i++){
        if (valor.substring(i,i+1)!=0){
            document.form1.identificacion.value=valor.substring(i,valor.length);
            i=valor.length+1;
            estado=1;
        }
    }
    if (estado==0){
        document.form1.identificacion.value="";
    }    
    
}


function isAlphanumeric(s){  
    var i;
    var cadena="";
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if ( isDigit(c) ){
            cadena+=c;
        }
    }
    document.forma.identificacion.value=cadena;
}

function isAlphanumericSalario(s,nombreCampo){  
    var i;
    var cadena="";
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if ( isDigit(c) ){
            cadena+=c;
        }
    }
        eval("document."+nombreCampo+".value='"+cadena+"'");

}



// c es una letra del alfabeto espanol
function isLetter(c){
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
    ( lowercaseLetters.indexOf( c ) != -1 ) )
}

// c es un digito
function isDigit(c){
    return ((c >= "0") && (c <= "9"))
}

function mostrarTeclado() { 
    document.getElementById("teclado").style.visibility = "visible";
    document.getElementById("fondo").style.visibility = "visible"; 
}

function ocultarTeclado() {
    document.getElementById("teclado").style.visibility = "hidden";
    document.getElementById("fondo").style.visibility = "hidden"; 
}

var digito;
var cedula="";
var tamano;
function campo(digito){
    if (digito==-1){
        document.forma.identificacion.value="";       
    }else{
        tamano=cedula.length;
        if (tamano!=0){
            document.forma.identificacion.value=document.forma.identificacion.value+digito;
        }else{
            if (numero!=0){
                document.forma.identificacion.value=document.forma.identificacion.value+digito; 
            }
        }       
    }
}


//******************************************************************************
// METODO QUE PERMITE QUE PERMITE REALIZAR LA VALIDACION DEL DOCUMENTO CARNET
// DIPLOMATICO, SE VALIDA QUE ESTE CAMPO INICIE POR ALGUNA DE LAS SIGUIENTES LETRAS
// (A, C, D, I,O), MINIMO DE 9 DIGITOS, MAXIMO 11 Y EN CASO DE EXISTIR LA POSICIÓN
// NUMERO 10 DEBE SER LA LETRA F.
//******************************************************************************
function validarCarnetDiplomatico(carnetDiplomatico){
    var documentoValido=false;
    if(carnetDiplomatico!=null && carnetDiplomatico.length>=9 && carnetDiplomatico.length<=11){
        var primerasLetrasValidas="ACDIO";
        var primeraLetra=carnetDiplomatico.substring(0, 1);
        
        if(primerasLetrasValidas.indexOf(primeraLetra)!=-1){
            if(carnetDiplomatico.length>=10){
                var letraPosicion10=carnetDiplomatico.charAt(9);
                if(letraPosicion10=='F'){
                    documentoValido=true;
                }
            }else{
                documentoValido=true;
            }
        }
    }
    return documentoValido;
}

//******************************************************************************
// FUNCION QUE SE ENCARGA DE MOSTRAR CUAL DE LAS RESTRICCIONES NO CUMPLIÓ EL VALOR
// INGRESADO PARA EL CARNET DIPLOMATICO.
//******************************************************************************
function mostrarValidacionesCarnetDiplomatico(carnetDiplomatico){
    var mensaje;
    if(carnetDiplomatico!=null && carnetDiplomatico.length>=9 && carnetDiplomatico.length<=11){
        var primerasLetrasValidas="ACDIO";
        var primeraLetra=carnetDiplomatico.substring(0, 1);
        
        if(primerasLetrasValidas.indexOf(primeraLetra)!=-1){
            if(carnetDiplomatico.length>=10){
                var letraPosicion10=carnetDiplomatico.charAt(9);
                if(letraPosicion10!='F'){
                    mensaje="Para el tipo de documento "+document.form1.documentoIdentidad.value+" el digito en la posici&oacute;n 10 debe ser la letra F"
                }
            }
        }else{
            mensaje="Para el tipo de documento "+document.form1.documentoIdentidad.value+" el primer digito debe ser una de las siguientes letras (A, C, D, I u O)"
        }
    }else{
        mensaje="Longitud permitida para el tipo de documento "+document.form1.documentoIdentidad.value+" es entre 9 y 11 digitos"
    }
    return mensaje;
}

//******************************************************************************
// FUNCION PARA CONTROLAR EL DE CARACTERES VALIDOS PARA EL TIPO DE DOCUMENTO 
// CARNET DIPLOMATICO, CUANDO SE TRATA DE ESTE TIPO DE DOCUMENTO SE PERMITE EL
// INGRESO DE LETRAS COSA QUE NO ES POSIBLE PARA LOS OTROS TIPOS, POR TAL RAZON
// SE DECIDE REEMPLAZAR HACIENDO USO DE DOM EL CAMPO DE TEXTO EN LA JSP Y SE 
// REEMPLAZAN LAS VALIDACIONES AL DIGITAR
//******************************************************************************
function aplicarMascara(tipoDocumento, identificacion){
    if(tipoDocumento==7){
        html="<input name='identificacion' type='text' class='mensaje' maxlength='15' onKeypress='if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97) ||(event.keyCode > 123) ||(event.keyCode ==13)) event.returnValue = false; if (event.keyCode == 13) javascript:enviar();' onKeyUp='upperCase(\"identificacion\", true);javascript:validar(this.value);' value='"+identificacion+"' onchange='javascript:validar(this.value);'>";
        document.getElementById("campoIdentificacion").innerHTML = html;
    }else{
        identificacion= retornarSoloLetras(identificacion);
        html="<input name='identificacion' type='text' class='mensaje' maxlength='15' onKeypress='if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false; if (event.keyCode == 13) javascript:enviar();' onKeyUp='isAlphanumeric(this.value);javascript:validar(this.value);' value='"+identificacion+"' onchange='isAlphanumeric(this.value);javascript:validar(this.value);'>";
        document.getElementById("campoIdentificacion").innerHTML = html;
    }
}
//******************************************************************************
// FUNCION PARA CONTROLAR EL INGRESO DE LETRAS SOLO EN MAYUSCULAS
//******************************************************************************
function upperCase(nombreCampo, eliminarEspacios){
    var valor=eval('document.form1.'+nombreCampo+'.value');
    if(eliminarEspacios){
        valor=eliminarEspaciosEnBlanco(valor);
    }
    eval("document.form1."+nombreCampo+".value='"+valor.toUpperCase()+"'");
}

//******************************************************************************
// FUNCION ELIMINA DE UNA CADENA TODAS LAS LETRAS QUE ENCUENTRE Y RETORNA ESTA
// NUEVA CADENA
//******************************************************************************
function retornarSoloLetras(valor){  
    var i;
    var cadena="";
    for (i = 0; i < valor.length; i++){   
        var c = valor.charAt(i);
        if ( isDigit(c) ){
            cadena+=c;
        }
    }
    return cadena;
}
//******************************************************************************
// FUNCION ELIMINA DE UNA CADENA LOS ESPACIOS EN BLANCO
//******************************************************************************
function eliminarEspaciosEnBlanco(valor){  
    var i;
    var cadena="";
    for (i = 0; i < valor.length; i++){   
        var c = valor.charAt(i);
        if ( c!='' && c!=' ' ){
            cadena+=c;
        }
    }
    return cadena;
}

//******************************************************************************
// GENERAR VINCULO PROCESO
//******************************************************************************
function vinculoProceso(proceso,nombreId,consecutivo){  
 var cadena="<a href='../../servlet/co.com.quipux.qxmultas.utilidades.presentation.controller.QxMultasController?accionSolicitada=ConsultaDetalleCargaCargaInformacion&paginaRespuesta=../reportes/carga_imprimir.jsp"+proceso+"'>"+consecutivo+"</a>"   
 window.opener.document.getElementById(nombreId).innerHTML=cadena;
 window.opener.document.getElementById('botonEjecutar').innerHTML='';
 window.setTimeout("window.close()",500);
}

//****************************************************************
// FUNCION PARA CONTROLAR EL MAXIMO NUMERO DE CARACTERES QUE SE PUEDE
// DIGITAR EN UN CONTROL TEXTAREA
//***************************************************************

function ismaxlength(obj,maxlength){
    var mlength=parseInt(maxlength)
    if (obj.value.length>mlength)
        obj.value=obj.value.substring(0,mlength)
}

//****************************************************************
// FUNCION PARA CONTROLAR EL FORMATO DE LA HORA 
// DIGITAR EN UN CONTROL TEXTAREA
//***************************************************************

function mascaraHora(dato){
    var cadena=dato;
    if (dato.length==2){
        cadena=cadena+":";
        document.form1.hora.value=cadena;
    }
}

//***************************************************************************
// FUNCION PARA CONTROLAR EL INGRESO DE NUMEROS DECIMALES CON UNA PRECISION
// ESPECIFICA
//**************************************************************************
var borrarCampo="false";
function decimal(campo,precision) {
   punto=false;
   if(borrarCampo=="true"){
       campo.value='';
       borrarCampo="false";
   }

   val = campo.value
   var key=event.keyCode;//codigo de tecla.

   for(z=0;z<val.length;z++){
       if(val.charAt(z)=='.'){
           punto=true;
       }
   }

   if ((key < 48 || key > 57) && key!=46) {//si no es numero
       window.event.keyCode=0;//anula la entrada de texto.
   }else if(key!=46){
       if(punto==true){
           index=val.lastIndexOf('.')
           val2=val.substring(index,val.length)
           if((val2.length)>precision){
               window.event.keyCode=0;
               return false;
           }
       }
   }

   // no deja introducir mas de una coma.
   if (key == 46) {
       if (punto==false) {
           punto=true;
       } else {
           window.event.keyCode=0;
           return false;
       }
   }
   return true
}



