/**
 * valida os campos de um formulario
 * propriedades a serem setadas no campo(quando necessario):
 *================================================================
 * obrigatorio = 0|1   ( indica se o campo eh ou nao obrigatorio )
 * tipo= texto|data|numero|cpf|cnpj|combo|valor
 * maxchar= quando existir, o numero maximo de caracteres
 * minchar= quando existir, o numero minimo de caracteres
 */

/**
 * determina se valida os campos
 * nao obrigatorios tambem ....:
 * 0= nao valida os campos nao obrigatorios
 * 1= valida, quando preenchido, os campos nao obrigatorios
 */
var VALIDA_NAO_OBRIGATORIOS=0;

/**
 * mensagens de erro
 */
var errorMessage = "";

//function __valida(formulario,bloco){
function __valida(formulario){

    /** guarda o retorno dessa funcao */
    var retorno = 1;

    /** percorre todos os campos do formulario */
    for( var i=0; i< formulario.elements.length; i++){

        campo = formulario.elements[i];

        /** verificando se o campo faz parte
            da pagina/bloco atual */
        //if(parseInt(campo.bloco) && parseInt(campo.bloco)==parseInt(bloco)){

            /** se o campo eh obrigatorio
                verifico o seu tipo de dado
                e faco sua validacao */
            if ( VALIDA_NAO_OBRIGATORIOS || parseInt(campo.obrigatorio)){
                /** verifica o tipo de dado
                    que o campo espera */
                if(campo.tipo=="texto"){
                    retorno = __validaTexto(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"Informa??o incorreta":"";
                } else if(campo.tipo=="data"){
                    retorno = __validaData(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"Data no formato incorreto (dd/mm/aaaa)":"";
                } else if(campo.tipo=="numero"){
                    retorno = __validaNumero(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"Digite apenas n?meros":"";
                    //alert(campo.name);
                } else if(campo.tipo=="cpf"){
                    retorno = __validaCPF(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"CPF no formato incorreto":"";
                } else if(campo.tipo=="cnpj"){
                    retorno = __validaCNPJ(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"CNPJ no formato incorreto":"";
                } else if(campo.tipo=="combo"){
                    retorno = __validaCombo(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"Selecione uma op??o":"";
                } else if(campo.tipo=="valor"){
                    retorno = __validaValor(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"Valor no formato incorreto":"";
                } else if(campo.tipo=="email"){
                    retorno = __validaEmail(campo);
                    errorMessage = (!retorno && errorMessage.length==0)?"e-mail informado no formato incorreto":"";
                //* **** (Inicio) ASK 358591 - Daniel Felix - Data 14/09/2009 **** *  
				} else if(campo.tipo=="cpfCnpj"){
					retorno = valida_CNPJ_CPF_BY_TipoPropostaFavorecido(campo);
					errorMessage = (!retorno && errorMessage.length==0)?"CNPJ no formato incorreto":"";
				}
		    	//* **** (Fim) ASK 358591 - Daniel Felix - Data 14/09/2009 **** *  
			
            
                /** marcando o campo */
                if(!parseInt(retorno)){
                    //campo.style.background="#ff0000";
                    if(errorMessage.length >0){
                        alert(errorMessage);
                        errorMessage = "";
                        campo.focus();
                        break;
                    }
                }
            }
        //}
    }
    return(retorno);
}

//* **** (Inicio) ASK 358591 - Daniel Felix - Data 14/09/2009 **** *  

function valida_CNPJ_CPF_BY_TipoPropostaFavorecido(campo){

	var retorno = 1;
	
	if(document.getElementById('VFVCdTipoPropostaFavorecido0') != null){ 
	
		comboFavorecido = document.getElementById('VFVCdTipoPropostaFavorecido' + campo.index);
		
		//*** 1 - Cliente 3 - Compra Divida
		if (comboFavorecido.value == "1"){
			retorno = __validaCPF(campo);
		}else if (comboFavorecido.value == "3"){
			retorno = __validaCNPJ(campo);
		}
	}
	
	return (retorno);
}

//* **** (Fim) ASK 358591 - Daniel Felix - Data 14/09/2009 **** *  
				
/**
 * valida um campo individualmente
 */
function __validaCampo( campo ){

    /** guarda o retorno dessa funcao */
    var retorno = 1;

    /** se nao foi digitado nada,
        retorno **/
	campo.value = trim(campo.value);
    if(campo.value.length == 0){
        return;
    }

    /** verifica o tipo de dado
        que o campo espera */
    if(campo.tipo=="texto"){
        retorno = __validaTexto(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"Informa??o incorreta":"";
    } else if(campo.tipo=="data"){
        retorno = __validaData(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"Data no formato incorreto (dd/mm/aaaa)":"";
    } else if(campo.tipo=="numero"){
        retorno = __validaNumero(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"Digite apenas n?meros":"";
    } else if(campo.tipo=="cpf"){
        retorno = __validaCPF(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"CPF no formato incorreto":"";
    } else if(campo.tipo=="cnpj"){
        retorno = __validaCNPJ(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"CNPJ no formato incorreto":"";
    } else if(campo.tipo=="cpfCnpj"){
    	retorno = __validaCPF_CNPJ(campo);
       	//errorMessage = (!retorno && errorMessage.length==0)?"CPF/CNPJ no formato incorreto":"";
    } else if(campo.tipo=="combo"){
        retorno = __validaCombo(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"Selecione uma op??o":"";
    } else if(campo.tipo=="valor"){
        retorno = __validaValor(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"Valor no formato incorreto":"";
    } else if(campo.tipo=="email"){
        retorno = __validaEmail(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"e-mail informado no formato incorreto":"";
    } else {
        /** se nao eh de nenhum tipo
            valido como texto */
        retorno = __validaTexto(campo);
        errorMessage = (!retorno && errorMessage.length==0)?"Informa??o incorreta":"";
    }
    if(parseInt(retorno)){
        //formulario.submit();
    } else {

        if(errorMessage.length >0){
            alert(errorMessage);
            campo.focus();
            if(campo.tipo != "combo"){
                campo.value="";
            }
        }
    }
    return(retorno);
}

function __setFocus(campo){
    var encontrado = 0;
    try{
        if(campo.value.length < parseInt(campo.maxchar)){
            return;
        }
        var formulario = campo.form;
        for(var i=0; i< formulario.length; i++){
            if( !encontrado && campo != formulario[i]){
                continue;
            }
            try{
                encontrado = 1;
                errorMessage="";
                formulario[i+1].focus();
                break;
            } catch(e){}
        }
    } catch(ex){}
}

function __validaEmail(campo){

    if(campo.value.length != 0){
        mail = campo.value;
        tmp1 = /(@.*@)|(\.\.)|(@\.)|(^\.)/;
        tmp2 = /^.+@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
        tmp3 = /^[w]+[w]+[w]/;

        if (!(!tmp1.test(mail) && tmp2.test(mail) && !tmp3.test(mail))){
            campo.focus();
            return(0);
        }
    }
    return(1);
}

function __validaData(campo){

    var data = campo.value;
    var currentYear = new Date(year);

    if(data.length != 10){
        return(0);
    }

    var dia = data.substring(0,2);
    var mes = data.substring(3,5);
    var ano = data.substring(6);

    if( isNaN(dia) || parseInt(dia) < 1 || parseInt(dia) > 31){
        return(0);
    } else if( isNaN(mes) || parseInt(mes) < 1 || parseInt(mes) > 12){
        return(0);
    } else if( isNaN(ano) || ano.length != 4 || parseInt(ano) > currentYear){
        return(0);
    }
    return(1);
}
function __validaTexto(campo){

	campo.value = trim(campo.value);

    if(campo.value.length == 0){
        return(0);
    } else if(parseInt(campo.minchar) > campo.value.length){
        return(0);
    } else if(parseInt(campo.maxchar) < campo.value.length){
        return(0);
    }
    return(1);
}
function __validaNumero(campo){

    /** verificando se realmente eh um numero */
    if(isNaN(campo.value)){
        return(0);
    }
    /** verificando se foi especificado
        o tamanho minimo para o campo */
    if(parseInt(campo.minchar)>=0){
        if(parseInt(campo.minchar) > campo.value.length){
            return(0);
        }
    }
    /** verificando se foi especificado
        o tamanho maximo para o campo */
    if(parseInt(campo.maxchar)>=0){
        if(parseInt(campo.maxchar) < campo.value.length){
            return(0);
        }
    }
    return(1);
}
function __validaCPF(campo){

    if(__isCpf(campo.value)){
        if(!_validaCPF(__limpa(campo.value))){
            campo.focus();
            return (0);
        }else{
            campo.value = __formataCpf(campo.value);
            return (1);
        }
    } else {
        campo.focus();
        return(0);
    }
}
function __validaCNPJ(campo){
    if(__isCgc(campo.value)){
        if(!__validaCGC(__limpa(campo.value))){
            campo.focus();
            return (0);
        }else{
            campo.value = __formataCNPJ(campo.value);
            return (1);
        }
    }else{
        campo.focus();
        return (0);
    }
}
function __validaCPF_CNPJ(campo){
    // caso campo = cpf
    if(__isCpf(campo.value)){
        if(!_validaCPF(__limpa(campo.value))){
            alert("CPF inv?lido!");
            campo.focus();
            return (0);
        }else{
            campo.value = __formataCpf(campo.value);
            return (1);
        }
    // caso campo = cnpj
    }else if(__isCgc(campo.value)){
        if(!__validaCGC(__limpa(campo.value))){
            alert("CNPJ inv?lido!");
            campo.focus();
            return (0);
        }else{
            campo.value = __formatCharacterCNPJ(campo.value);
            return (1);
        }
    }else{
        alert("CPF/CNPJ inv?lido!");
		campo.focus(); //ERROv11-04
        return (0);
    }
}
function __validaCombo(campo){
    try{
        //if((parseInt(campo.value) == 0) || (parseInt(campo.value) == -1)){
		if (campo.selectedIndex == 0) {
            return(0);
        }
    } catch(e){}
    return(1);
}
function __validaValor(campo){

    valor = campo;
    if(valor.value.length >0){
        var i = 0;
        for (i=0; i < valor.value.length; i++){
            var a = ",".indexOf(valor.value.charAt(i));
            if( a >= 0){
                if((valor.value.length-1)-i == 0){
                    valor.value = valor.value + "00";
                    return (1);
                } else if((valor.value.length-1)-i == 1) {
                    valor.value = valor.value + "0";
                    return (1);
                }else if((valor.value.length-1)-i == 2)
                    return (1);
            }
        }
        valor.value = valor.value+",00"
        return (1);
    } else {
        return (0);
    }
}
function __isCpf(texto){
    if(__limpa(texto).length == 11)
        return (1);
    else
        return (0);
}
function __isCgc(texto){
    if(__limpa(texto).length == 14)
        return (1);
    else
        return (0);
}
function __limpa(c) { //Retira os caracteres - / . da string c
    while((cx=c.indexOf("-"))!=-1){
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("/"))!=-1){
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("."))!=-1){
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    return(c);
}
function _validaCPF(cpfFormatado){ //valida se o cpf(sem caracter de formato, so numeros) e valido

    var c = cpfFormatado.substring(0,9);
    var dv = cpfFormatado.substring(9,11);
    var d1 = 0;
    for (i = 0; i < 9; i++)
       d1 += c.charAt(i)*(10-i);

    if (d1 == 0)
        return (0);

    d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;

    if (dv.charAt(0) != d1)
        return (0);

    d1 *= 2;

    for (i = 0; i < 9; i++)
        d1 += c.charAt(i)*(11-i);

    d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;

    if (dv.charAt(1) != d1)
       return (0);

    return (1);
}
function __formataCpf(texto){
    if(texto.charAt(3) != "." )
        texto = texto.substring(0,3) +"."+ texto.substring(3,12);

    if(texto.charAt(7)!= "." )
        texto = texto.substring(0,7) +"."+ texto.substring(7,13);

    if(texto.charAt(11) != "-")
        texto = texto.substring(0,11) +"-"+ texto.substring(11,14);

    return (texto);
}

function __formataCNPJ(texto){
    if(texto.charAt(2) != ".")
        texto = texto.substring(0,2)+"."+texto.substring(2,15);

    if(texto.charAt(6) != ".")
        texto = texto.substring(0,6)+"."+texto.substring(6,16);

    if(texto.charAt(10) != "/")
        texto = texto.substring(0,10)+"."+texto.substring(10,17);

    if(texto.charAt(15) != "-")
        texto = texto.substring(0,15)+"."+texto.substring(15,18);

    return (texto);
}
function __formatCharacterCNPJ(texto){
    if(texto.charAt(2) != ".")
        texto = texto.substring(0,2)+"."+texto.substring(2,15);

    if(texto.charAt(6) != ".")
        texto = texto.substring(0,6)+"."+texto.substring(6,16);

    if(texto.charAt(10) != "/")
        texto = texto.substring(0,10)+"/"+texto.substring(10,17);

    if(texto.charAt(15) != "-")
        texto = texto.substring(0,15)+"-"+texto.substring(15,18);

    return (texto);
}
function __validaCGC(CNPJ){ //valida se o cpf(sem caracter de formato, so numeros) e valido

    var g = CNPJ.length-2;
    if(CNPJ == 0 )
        return (0);
    if(__RealTestaCNPJ(CNPJ,g) == 1){
        g=CNPJ.length-1;
        if(__RealTestaCNPJ(CNPJ,g) == 1)
            return (1);
        else
            return (0);

    }else
        return (0);

}
function __RealTestaCNPJ(CNPJ,g){
    var VerCNPJ=0;
    var ind=2;
    var tam;
    for(f=g;f>0;f--){
        VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind;
        if(ind>8){
            ind=2;
        }else{
            ind++;
        }
    }
    VerCNPJ%=11;
    if(VerCNPJ == 0 || VerCNPJ == 1){
        VerCNPJ=0;
    }else{
        VerCNPJ=11-VerCNPJ;
    }
    if(VerCNPJ != parseInt(CNPJ.charAt(g)))
        return (0);
    else
        return (1);
}
function continuar(){

    for ( var i=0; i< document.forms.length; i++){
        try{
            document.forms[i].acao.value="salvar";
            salvar();
            break;
        }catch(e){}
    }

    //try{
    //    var form;
    //    for( var i=0; i< document.forms.length; i++){
    //        if(document.forms[i].acao){
    //            form = document.forms[i];
    //            break;
    //        }
    //    }
    //    if(form.acao.value.length == 0){
    //        form.acao.value="salvar";
    //    }
    //    salvar();
    //}catch(e){
    //    alert("N?o foi definido campo acao no formulario");
    //}
    //document.forms[0].submit();
}
function voltar(){

    for ( var i=0; i< document.forms.length; i++){
        try{
            document.forms[i].acao.value="voltar";
            salvar();
            break;
        } catch(e){}
    }

    //try{
    //    var form;
    //    for( var i=0; i< document.forms.length; i++){
    //        if(document.forms[i].acao){
    //            form = document.forms[i];
    //            break;
    //        }
    //    }

    //    form.acao.value="voltar";
    //    salvar();
    //}catch(e){
    //    alert("N?o foi definido campo acao no formulario");
    //}
    //document.forms[0].submit();
}
function salvarProposta(){

    for ( var i=0; i< document.forms.length; i++){
        try{
            document.forms[i].acao.value="salvar_proposta";
            salvar();
            break;
        } catch(e){}
    }
    //try{
    //    var form;
    //    for( var i=0; i< document.forms.length; i++){
    //        if(document.forms[i].acao){
    //            form = document.forms[i];
    //            break;
    //        }
    //    }
    //    form.acao.value="salvar_proposta";
    //    salvar();
    //}catch(e){
    //    alert("N?o foi definido campo acao no formulario");
    //}
    //document.forms[0].submit();
}
function salvar(){

    for ( var i=0; i< document.forms.length; i++){
        try{
            /** teste se eh o formulario correto */
            var teste = document.forms[i].acao.value;
            if(!__valida(document.forms[i])){
                return (false);
            } else {
                document.forms[i].submit();
            }
            break;
        } catch(e){}
    }

    //try{
    //    var form;
    //    for( var i=0; i< document.forms.length; i++){
    //        if(document.forms[i].acao){
    //            form = document.forms[i];
    //            break;
    //        }
    //    }

    //    if(!__valida(form)){
    //        return (false);
    //    } else {
    //        form.submit();
    //    }
    //}catch(e){
    //    alert("Ocorreu um erro na valida??o das informa??es");
    //}
}
function menu(destino){

    for ( var i=0; i< document.forms.length; i++){
        try{
            document.forms[i].acao.value="salvar";
            document.forms[i].destino.value=destino;
            break;
        } catch(e){}
    }

    //try{
    //    form.acao.value="salvar";
    //    form.destino.value=destino;
    //} catch(e){
    //    alert("Ocorreu um erro");
    //}
}

/**
 * transforma e caixa alta
 * os valores digitados na pagina
 */
function toUpperCase(e){

    /**
     * no codigo ASCII, as teclas
     * de codigo na faixa 97-122
     * sao minusculas e sua correspondente
     * maiscula estao na posicao 32 anteriores
     */
    if((e.keyCode > 96 && e.keyCode < 123) || (e.keyCode > 223 && e.keyCode < 253) ){
        /** substituindo o codigo da tecla
            para 32 posicoes anteriores */
        e.keyCode -= (32);
    }
}

function days_between(date1, date2) {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)
}

function validaMatriculaPrefSaoPaulo(objMatricula) {
		
		var matricula = objMatricula.value;
		
		mPs1 = new Number();
		mPs2 = new Number();
		mPs3 = new Number();
		mPs4 = new Number();
		mPs5 = new Number();
		mPs6 = new Number();
		
		digito = new Number();
		digito = matricula.charAt(6);
		
		somaResultado = new Number();
		divisaoResultado = new Number();
		restoResultado = new Number();
		
		mPs1 = matricula.charAt(0) * 7;
		mPs2 = matricula.charAt(1) * 6;
		mPs3 = matricula.charAt(2) * 5;
		mPs4 = matricula.charAt(3) * 4;
		mPs5 = matricula.charAt(4) * 3;
		mPs6 = matricula.charAt(5) * 2;
		
		somaResultado = mPs1 + mPs2 + mPs3 + mPs4 + mPs5 + mPs6;
		restoResultado = somaResultado % 11;
		
		resultado = new Number();
		resultado = 11 - restoResultado;
		
		if(resultado == 10) {
			resultado = 0;
		} else if(restoResultado == 0) {
			resultado = 1;
		}		
		
		if(digito != resultado) {
			alert("matricula inv?lida !");
			objMatricula.focus();
		}		
}


// CREDv0604-05 Data:28/04/2006 Kleber Monteiro

/*
brasil = 001
real = 356
bradesco = 237	
itau = 341
*/
function validarDigitoContaCorrente(objBanco,objAgencia,objConta) {		
	
	if(objAgencia.value != "" && objConta.value != "") {			
		if(objBanco.value == "001") {			
			if(!calcularModulo(objConta.value, '1', 11,'brasil')) {
				alert("Conta Corrente invalida !");	
				objAgencia.focus();
				objConta.value = "";
			}
		} else if (objBanco.value == "237") {
			if(objConta.value != "1") {
				/*if(!calcularModulo(objConta.value, '2', 11,'bradesco')) {
					alert("Conta Corrente invalida !");	
					objAgencia.focus();
					objConta.value = "";
				}*/	
				
				var li_Peso = new Number();
				var li_tamanho = new Number();
				var ll_soma = new Number();
				var li_Peso = new Number();
				
				var ls_DigitoAux = new String();
				var ls_dac = new String();
				var ls_digito = new String();
				
				var tamContaCorrenteDv = objConta.value.length;
				var as_cdagencia = new String(objConta.value.substring(0,tamContaCorrenteDv - 1));
				var ls_digito = new String(objConta.value.substring(tamContaCorrenteDv - 1));
								
				li_Peso    = 2;
				li_Tamanho = as_cdagencia.length;
				ll_Soma    = 0;
				posicao = (li_Tamanho - 1);				
				while(li_Tamanho > 0){
   					//alert(escape(as_cdagencia.charAt(posicao)));
					//alert(as_cdagencia.charCodeAt(posicao));
					//alert(li_Peso);
   					if(as_cdagencia.charCodeAt(posicao) >= 48 && as_cdagencia.charCodeAt(posicao) <= 57 ) {
      					ll_Soma = ll_Soma + (as_cdagencia.charCodeAt(posicao) - 48) * li_Peso;
      					li_Peso = li_Peso + 1;
      					if( li_Peso > 7) {
							li_Peso = 2;
						}
      					li_Tamanho = li_Tamanho - 1;
						posicao--;
					}
				}
				ll_Soma = (ll_Soma % 11);
				ll_Soma = 11 - ll_Soma;
				//alert(ll_Soma);

				if( ll_Soma == 11) {
   					ls_DAC = "0";
				} else if(ll_Soma == 10) {
					//Pedro - 28/05/2009 - ASK 266374
					if (ls_digito.toUpperCase() == "0") {
						ls_DAC = "0";
					} else {
						// Digito P Bradesco 
						ls_DAC = "P";
					}
				} else {
   					ls_DAC = ll_Soma;
				}
				
				if(ls_digito.toUpperCase() != ls_DAC) {
					alert("Conta Corrente invalida !");
					objAgencia.focus();
					objConta.value = "";
				}				
			} 
		} else if (objBanco.value == "341") {
			
			var tamCampoConta = new Number();			
			tamCampoConta = objConta.value.length;			
			for (i = tamCampoConta; i < 6; i++) {
				objConta.value = '0' + objConta.value;
			}			
			if(!calcularModulo(objAgencia.value + objConta.value, '4', 10,'itau')) {
				alert("Agencia ou Conta Corrente invalida !");	
				objAgencia.focus();
				objAgencia.value = "";
				objConta.value = "";
			}
		
		} 
	}
}


/* ****(Inicio) Alexandre Curado - DIGITO VERIFICADOR - 22/12/2009 **** */
function validarDigitoAgencia(objBanco,objAgencia,objTpPagto,tpConvenio,objTpPropFav){
	var form = getForm();
var digAgeOP = consisteModuloOPBB(objBanco,objAgencia);
	if(objTpPropFav.value == 1){//Somente Cliente Possui OP e tpConvenio I OU P
		if(tpConvenio == "I"){	
			if(form.VFVCdTipoPropostaFavorecido[1] != null) {
				for(i = 0; i < form.VFVCdTipoPropostaFavorecido.length; i++) {
					if ( form.VFVNuBanco[i].value != null && form.VFVNuBanco[i].value == "001"){
						if(form.VFVTpPagamento[i].value != null && form.VFVTpPagamento[i].value == "6"){
							form.VFVDvAgencia[i].value = digAgeOP;
						}   
					}
				}
			}else{
				if(objBanco.value == "001" && objTpPagto.value == "6"){
					form.VFVDvAgencia.value = digAgeOP;
				}
			}
		}else if(tpConvenio == "P"){
			var digAgeOP = consisteModuloOPBB(objBanco,objAgencia);
			var qtFavorecidos = parseInt(form.qtFavorecidos.value);	
			if(qtFavorecidos == 1){
				if(objBanco.value == "001" && objTpPagto.value == "6"){
					form.VFVDvAgencia.value = digAgeOP;
				}
			}else{
				for(i = 0; i < qtFavorecidos; i++) {
					if ( form.VFVNuBanco[i].value != null && form.VFVNuBanco[i].value == "001"){
						if(form.VFVTpPagamento[i].value != null && form.VFVTpPagamento[i].value == "6"){
							form.VFVDvAgencia[i].value = digAgeOP;
							
						}   
					}
				}
			}
		}
	}
	
}
function consisteModuloOPBB(objBanco,objAgencia){
	var ll_soma = new Number();
	ll_Soma    = 0;
	var ls_DAC = new String();
	var pesos = montaPesos(objBanco,null);
	var ageConta = new String(objAgencia.value);
	
	for(i = 0; i < ageConta.length ; i++){
		ll_soma = ll_soma + (ageConta.charAt(i) * pesos[i]);	
	}
	
	ll_soma = ll_soma % 11;
	
	if(ll_soma == "10"){
		ls_DAC = "X";
	}else if(ll_soma < "10"){
		ls_DAC = ll_soma;
	}else if(ll_soma == "0"){
		ls_DAC = "0";
	}
	
	return ls_DAC;
}
function montaPesos(objBanco,tpModulo){
	var pesos = new Array();
	if (objBanco.value == "356" || objBanco.value == "347"){
		pesos = new Array(10);
		pesos[0] = "8";
		pesos[1] = "1";
		pesos[2] = "4";
		pesos[3] = "7";
		pesos[4] = "2";
		pesos[5] = "2";
		pesos[6] = "5";
		pesos[7] = "9";
		pesos[8] = "3";
		pesos[9] = "9";
		pesos[10] = "5";
	}else if(objBanco.value == "399"){
		if(tpModulo == "10"){
			pesos = new Array(4);
			pesos[0] = "2";
			pesos[1] = "1";
			pesos[2] = "2";
			pesos[3] = "1";
			pesos[4] = "2";
		}else if(tpModulo == "11"){
			pesos = new Array(9);
			pesos[0] = "8";
			pesos[1] = "9";
			pesos[2] = "2";
			pesos[3] = "3";
			pesos[4] = "4";
			pesos[5] = "5";
			pesos[6] = "6";
			pesos[7] = "7";
			pesos[8] = "8";
			pesos[9] = "9";
		}
	}else if(objBanco.value == "151"){
		pesos = new Array(11);
		pesos[0] = "6";
		pesos[1] = "7";
		pesos[2] = "8";
		pesos[3] = "9";
		pesos[4] = "2";
		pesos[5] = "3";
		pesos[6] = "4";
		pesos[7] = "5";
		pesos[8] = "6";
		pesos[9] = "7";
		pesos[10] = "8";
		pesos[11] = "9";
	}else if(objBanco.value == "001"){
		pesos = new Array(3);
		pesos[0] = "6";
		pesos[1] = "7";
		pesos[2] = "8";
		pesos[3] = "9";
	}else if(objBanco.value == "104"){
		pesos = new Array(7);
		pesos[0] = "2";
		pesos[1] = "3";
		pesos[2] = "4";
		pesos[3] = "5";
		pesos[4] = "6";
		pesos[5] = "7";
		pesos[6] = "8";
		pesos[7] = "9";
	}
	
	return pesos;
}
/* ****(FIM) Alexandre Curado - DIGITO VERIFICADOR - 22/12/2009 **** */


// CREDv0604-05 Data:28/04/2006 Kleber Monteiro

function calcularModulo(parametro, peso, modulo, banco){
	
	var retorno = "";
	var tamanho = new Number();
	var resto = new Number();	
	tamanho = parametro.length;
    var c = parametro.substring(0,tamanho - 1);	
    var dv = parametro.substring(tamanho -1);
	
    var d1 = 0;
	posicao = (tamanho - 1) - 1;
	varPeso = 0; 
	d1 = calcularPeso(c,peso,tamanho);
	resto = (d1 % modulo);
	if(banco == "brasil") {
		if(resto < 10) {
			retorno = resto; 
		} else if(resto == 10) {
			//Pedro - 28/05/2009 - ASK 266374
			if (dv.toUpperCase() == "0") {
				retorno =  "0";
			} else {
				retorno =  "X";
			}
		} else if(resto == 0) {
			retorno = "0";
		}
	} else if(banco == "real") {
		if(resto == 1) {
			retorno = "0"; 
		} else if(resto == 0) {
			retorno =  "1";
		} else {
			retorno = 11 - resto;
		}
	} else if(banco == "bradesco") {
		if(resto == 1) {
			retorno = "1"; 
		} else if(resto == 0) {
			retorno =  "0";
		} else {
			retorno = 11 - resto;
		} 		
	} else if(banco == "itau") {
		if(resto == 0) {
			retorno = "0";
		} else {
			retorno = 10 - resto;
		} 
	}
	//alert('valor calculado ' + retorno);
	//alert('valor digitado ' + dv);
	
	if(retorno == dv.toUpperCase()) {
		return (true);	
	} else {
		return (false);	
	}	
}


// CREDv0604-05 Data:28/04/2006 Kleber Monteiro
/*
  Banco do Brasil >> peso = 1
  Bradesco >> peso = 2
  Banco Real >> peso = 3
  Banco Itau >> peso = 4
*/
function calcularPeso(conta,peso,tamanho){
	var d1 = 0;
	posicao = (tamanho - 1) - 1;
	varPeso = 0; 
	
	if(peso == "1") {
		varPeso = 9;
	} else {
		varPeso = 2;
	}
	
	for (i = 0; i < tamanho - 1; i++) {
		if(peso == "1") {	   		
			if(varPeso < 2 ) {
				varPeso = 9;	
			}
			d1 += conta.charAt(posicao)*(varPeso--);
		} else if(peso == "2") {
			if(varPeso > 7 ) {
				varPeso = 2;	
			}			
			//alert("conta: " + conta.charAt(posicao));
			//alert("peso: " + varPeso);			
			d1 += conta.charAt(posicao)*(varPeso++);
			//alert("resultado: " + d1);
		} else if (peso == "3") {
			if(varPeso > 7 ) {
				varPeso = 2;
			}
			d1 += conta.charAt(posicao)*(varPeso++);
		} else if (peso == "4") {
			if(varPeso < 1 ) {
				varPeso = 2;
			}
			d1Mlt = conta.charAt(posicao)*(varPeso--);
			d1Aux = new String(d1Mlt);
			d1Soma = new Number();			
			if(d1Aux.length > 1) {
				for(j=0; j < d1Aux.length	; j++) {
					d1Soma += new Number(d1Aux.charAt(j));					
				}
				d1 += d1Soma;
			} else {
				d1 += d1Mlt;	
			}			
		}
	    posicao --;
	}	
    return (d1);
}



//************************************************************************************************
//inicio branch CREDv0707-01 accenture.javero 13/07/2007
//Função que capta eventos de digitação e ignora caracteres inválidos, cujo char codes estão
//presentes em 'invalidChars' e são iniciados por '#' e separados por ';'
//
//Exemplo de uso para ignorar todos os caracteres '%': onKeyPress="return filterInput(event,'#37;')"
//
function filterInput (event, invalidChars) {
    if (invalidChars.indexOf("#" + String(event.keyCode+ ";")) != -1) {
        event.returnValue = false
    }
}

//Após uma alteração de um campo de text input 'field', remove todos os caracteres
//cujo char codes estão separados por ',' e iniciados por '#' presente em 'invalidChars'
//
//Exemplo de uso para remover todos os caracteres '%': onKeyUp="clearInvalidChars(event, this, '#37;')"
//
function clearInvalidChars (event, field, invalidChars) {
    var invalidChar = invalidChars.replace(/#/g,"").split(";");
    var finalText = field.value;

    for (i = 0; i < invalidChar.length && finalText.length > 0; i++) {
    	finalText = removeAll(finalText, invalidChar[i]);
    }

    field.value = finalText;
}

//Dado uma string 'str', e um char code 'chCode', remove todas as ocorrências de 'chCode' de 'str'
//
//Exemplo: removeAll ('A%BC%%DE%F', 37) => retorna 'ABCDEF'
//
function removeAll (str, chCode) {
    var result = "";

    for (i = 0; i < str.length; i++) {
       if (str.charCodeAt(i) != chCode) {
           result = result + str.charAt(i);
       }
    }

    return result;
}
//fim branch
//************************************************************************************************

