/*
 * Biblioteca necessaria para consistencia padrao de campos
 * @Autor: Luciano M. Ribas
 * @Colaborador: Anderson Cesconeto
 */
var ERRO= false;
var LAST_FIELD;

SIZE_DATE = 8;
SIZE_CEP = 8
SIZE_ACCOUNT = 7;
SIZE_AG_ACCOUNT = 11;
MAX_NUMERIC = Number.MAX_VALUE;
SIZE_MONEY = 10; //9999999.99
SIZE_CPF =11;
SIZE_CNPJ =14;
SIZE_PERCENT = 5;
SIZE_PERCENT_OVER = 6;
SIZE_PERCENT_INT = 3;
SIZE_BRANCH = 4;
var NR_FORM;
if (NR_FORM == undefined) {
   NR_FORM = 0;
}

/**
 * Valida se a string contém apenas numéricos
 * 
 * @param string
 * @return
 */
function validaNumerico(value)
{
	var strValidos = "0123456789";
	var valor= new String(value);
	for(var i=0; i< valor.length; i++) {
		if( strValidos.indexOf(valor.charAt(i)) == -1) {
			return false;
		}
	}
	return true;
}

/**
 * Valida se a strinf contém apenas letras
 * 
 * @param string
 * @return
 */
function isAlfa(value)
{
	var expr= new RegExp("[A-Za-z ]+");
	return expr.test( value);
}

/**
 * Expressão regular de validação de conta e agência
 * 
 * @param string
 * @return
 */
function isStringBancoValida(value)
{
	var expr= new RegExp("([xX]|[0-9])");
    return expr.test( value);
}

/**
 * Expressão regular de validação de nome inválido para nome de cartão.
 * 
 * @param string
 * @return
 */
function isNomeValido(value)
{
	var expr= new RegExp("([A-Z]|[a-z]|^[ \t]+|[ \t]+$)");
    return expr.test( value);
}


///////////////////////////////////////////////////////////////////////
//Método: TrataValorMaximo( obj, tipo )
//Funcionalidade: Verifica se o campo não ultrapassou o limite do
//                tipo de dados
//Descrição:        -Recebe um objeto para pegar o valor e o tipo do dado
//                -Caso haja um valor excedente, set o campo para 0,00
///////////////////////////////////////////////////////////////////////
function TrataValorMaximo(el, tipo)
{
	var vr;
	vr = el.value;

	if (tipo == "decimal" && vr.length > 0){
		if (parseFloat(vr) > 9999999.99){
			el.value = "0,00";
		}
	}
}

//Nome do campo que está atualmente em edição para validação de erro
var nome = "";

///////////////////////////////////////////////////////////////////////
//Conjunto de comando para verificar navegador e versão
///////////////////////////////////////////////////////////////////////
var isNav = false, isIE = false, Versao="0.00";

AppName = navigator.appName;
AppVersion = navigator.appVersion;

if ( AppName.indexOf("Netscape") != -1 )
{
	isNav = true;
	Versao = AppVersion.substring(0, 4);
} else if ( AppName.indexOf("Microsoft") != -1 ) {
	isIE = true;
	Versao = AppVersion.substring((AppVersion.indexOf("E")+1), (AppVersion.indexOf("E")+6))
}

NUMVER = parseFloat(Versao);

if ( NUMVER >= 5) {
	Versao = "5"
} else if ( NUMVER >= 4 ) {
	Versao = "4"
} else if ( NUMVER >= 3 ) {
	Versao = "3"
} else Versao = "2"

///////////////////////////////////////////////////////////////////////
//Método: validaConteudo( obj, event, tipo)
//Funcionalidade: Não permite entrada de caracteres não autorizados
//Descrição:        -Recebe um objeto
//                -event é uma variável do navegador que guarda o evento do
//                teclado
//                -Tipo de dado
///////////////////////////////////////////////////////////////////////
function validaConteudo(event, el, tipo)
{
	var key;
	/**
	 * 9 = TAB
	 * 37,38,39,40 = ARROW KEYS
	 * 46 = DELETE
	 * 36 = HOME
	 * 35 = END
	 * 13 = ENTER
	 * 16 = SHIFT
	 * 45 = INSERT
	 */
	var validKeys = new Array(9, 37, 38, 39, 40, 46, 36, 35, 13, 16, 45);

	if (!isIE) {
		if (validKeys.in_array(event.keyCode)) {
			return true;
		} else {
			var blnTeclaControl = event.ctrlKey;
		    var regExp = /^[CVXAZ]$/;
		    
		    if (blnTeclaControl && regExp.test(String.fromCharCode(event.which).toUpperCase())) {
		        return true;
		    }
		}
	}
	
	if (isNav) {
		key = String.fromCharCode(event.which);
	} else {
		key = String.fromCharCode(event.keyCode);
	}
	
	if (isNav && event.which == 8) {
		return true;
	}
	
	if (tipo == "money" || tipo == "percent") {
		if (validaNumerico(key)) {
			return true;
		} else {
			if (key == ",") {
				return (el.value.indexOf(",") == -1);
			} else {
				return false;
			}
		}
	} else if (tipo == "text") {
		return ( isAlfa(key));
	} else if (tipo == "email") {
		return true;
	} else if (tipo == "banco") {
		if (validaNumerico(key) || isAlfa(key)) {
			return true;
		}else{
			return false;  
		}
	} else if (tipo == "banco2") {
		return  isStringBancoValida(key) ;
	} else if (tipo == "nome") {
		return isNomeValido(key);
	} else {
		return validaNumerico(key);
	}
}

function removeCaracs(Campo, tipo)
{
	wrkCampo = '';
	var type= "";
	var caracter= "", ok= false;

	if ( removeCaracs.arguments.length < 2) {
		type= new String("default");
	} else {
		type= new String(tipo);
	}
        
	if (type == "email") {
		focusNetscape(Campo);
		return;
	}

	vr = Campo.value;
	for ( i=0; i < vr.length; i++ ) {
		caracter = vr.substring(i,i+1);
		if( type != "text") {
			ok= ( caracter != '.' && caracter != ':' && caracter != '/' && caracter != '-' && caracter != ' ' && caracter != '%' && caracter != '(' && caracter != ')');
		} else {
			ok= isAlfa( caracter);
		}

		if( ok) {
			wrkCampo += caracter;
		}
	}
	
	Campo.value = wrkCampo;
	focusNetscape(Campo);
}

function focusNetscape(campo)
{
	if( navigator.appName.indexOf("Netscape") != -1) {
		if( ERRO ) {
			LAST_FIELD.focus();
			ERRO= false;
		}
	}
}

///////////////////////////////////////////////////////////////////////
//Método: formatTelefone( obj )
//Funcionalidade: Formata um valor no padrão (DDD) FONE
//Descrição:      -Recebe um objeto com o valor data digitada
//              -Se possível acrescenta caracteres separadores
//              -Valida a quandidade de caracteres
///////////////////////////////////////////////////////////////////////
function formatTelefone(e1)
{
	if ( e1.value != '' ) {
		if ( (e1.value.length < 9) && (e1.value.length > 0) ) {
			alert('Número inválido');
			focusCamp(e1);
		} else {
			var ddd = e1.value.substring(0,2);
			var fone = e1.value.substring(2,e1.value.length);
			var indice;
			if (e1.value.length == 9) {
				indice = 3;
			} else {
				indice = 4;
			}
			var fone1 = fone.substring(0, indice);
			var fone2 = fone.substring(indice, fone.length);
			e1.value = '(' + ddd + ') ' + fone1 + '-' + fone2;
		}
	}
}

///////////////////////////////////////////////////////////////////////
//Método: formatTelefoneResidencial( obj )
//Funcionalidade: Formata um valor no padrão (DDD) FONE, respeitando a regra que o primeiro numero
//após o DDD seja 2, 3, 4 ou 5
//Descrição:      -Recebe um objeto com o valor data digitada
//              -Se possível acrescenta caracteres separadores
//              -Valida a quandidade de caracteres
///////////////////////////////////////////////////////////////////////
function formatTelefoneResidencial(e1)
{
	if ( e1.value != '' ) {
		var digito = e1.value.substring(2,3);
		if ( (e1.value.length < 10) && (e1.value.length > 0) ) {
			alert('Número inválido');
	        focusCamp(e1);
		} else if (digito < 2 || digito > 5) {
			alert('Este não é um telefone fixo válido.');
			focusCamp(e1);
		} else {
			var ddd = e1.value.substring(0,2);
			var fone1 = e1.value.substring(2,6);
			var fone2 = e1.value.substring(6,10);
			e1.value = '(' + ddd + ') ' + fone1 + '-' + fone2;
		}
	}
}

///////////////////////////////////////////////////////////////////////
//Método: formatTelefoneCelular( obj )
//Funcionalidade: Formata um valor no padrão (DDD) FONE, respeitando a regra que o primeiro numero
//após o DDD seja maior que 5
//Descrição:  -Recebe um objeto com o valor data digitada
//            -Se possível acrescenta caracteres separadores
//            -Valida a quandidade de caracteres
///////////////////////////////////////////////////////////////////////
function formatTelefoneCelular(e1)
{
	if ( e1.value != '' ) {
		var digito = e1.value.substring(2,3);
		if ( (e1.value.length < 10) && (e1.value.length > 0) ) {
			alert('Número inválido');
	        focusCamp(e1);
		} else if (digito < 6) {
			alert('Este não é uma telefone celular válido.');
			focusCamp(e1);
		} else {
			var ddd = e1.value.substring(0,2);
			var fone1 = e1.value.substring(2,6);
			var fone2 = e1.value.substring(6,10);
			e1.value = '(' + ddd + ') ' + fone1 + '-' + fone2;
		}
	}
}

///////////////////////////////////////////////////////////////////////
//Método: formataPeriodo( obj )
//Funcionalidade: Formata um valor no padrão MM/AAAA
//Descrição:        -Recebe um objeto com a data digitada
//                -Se possível insere / e acrescenta caracteres
//                -Validade data gerada, impedindo que o campo seja deixado
//                se não for preenchido corretamente
///////////////////////////////////////////////////////////////////////
function formatPeriodo(el)
{
	var dia;
	var mes;
	var ano;
	var valor = new String(el.value);
	var a = new String();
	valor = "01" + valor;
	LAST_FIELD = el;
	
	if (el.maxLength < 7) {
		el.maxLength = 7;
	}

	if (!validaNumerico(valor)) {
		alert("Você deve digitar o período utilizando apenas números.\nUtilize 2 dígitos para o mês e 4 dígitos para o ano (MMAAAA)\n");
		focusCamp(el);
		return;
	}
	
	if (nome == "" || el.name == nome) {
		vr = el.value;
		vr = "01" + vr;
		if (vr.length >= 6 && vr.length <= 10) {
			token = new Array();
			i = 0;
			j = 0;
			nBar = 0;
			nDig = 0;
			
			if (vr.match(/^[0-9]{2}[0-9]{2}[0-9]{4}$/) || vr.match(/^[0-9]{2}[0-9]{2}[0-9]{2}$/)) {
				
				dia = vr.substring(0, 2);
				mes = vr.substring(2, 4);
				
				if (vr.length == 6) {
					if (parseInt(vr.substring(4, 6)) < 30) {
						ano = "20" + vr.substring(4, 6);
					} else {
						ano = "19" + vr.substring(4, 6);
					}
				} else {
					ano = vr.substring(4, vr.length);
				}
				
				a = dia + "/" + mes + "/" + ano;
			} else if (vr.match(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/) || vr.match(/^[0-9]{2}\/[0-9]{2}\/[0-9]{2}$/)) {
				var dados = vr.split;
				
				if (parseInt(dados[0]) < 10) {
					dia = "0" + parseInt(dados[0]);
				} else {
					dia = dados[0].substring(0, 2);
				}
				
				barra1 = dados[1];
				
				if (parseInt(dados[2]) < 10) {
					mes = "0" + parseInt(dados[2]);
				} else {
					mes = dados[2].substring(0, 2);
				}
				
				barra2 = dados[3];
				
				if (dados[4].length == 2) {
					if (parseInt(dados[4]) < 30) {
						ano = "20" + dados[4];
					} else {
						ano = "19" + dados[4];
					}
				} else {
					ano = dados[4];
				}
					
				a = dia + barra1 + mes + barra2 + ano;
			}
		}
		
		
		var err = 0;
		var psj = 0;
		
		if (a.length != 10) {
			err = 4;
		} else {
			dia = a.substring(0, 2);
			barra1 = a.substring(2, 3);
			mes = a.substring(3, 5);
			barra2 = a.substring(5, 6);
			ano = a.substring(6, 10);
			
			if (mes < 1 || mes >12) {
				err = 1;
			}
			
			if (barra1 != '/') {
				err = 4;
			}
			
			if (dia < 1 || dia > 31) {
				err = 2;
			}
			
			if (barra2 != '/') {
				err = 4
			}
				
			if (ano < 1900 || ano > 2100) {
				err = 3
			}
			
			if (mes == 4 || mes == 6 || mes == 9 || mes == 11) {
				if (dia == 31) {
					err = 4
				}
			}
			
			if (mes == 2) {
				var g = parseInt(ano/4)
				
				if (isNaN(g)) {
					err = 4
				}
				
				if (dia > 29) {
					err = 4
				}
				
				if (dia == 29 && ((ano/4)!=parseInt(ano/4))) {
					err = 4
				}
			}
		}
		
		if (err > 0 && a.length > 0) {
			el.value = a.substring(3, 10);
			alert('Período Inválido');
			nome = el.name;
			focusCamp(el);
			return;
		} else {
			nome = "";
			el.value = a.substring(3, 10);
		}
	}
	
	ERRO = false;
}

///////////////////////////////////////////////////////////////////////
//Método: formataDate( obj )
//Funcionalidade: Formata e valida campos do tipo data
//Descrição:        -Recebe um objeto com a data digitada
//                -Se possível insere / e acrescenta caracteres
//                -Validade data gerada, impedindo que o campo seja deixado
//                se não for preenchido corretamente
///////////////////////////////////////////////////////////////////////
function formatDate( el )
{
	var valor= new String(el.value);
	LAST_FIELD= el;
        
	if(!validaNumerico(valor)) {
		alert("Você deve digitar a data utilizando apenas números.\n" +
                                "Utilize 2 dígitos para o dia, 2 dígitos para o mês e " +
                                        "4 dígitos para o ano (DDMMAAAA)\n");
		focusCamp(el);
		return false;
	}

	nome = "";
	if (nome == "" || el.name == nome) {
		vr = el.value;
		if (vr.length >= 6 && vr.length <= 10) {
			token = new Array();
			i = 0;
			j = 0;
			nBar = 0;
			nDig = 0;
			while (i < vr.length) {
				if (vr.substring(i, i+1) >= '0' && vr.substring(i, i+1) <= '9') {
					str = "" + vr.substring(i, i+1);
					i++;
					while (vr.substring(i, i+1) >= '0' && vr.substring(i, i+1) <= '9' && i < vr.length) {
						str = str + vr.substring(i, i+1);
						i++;
					}
					token[j] = str;
					j++;
					nDig++;
				} else if (vr.substring(i, i+1) == "/") {
					str = "" + vr.substring(i, i+1);
					token[j] = str;
					j++;
					i++;
					nBar++;
				} else {
					i++;
				}
			}

            //verifica quantas barras e digitos foram reconhecidos
            //nBar == 0 e nDig == 1  - formato 01012000
            //nBar == 2 e nDig == 3  - formato 01/10/2000
            //para quaisquer outros formatos não faz formatação, ocasionando em erro
			if ((nBar == 0 && nDig == 1) || (nBar == 2 && nDig == 3)) {
				if (token.length == 1) {
					dia = token[0].substring(0, 2);
                                        mes = token[0].substring(2, 4);

                                        if (token[0].length == 6){
                                                if (eval(token[0].substring(4, 6)) < 30)
                                                        ano = "20" + token[0].substring(4, 6);
                                                else
                                                        ano = "19" + token[0].substring(4, 6);
                                        }
                                        else
                                        if (token[0].length == 8)
                                                ano = token[0].substring(4, 8);
                                        else
                                                ano = token[0].substring(4, token[0].length);

                                        el.value = dia + "/" + mes + "/" + ano;
                                }else
                                if (token.length == 5){
                                        if (token[0].length == 1 && eval(token[0]) < 10)
                                                dia = "0" + token[0];
                                        else
                                                dia = token[0].substring(0, 2);
                                        barra1 = token[1];
                                        if (token[2].length == 1 && eval(token[2]) < 10)
                                                mes = "0" + token[2];
                                        else
                                                mes = token[2].substring(0, 2);

                                        barra2 = token[3];

                                        if (token[4].length == 2){
                                                if (eval(token[4]) < 30)
                                                        ano = "20" + token[4];
                                                else
                                                        ano = "19" + token[4];
                                        }
                                        else
                                                ano = token[4];

                                        el.value = dia + barra1 + mes + barra2 + ano;
                                }
                        }
                }

                var err=0;
                var psj=0;
                a = el.value;

                if (a.length != 10)
                        err=4;
                else{

                        dia = a.substring(0, 2);
                        barra1 = a.substring(2, 3);
                        mes = a.substring(3, 5);
                        barra2 = a.substring(5, 6);
                        ano = a.substring(6, 10);

                        if (mes < 1 || mes >12) err = 1;
                        if (barra1 != '/') err = 4;
                        if (dia < 1 || dia > 31) err = 2;
                        if (barra2 != '/') err = 4
                        if (ano < 1900 || ano > 2100) err = 3
                        if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
                                if (dia == 31) err=4
                        }
                        if (mes == 2){
                                var g = parseInt(ano/4)
                                if (isNaN(g)) {
                                        err=4
                                }
                                if (dia > 29) err=4

                                if (dia == 29 && ((ano/4)!=parseInt(ano/4))) err=4
                        }
                }

                if (err > 0 && a.length > 0){
                        alert('Data Inválida');
                        nome = el.name;
                        focusCamp(el);
                        return false;
                }
                else
                        nome = "";
        }
        ERRO= false;
        return true;
}
function formatAg_Account(campo)
{
        var valor= new String(campo.value);
        LAST_FIELD= campo;

        if( valor == "" || valor == null)
                return;
        if( !validaNumerico(campo.value))
        {
                alert("Você deve digitar apenas números neste campo.\n" +
                                "Por favor, redigite-o novamente.");
                focusCamp(campo);
                return;
        }
        if( valor.length < SIZE_AG_ACCOUNT)
        {
                alert('Digite 4 dígitos para a agência e 7 dígitos para a conta.\nExemplo: 11112222222');
                focusCamp(campo);
                return;
        }
        var temp= valor.substring(0,4) + "-" + valor.substring(4,9) + "-" + valor.substring(9,11);
        campo.value= temp;
        ERRO= false;
        return;
}

function formatBranch(campo)
{
        var valor= new String(campo.value);
        LAST_FIELD= campo;

        if( valor == "" || valor == null)
                return;
        if( !validaNumerico(campo.value))
        {
                alert('Agência "' + campo.value + '" está incorreta.\n\n' +
                                "Você deve digitar apenas números neste campo.\n" +
                                "Por favor, redigite-o novamente.");
                focusCamp(campo);
                return;
        }
        if( valor.length < SIZE_BRANCH)
        {
                alert('Agência "' + campo.value + '" está incorreta.\n\n' +
                                'Por favor, digite a agência com ' + SIZE_BRANCH + ' dígitos.');
                focusCamp(campo);
                return;
        }
        ERRO= false;
        return;
}

function formatAccount(campo)
{
        var valor= new String(campo.value);
        LAST_FIELD= campo;

        if( valor == "" || valor == null)
                return;
        if( !validaNumerico(campo.value))
        {
                alert("Você deve digitar apenas números neste campo.\n" +
                                "Por favor, redigite-o novamente.");
                focusCamp(campo);
                return;
        }
        if( valor.length < SIZE_ACCOUNT)
        {
                alert('Conta \"' + campo.value + '\" está incorreta.\n\n' +
                                'Você deve digitar a conta com ' + SIZE_ACCOUNT + ' dígitos.');
                focusCamp(campo);
                return;
        }
        var temp= valor.substring(0,5) + "-" + valor.substring(5,7);
        campo.value= temp;
        ERRO= false;
        return;
}

function formatCEP(campo)
{
	var valor = campo.value.toString();
	var LAST_FIELD = campo;
	
	if(valor == "" || valor == null) {
		return;
    }

	if (campo){        
		campo.value = valor.substring(0,5) + "-" + valor.substring(5,8);
        
	}
	var ERRO = false;
	return;
}


function formatAniversariante(el) {
        var valor= new String(el.value );
        LAST_FIELD = el;

        if( !validaNumerico(valor))
        {
                alert("Você deve digitar o período utilizando apenas números.\n" +
                                "Utilize 2 dígitos para o dia e 2 dígitos para o mês (DDMM)\n");
                focusCamp(el);
                return;
        }

         if (nome == "" || el.name == nome){
                vr = el.value + '2000';
                if (vr.length >= 6 && vr.length <= 10){
                        token = new Array();
                        i = 0;
                        j = 0;
                        nBar = 0;
                        nDig = 0;

                        while (i < vr.length)
                        {
                                if (vr.substring(i, i+1) >= '0' && vr.substring(i, i+1) <= '9'){
                                        str = "" + vr.substring(i, i+1);
                                        i++;
                                        while (vr.substring(i, i+1) >= '0' && vr.substring(i, i+1) <= '9' && i < vr.length)
                                        {

                                                str = str + vr.substring(i, i+1);
                                                i++;
                                        }
                                        token[j] = str;
                                        j++;
                                        nDig++;
                                }else
                                if (vr.substring(i, i+1) == "/"){
                                        str = "" + vr.substring(i, i+1);
                                        token[j] = str;
                                        j++;
                                        i++;
                                        nBar++;
                                }
                                else{
                                        i++;
                                }
                        }

                        //verifica quantas barras e digitos foram reconhecidos
                        //nBar == 0 e nDig == 1  - formato 01012000
                        //nBar == 2 e nDig == 3  - formato 01/10/2000
                        //para quaisquer outros formatos não faz formatação, ocasionando em erro
                        if ((nBar == 0 && nDig == 1) || (nBar == 2 && nDig == 3)){
                                if (token.length == 1){
                                        dia = token[0].substring(0, 2);
                                        mes = token[0].substring(2, 4);

                                        if (token[0].length == 6){
                                                if (eval(token[0].substring(4, 6)) < 30)
                                                        ano = "20" + token[0].substring(4, 6);
                                                else
                                                        ano = "19" + token[0].substring(4, 6);
                                        }
                                        else
                                        if (token[0].length == 8)
                                                ano = token[0].substring(4, 8);
                                        else
                                                ano = token[0].substring(4, token[0].length);

                                        el.value = dia + "/" + mes + "/" + ano;
                                }else
                                if (token.length == 5){
                                        if (token[0].length == 1 && eval(token[0]) < 10)
                                                dia = "0" + token[0];
                                        else
                                                dia = token[0].substring(0, 2);
                                        barra1 = token[1];
                                        if (token[2].length == 1 && eval(token[2]) < 10)
                                                mes = "0" + token[2];
                                        else
                                                mes = token[2].substring(0, 2);

                                        barra2 = token[3];

                                        if (token[4].length == 2){
                                                if (eval(token[4]) < 30)
                                                        ano = "20" + token[4];
                                                else
                                                        ano = "19" + token[4];
                                        }
                                        else
                                                ano = token[4];

                                        el.value = dia + barra1 + mes + barra2 + ano;
                                }
                        }
                }

                var err=0;
                var psj=0;
                a = el.value;

                if (a.length != 10)
                        err=4;
                else{

                        dia = a.substring(0, 2);
                        barra1 = a.substring(2, 3);
                        mes = a.substring(3, 5);
                        barra2 = a.substring(5, 6);
                        ano = a.substring(6, 10);

                        if (mes < 1 || mes >12) err = 1;
                        if (barra1 != '/') err = 4;
                        if (dia < 1 || dia > 31) err = 2;
                        if (barra2 != '/') err = 4
                        if (ano < 1900 || ano > 2100) err = 3
                        if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
                                if (dia == 31) err=4
                        }
                        if (mes == 2){
                                var g = parseInt(ano/4)
                                if (isNaN(g)) {
                                        err=4
                                }
                                if (dia > 29) err=4

                                if (dia == 29 && ((ano/4)!=parseInt(ano/4))) err=4
                        }
                }

                if (err > 0 && a.length > 0){
                        el.value = a.substring(0, 5);
                        alert('Data Inválida');
                        nome = el.name;
                        focusCamp(el);
                        return;
                }
                else {
                        nome = "";
                        el.value = a.substring(0, 5);
                }
        }
        ERRO= false;
}


function formatNumeric(campo)
{
        var valor= new String(campo.value);
        LAST_FIELD= campo;

        if( valor == "" || valor == null)
                return;
        if( !validaNumerico(campo.value))
        {
                alert("Você deve digitar apenas numeros.\n" +
                                "Por favor, redigite este campo novamente.");
                focusCamp(campo);
                return;
        }
        ERRO= false;
        return;
}

function validaConteudoPercent(campo)
{
	var strValidos = "0123456789,";
	LAST_FIELD= campo;

	var valor= new String(campo.value);
	var temVirgula= false;
	for (var i=0; i< valor.length; i++) {
		if (strValidos.indexOf(valor.charAt(i)) == -1) {
			return false;
		} else {
			if (valor.charAt(i) == ",") {
				if (temVirgula) {
					return false;
				}
				temVirgula= true;
			}
		}
	}
	var antes= obtemPartePerc( "antes", campo.value);
	var depois=obtemPartePerc( "depois", campo.value);
    
	if (antes > 100 || antes < 0) { 
		return false;
	}
     
	if (depois > 99 || depois < 0) {
		return false;
	}
	
	if (antes == 100 && depois != 0) {
		return false;
	}

	return true;
}

function validaConteudoPercentOver(campo)
{
	var strValidos = "0123456789,";
	LAST_FIELD= campo;

	var valor= new String(campo.value);
	var temVirgula= false;
	for (var i=0; i< valor.length; i++) {
		if (strValidos.indexOf(valor.charAt(i)) == -1) {
			return false;
		} else {
			if (valor.charAt(i) == ",") {
				if (temVirgula) {
					return false;
				}
				temVirgula= true;
			}
		}
	}
	var antes= obtemPartePerc( "antes", campo.value);
	var depois=obtemPartePerc( "depois", campo.value);
    
	if (antes > 1000 || antes < 0) { 
		return false;
	}
     
	if (depois > 99 || depois < 0) {
		return false;
	}
	
	if (antes == 1000 && depois != 0) {
		return false;
	}

	return true;
}

function validaConteudoPercentInt(campo)
{
	var strValidos = "0123456789,";
	LAST_FIELD = campo;
	var valor = new String(campo.value);        
        
	for (var i=0; i< valor.length; i++) {
		if (strValidos.indexOf(valor.charAt(i)) == -1) {
			return false;
		}
	}
    
	var antes = obtemPartePerc("antes", campo.value);
        
	if (antes > 100 || antes < 0) {
		return false;
	}
        
	return true;
}

function obtemPartePerc( parte, valor)
{
	var posVirg= String(valor).indexOf(",");
	if (posVirg != -1) {
		if (parte == "antes") {
			return parseInt(String(valor).substring(0,posVirg),10);
		} else {
			var depois= String(valor).substring(posVirg+1,valor.length);
			if (depois.length == 1) {
				depois += "0";
			}
			return parseInt( depois,10);
		}
	}else{
		if( parte == "antes") {
			return parseInt( valor,10);
		} else {
			return 0;
		}
	}
}

function formatPercent(campo)
{
	var valor= new String(campo.value);
	LAST_FIELD= campo;

	if( valor == "" || valor == null)
		return;
	if (!validaConteudoPercent(campo)) {
		alert("Você deve digitar um percentual entre \"0,00\" e \"100,00\" \n" +
				"Digite o percentual separado por uma vírgula e sem o sinal \"%\"");
		focusCamp(campo);
		return;
	} else {
		var antes= obtemPartePerc( "antes", campo.value);
		var depois=obtemPartePerc( "depois", campo.value);
		var valorAntes= new String("");
		var valorDepois= new String("");
		if (antes == 100) {
			valorAntes= String(antes);
		} else {
			valorAntes= antes;
		}

		if (depois < 10) {
			valorDepois= "0" + depois;
		} else {
			valorDepois= String(depois);
		}
		
		campo.value = valorAntes + "," + valorDepois;
	}

	return;
}

function formatPercentOver(campo)
{
	var valor= new String(campo.value);
	LAST_FIELD= campo;

	if( valor == "" || valor == null)
		return;
	if (!validaConteudoPercentOver(campo)) {
		alert("Você deve digitar um percentual entre \"0,00\" e \"1000,00\" \n" +
				"Digite o percentual separado por uma vírgula e sem o sinal \"%\"");
		focusCamp(campo);
		return;
	} else {
		var antes= obtemPartePerc( "antes", campo.value);
		var depois=obtemPartePerc( "depois", campo.value);
		var valorAntes= new String("");
		var valorDepois= new String("");
		if (antes == 1000) {
			valorAntes= String(antes);
		} else {
			valorAntes= antes;
		}

		if (depois < 10) {
			valorDepois= "0" + depois;
		} else {
			valorDepois= String(depois);
		}
		
		campo.value = valorAntes + "," + valorDepois;
	}

	return;
}


function formatPercentInt(campo)
{
	var valor= new String(campo.value);
	LAST_FIELD= campo;

	if (valor == "" || valor == null) {
		return;
	}
     
	if (!validaConteudoPercentInt(campo)) {
		alert("Você deve digitar um percentual entre \"0\" e \"99\" \n" +
				"Digite apenas números e sem o sinal \"%\"");
		focusCamp(campo);
		return;
	}
        
	return;
}

function isEmail(email)
{
	return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}

function formatEmail(campo)
{
	var email= new String(campo.value);
	LAST_FIELD= campo;

	if (email == "" || email == null) {
		return;
	}
	
	if (!isEmail(email)) {
		alert("O e-mail \"" + campo.value + "\" não está correto.\n\nPor favor, redigite este campo.");
		focusCamp(campo);
		return;
	}
    
	ERRO= false;
}

function formatText(campo)
{
	var texto= new String(campo.value);
	LAST_FIELD= campo;

	if (texto == "" || texto == null) {
		return;
	}

	if (!isAlfa(texto)) {
		alert("Por favor, digite apenas letras neste campo.");
		focusCamp(campo);
		return;
	}
}

function formatMoney(el)
{
	LAST_FIELD = el;
	el.value = _formatMoney(el.value);
	
	return true;
}

function _formatMoney(value)
{
	var vr = value.replace(/\./g, '');
	tam = vr.length;
	vrtmp = "";
	
	if (vr == "") {
		vrtmp = "";
	} else if ( vr.indexOf(",") == -1 ) {
		vrtmp = vr + ",00";
	} else {
		if ( vr.indexOf(",") == 0 && tam == 2 ) {
			vrtmp = "0" + vr + "0";
		} else if ( vr.indexOf(",") == 0 && tam == 3 ) {
			vrtmp = "0" + vr;
		} else if ( vr.indexOf(",") == (tam-1) ) {
			vrtmp = vr + "00";
		} else if ( vr.indexOf(",") == (tam-2) ) {
			vrtmp = vr + "0";
		} else {
			vraux = vr;
			
			if (vraux.indexOf(",") == 0 && tam >= 3 ) {
				vraux = "0" + vraux;
			}
			
			tamaux = vraux.length;
			posdec = (vraux.indexOf(",")) + 3;
			vrtmp = vraux.substr( 0, posdec ) ;
		}
	}
	
	tamvrtmp = vrtmp.length;
	
	if (tamvrtmp >= 6) {
		tammantissa = vrtmp.indexOf(",");
		vrdec=vrtmp.substr( tammantissa, 3 );
		vraux = "";
		
		for ( i = tammantissa; i > 0; i--) {
			caracter = vrtmp.substring( i, i-1 );
			tamaux = i - tammantissa;
			
			if ( i != tammantissa && (tamaux/3 == parseInt( tamaux/3 ) ) ) {
				vraux += ".";
			}
			
			vraux += caracter;
		}
		
		vrfinal = "";
		tamvrfinal = vraux.length;
		
		for ( i = tamvrfinal; i > 0; i-- ) {
			caracter = vraux.substring( i, i-1 );
			vrfinal += caracter;
		}
		
		return vrfinal + vrdec;
	} else {
		return vrtmp;
	}
}


//formataçcao de money para n casas decimais
function formatMoney3(el)
{
  
  vr = el.value.replace(/\./g, '');
  tam = vr.length;
  vrtmp = "";
  LAST_FIELD= el;

  if ( vr == "" )
  {
    vrtmp = "";
  }

  else if ( vr.indexOf(",") == -1 )
  {
    vrtmp = vr + ",000";
 	
  }
  else
  {
    if ( vr.indexOf(",") == 0 && tam == 2 )
    {
      vrtmp = "0" + vr + "0";
      
     }
    else if ( vr.indexOf(",") == 0 && tam == 3 )
    {
      vrtmp = "00" + vr;
      
    }
    else if ( vr.indexOf(",") == (tam-1) )
    {
      vrtmp = vr + "000";
     
    }
    else if ( vr.indexOf(",") == (tam-2) )
    {
      vrtmp = vr + "00";
     
     }
    else
    {
      vraux = vr;
      if ( vraux.indexOf(",") == 0 && tam >= 3 )
        vraux = "0" + vraux;
      tamaux = vraux.length;
      posdec = (vraux.indexOf(",")) + 4;
      vrtmp = vraux.substr( 0, posdec ) ;
      
    }
  }
  
  tamvrtmp = vrtmp.length;
  if ( tamvrtmp >= 6 )
  {
    tammantissa = vrtmp.indexOf(",");
    vrdec=vrtmp.substr( tammantissa, 4 );
      
    vraux = "";
    for ( i = tammantissa; i > 0; i--)
    {
      caracter = vrtmp.substring( i, i-1 );
      tamaux = i - tammantissa;
      if ( i != tammantissa && (tamaux/3 == parseInt( tamaux/3 ) ) )
        vraux += ".";
      vraux += caracter;
    }
    vrfinal = "";
    tamvrfinal = vraux.length;
    for ( i = tamvrfinal; i > 0; i-- )
    {
      caracter = vraux.substring( i, i-1 );
      vrfinal += caracter;
    }
    el.value = vrfinal + vrdec;
  
  }
  else
    el.value = vrtmp;
    
    
  return true;
}


function formatCPF(campo)
{
        var valor= new String(campo.value);
        LAST_FIELD= campo;

        if( valor == "" ||  valor == null)
                return;
        if(  !isCPF(valor) )
        {
                alert('CPF inválido.\nPor favor, preencha-o novamente.');
                focusCamp(campo);
                return;
        }else{
                var temp= new String("");
                var x1 = valor;
        
				x1 = x1.replace(/\./g,"");
		       	x1 = x1.replace(/-/g,"");
		        x1 = x1.replace(/\//g,"");
		        
                temp= x1.substring(0,3) + "." + x1.substring(3,6) + "." + x1.substring(6,9) + "-" + x1.substring(9,11)
                campo.value= temp;
        }
}

function formatCNPJ(campo)
{
        var valor= new String(campo.value);


        LAST_FIELD= campo;

        if( valor == "" ||  valor == null) {
           return false;
        } else if (valor == '00000000000000') {
           alert('CNPJ inválido.\nPor favor, preencha-o novamente.');
           focusCamp(campo);
           return false;
        }
        
        var x1 = valor;
        
		x1 = x1.replace(/\./g,"");
       	x1 = x1.replace(/-/g,"");
        x1 = x1.replace(/\//g,"");
        
        var x = '';
        x = x1.substring(0,2);
        x += "." + x1.substr(2,3);
        x += "." + x1.substr(5,3);
        x += "/" +x1.substr(8,4);
        x += "-" +x1.substr(12,2);

        if( ! validaCNPJ(x) ) {
           alert('CNPJ inválido.\nPor favor, preencha-o novamente.');
           focusCamp(campo);
           return false;
        } else {
           campo.value= x;
           return true;
        }
}


function formatHoraCurta(campo) {
        var valor= new String(campo.value);

        if( valor == "" ||  valor == null)
                return;

        var hora = valor.substring(0,2);
        var minuto = valor.substring(2,4);

        if ((parseInt(hora+minuto) > 2400) || (parseInt(minuto) > 59) || (! validaNumerico(valor) ) || ( valor.length != 4) ) {
           alert('Hora inválida.\nPor favor, preencha novamente.');
           focusCamp(campo);
           return;

        }else{
           if ( parseInt(hora) == 24 ) {
             hora = "00";
           }
           var temp= new String("");
           temp= hora + ":" + minuto;
           campo.value= temp;
        }
}

function formatHora(campo) {
        var valor= new String(campo.value);

        if( valor == "" ||  valor == null)
                return;

        var hora = valor.substring(0,2);
        var minuto = valor.substring(2,4);
        var segundo = valor.substring(4,6);

        if ((parseInt(hora+minuto+segundo) > 240000) || (parseInt(minuto) > 59) || (parseInt(segundo) > 59) || (! validaNumerico(valor) ) || ( valor.length != 6) ) {
           alert('Hora inválida.\nPor favor, preencha novamente.');
           focusCamp(campo);
           return;

        } else{

           if ( parseInt(hora) == 24 ) {
              hora = "00";
           }

           var temp= new String("");
           temp= hora + ":" + minuto + ":" + segundo;
           campo.value= temp;
        }
}

function validaCNPJ(valor) {
   CNPJ = valor;
   erro = new String;
   if ( (CNPJ.length < 18) && (CNPJ.length > 0) ) {
     erro += "CNPJ inválido! \n\n";
   }

   if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
           if (erro.length == 0) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
   }

   if(document.layers && parseInt(navigator.appVersion) == 4){
           x = CNPJ.substring(0,2);
           x += CNPJ.substring(3,6);
           x += CNPJ.substring(7,10);
           x += CNPJ.substring(11,15);
           x += CNPJ.substring(16,18);
           CNPJ = x;
   } else {
           CNPJ = CNPJ.replace(/\./g,"");
           CNPJ = CNPJ.replace(/-/g,"");
           CNPJ = CNPJ.replace(/\//g,"");
   }


   var nonNumbers = /\D/;
   if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n";
   var a = [];
   var b = new Number;
   var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
   for (i=0; i<12; i++){
           a[i] = CNPJ.charAt(i);
           b += a[i] * c[i+1];
   }
   if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
   b = 0;
   for (y=0; y<13; y++) {
           b += (a[y] * c[y]);
   }
   if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
   if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
           erro +="Digito verificador com problema!";
   }
   if (erro.length > 0){
           return false;
   }
   return true;
}

function AutoSkip(NomeCampo)
{
	
	for (i = 0; i < document.forms[NR_FORM].elements.length; i++) {
		if (NomeCampo == document.forms[NR_FORM].elements[i].name)
			break;
	}
	
	
	if(typeof(document.forms[NR_FORM].elements[(i + 1)]) == "undefined") {
		document.forms[NR_FORM].elements[i].blur();
		return true;
	}
	
	var j = 0;
	while (document.forms[NR_FORM].elements[(i + 1)].type == "hidden" ) {
		i++;
		j++;
		
		if (i == document.forms[NR_FORM].elements.length - 1) {
			i = 0;
		}
		
		if (j > 200) {
			break;
		}
	}
	
	try {
		document.forms[NR_FORM].elements[(i + 1)].focus();
		return true;
	} catch (e) {
		try {
			document.getElementsByName(document.forms[NR_FORM].elements[(i + 1)].name).focus();
			return true;
		} catch (Exception) {
			return false;
		}
	}
}

function autoFocus()
{
	var tipo= "";

	for (i=0; i < document.forms[NR_FORM].elements.length; i++) {
		tipo= document.forms[NR_FORM].elements[i].type;
		if (tipo == 'text' || tipo == 'password' || tipo == 'select-one') {
			document.forms[NR_FORM].elements[i].focus();
			break;
		}
	}
    
	return;
}

//--------------------------------------------------------------------------
//-- focusCamp( <componente> )
//-- Devido a problemas ocorridos com o Netscape, neste browser e' feita a
//-- limpeza do campo em vez da setagem de seu foco
//--------------------------------------------------------------------------
function focusCamp(campo)
{
	if (navigator.appName.indexOf("Netscape") != -1) {  
		campo.value = "";
	} else {
		campo.focus();
	}
    
	ERRO = true;
}
//--------------------------------------------------------------------------//

function formatCamp(campo, tipo)
{
	var retorno = true;
	
	if( tipo == "account")
		retorno = formatAccount(campo);
	else if( tipo == "branch")
		retorno = formatBranch(campo);
	else if( tipo == "ag_account")
		retorno = formatAg_Account(campo);
	else if( tipo == "cpf")
		retorno = formatCPF(campo);
	else if( tipo == "cnpj")
		retorno = formatCNPJ(campo);
	else if( tipo == "date")
		retorno = formatDate( campo);
	else if( tipo == "money")
		retorno = formatMoney(campo);
	else if( tipo == "money3")
		retorno = formatMoney3(campo);
	else if( tipo == "numeric")
		retorno = formatNumeric(campo);
	else if( tipo == "cep")
		retorno = formatCEP(campo);
	else if( tipo == "email")
		retorno = formatEmail(campo);
	else if( tipo == "percent")
		retorno = formatPercent(campo);
	else if( tipo == "percent_int")
		retorno = formatPercentInt(campo);
	else if( tipo == "percent_over")
		retorno = formatPercentOver(campo);
	else if( tipo == "text")
		retorno = formatText(campo);
	else if( tipo == "periodo")
		retorno = formatPeriodo(campo);
	else if( tipo == "telefone")
		retorno = formatTelefone(campo);
	else if( tipo == "telefoneResidencial")
		retorno = formatTelefoneResidencial(campo);
	else if( tipo == "telefoneCelular")
		retorno = formatTelefoneCelular(campo);
	else if( tipo == "aniversariante")
		retorno = formatAniversariante(campo);
	else if( tipo == "short_time")
		retorno = formatHoraCurta(campo);
	else if( tipo == "time")
		retorno = formatHora(campo);
	else
		alert( "Tipo passado para formatação é inválido: " + tipo);
		
	return retorno;
}

//-------------------------------------------------------------------------
//FUNCAO QUE FAZ O "SALTO" DO CAMPO
//DEVE SER PASSADO O NOME DO PROXIMO CAMPO QUANDO FOR NECESSARIO SALTAR
//CASO NAO PRECISE, ESTE ULTIMO PARAMETRO PODE SER OMITIDO
// Autor: Luciano M. Ribas (HSBC E-Publishing)
//-------------------------------------------------------------------------
// Alterada em     : 18/08/2000
// Realizada por   : Luciano M. Ribas
// Modificacao     : Campo money pode ter tamanho definido pelo usuario
// Modificacao     : Inclusao do campo text
//-------------------------------------------------------------------------
function saltaCampo(evento,el,tipo,tamanho)
{
	var tecla;
	var maxSize;
	var fieldSize;
	switch(tipo) {
		case "date":
			maxSize = SIZE_DATE;
			break;
		case "cpf":
			maxSize = SIZE_CPF;
			break;
		case "cnpj":
		
			maxSize = SIZE_CNPJ;
			break;
		case "cep":
			maxSize = SIZE_CEP;
			break;
		case "numeric":
			maxSize = tamanho;
			break;
		case "email":
			maxSize = tamanho;
			break;
		case "money":
			if(saltaCampo.arguments.length > 3)
				maxSize = tamanho;
			else
				maxSize = SIZE_MONEY;
			break;
		case "account":
			maxSize = SIZE_ACCOUNT;
			break;
		case "branch":
			maxSize = SIZE_BRANCH;
			break;
		case "percent":
			maxSize = SIZE_PERCENT;
			break;
		case "percent_over":
			maxSize = SIZE_PERCENT_OVER;
			break;
		case "percent_int":
			maxSize = SIZE_PERCENT_INT;
			break;
		case "ag_account":
			maxSize = SIZE_AG_ACCOUNT;
			break;
		case "text":
			maxSize = tamanho;
			break;
		case "short_time":
			maxSize = tamanho;
			break;
		case "time":
			maxSize = tamanho;
			break;
		case "text":
			maxSize = tamanho;
			break;
		case "default":
			maxSize= tamanho;
	}

	(isNav) ? tecla = evento.which : tecla = evento.keyCode;

	fieldSize = String(el.value).length;
	if (el != '') {
		if (fieldSize >= maxSize && tecla >= 48)
			if (!AutoSkip(el.name)) {
				el.blur();
			}
	}
}
