//---------------------------------------------------------------------------//
//  validate.js
//  - Biblioteca necessaria para consistencia padrao de campos
//  Autor: Luciano M. Ribas
// Colaborador: Anderson Cesconeto
//---------------------------------------------------------------------------//

var ERRO= false;
var LAST_FIELD;

///////////////////////////////////////////////////////////////////////////////
//CONSTANTES UTILIZADAS
///////////////////////////////////////////////////////////////////////////////
SIZE_DATE = 8;
SIZE_CEP = 8
SIZE_ACCOUNT = 7;
SIZE_AG_ACCOUNT = 11;
MAX_NUMERIC = Number.MAX_VALUE; //Este não vai ser usado, mas só pra saber !!!
SIZE_MONEY = 10; //9999999.99
SIZE_CPF =11;
SIZE_PERCENT =6;
SIZE_BRANCH =4;
///////////////////////////////////////////////////////////////////////////////
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;
}

function isAlfa( value)
{
        var expr= new RegExp("[A-Za-z ]+");
        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);
        //document.captureEvents(Event.KEYDOWN);  (Dá' erro no Windows 9x)
}
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;
  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{  // todos os outros tipos só aceitam números
     return validaNumerico(key);
  }
}

function debug(msg)
{
        document.forms[0]._07_mensagem.value+="\n" + msg ;
}

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 != ')');
                else
                        ok= isAlfa( caracter);

                if( ok)
                        wrkCampo += caracter;
        }
        Campo.value = wrkCampo;
        focusNetscape(Campo);
}

function focusNetscape( campo)
{
        if( navigator.appName.indexOf("Netscape") != -1)
        {
                if( ERRO )
                {
                        //debug( "focara' em: " + LAST_FIELD.name );
                        LAST_FIELD.focus(); //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: 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 valor= new String(el.value);
        valor = "01" + valor;
        LAST_FIELD= el;

        if( !validaNumerico(valor))
        {
                alert("Você deve digitar o período utilizando apenas números.\n" +
                                "Utilize 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;
                //minimo 6, maximo 10
                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++;
                                        }
                                        //alert("numero: " + str);
                                        token[j] = str;
                                        j++;
                                        nDig++;
                                }else
                                if (vr.substring(i, i+1) == "/"){
                                        str = "" + vr.substring(i, i+1);
                                        token[j] = str;
                                        j++;
                                        i++;
                                        nBar++;

                                        //alert("barra: " + str);
                                }
                                else{
                                        //alert("caracter desconhecido: " + vr.substring(i, i+1));
                                        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)){
                                //alert("numero de tokens: " + token.length);

                                if (token.length == 1){ //um token de tamanho minimo 6, maximo 8
                                        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);

                                        //alert(dia + "/" + mes + "/" + ano);
                                        el.value = dia + "/" + mes + "/" + ano;
                                }else
                                if (token.length == 5){ //5 tokens indicam data no formato dd/mm/aa
                                        if (token[0].length == 1 && eval(token[0]) < 10)
                                                dia = "0" + token[0];
                                        else
                                                //pega os dois primeiros digitos e ignora o restante se houver
                                                dia = token[0].substring(0, 2);
                                        barra1 = token[1]; //pega barra
                                        if (token[2].length == 1 && eval(token[2]) < 10)
                                                mes = "0" + token[2];
                                        else
                                                //pega os dois primeiros digitos e ignora o restante se houver
                                                mes = token[2].substring(0, 2);

                                        barra2 = token[3]; //pega barra

                                        if (token[4].length == 2){
                                                if (eval(token[4]) < 30)
                                                        ano = "20" + token[4];
                                                else
                                                        ano = "19" + token[4];
                                        }
                                        else
                                                ano = token[4];

                                        //alert(dia + barra1 + mes + barra2 + ano);

                                        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); // day
                        barra1 = a.substring(2, 3); // '/'
                        mes = a.substring(3, 5); // month
                        barra2 = a.substring(5, 6); // '/'
                        ano = a.substring(6, 10); // year

                        //basic error checking
                        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){
                                //advanced error checking
                                // months with 30 days
                                if (dia == 31) err=4
                        }
                        if (mes == 2){
                                // february, leap year
                                // feb
                                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 = el.value.substring(3, 10);
                        alert('Período Inválido');
                        nome = el.name;
                        focusCamp(el);
                        return;
                }
                else {
                        nome = "";
                        el.value = el.value.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;
        }

        if (nome == "" || el.name == nome){
                vr = el.value;
                //minimo 6, maximo 10
                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++;
                                        }
                                        //alert("numero: " + str);
                                        token[j] = str;
                                        j++;
                                        nDig++;
                                }else
                                if (vr.substring(i, i+1) == "/"){
                                        str = "" + vr.substring(i, i+1);
                                        token[j] = str;
                                        j++;
                                        i++;
                                        nBar++;

                                        //alert("barra: " + str);
                                }
                                else{
                                        //alert("caracter desconhecido: " + vr.substring(i, i+1));
                                        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)){
                                //alert("numero de tokens: " + token.length);

                                if (token.length == 1){ //um token de tamanho minimo 6, maximo 8
                                        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);

                                        //alert(dia + "/" + mes + "/" + ano);
                                        el.value = dia + "/" + mes + "/" + ano;
                                }else
                                if (token.length == 5){ //5 tokens indicam data no formato dd/mm/aa
                                        if (token[0].length == 1 && eval(token[0]) < 10)
                                                dia = "0" + token[0];
                                        else
                                                //pega os dois primeiros digitos e ignora o restante se houver
                                                dia = token[0].substring(0, 2);
                                        barra1 = token[1]; //pega barra
                                        if (token[2].length == 1 && eval(token[2]) < 10)
                                                mes = "0" + token[2];
                                        else
                                                //pega os dois primeiros digitos e ignora o restante se houver
                                                mes = token[2].substring(0, 2);

                                        barra2 = token[3]; //pega barra

                                        if (token[4].length == 2){
                                                if (eval(token[4]) < 30)
                                                        ano = "20" + token[4];
                                                else
                                                        ano = "19" + token[4];
                                        }
                                        else
                                                ano = token[4];

                                        //alert(dia + barra1 + mes + barra2 + ano);

                                        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); // day
                        barra1 = a.substring(2, 3); // '/'
                        mes = a.substring(3, 5); // month
                        barra2 = a.substring(5, 6); // '/'
                        ano = a.substring(6, 10); // year

                        //basic error checking
                        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){
                                //advanced error checking
                                // months with 30 days
                                if (dia == 31) err=4
                        }
                        if (mes == 2){
                                // february, leap year
                                // feb
                                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;
                }
                else
                        nome = "";
        }
        ERRO= false;
}
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= new String(campo.value);
        LAST_FIELD= campo;

        if( valor == "" || valor == null)
                return;
        if( !validaNumerico(campo.value))
        {
                alert("Você deve digitar o CEP utilizando apenas números.\n" +
                                "Por favor, redigite-o novamente.");
                focusCamp(campo);
                return;
        }else{
                var temp= valor.substring(0,5) + "-" + valor.substring(5,8);
                campo.value= temp;
        }
        ERRO= false;
        return;
}

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)
                {
                        //alert('Erro: ' + valor.charAt(i))
                        return false;
                }else{
                        if( valor.charAt(i) == ",")
                        {
                                if( temVirgula)
                                {
                                        //alert('Erro: ' + valor.charAt(i))
                                        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 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) // Apenas um digito depois da virgula?
                                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 \"000,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= "0" + antes;
                else
                        valorAntes= String(antes);
                if( depois < 10)
                        valorDepois= "0" + depois;
                else
                        valorDepois= String(depois);
                campo.value = valorAntes + "," + valorDepois + "%";
        }
        return;
}

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)
{
  vr = el.value;
  tam = vr.length;
  vrtmp = "";
  LAST_FIELD= el;

  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;
    }
    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("");
                temp= valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,9) + "-" + valor.substring(9,11)
                campo.value= temp;
        }
}

function AutoSkip( NomeCampo )
{
        for(i=0; i < document.forms[0].elements.length; i++)
        {
                if ( NomeCampo == document.forms[0].elements[i].name )
                break;
        }
        if( ( typeof document.forms[0].elements[i+1]) == "undefined")
        {
                document.forms[0].elements[i].blur();
                return;
        }
        while ( document.forms[0].elements[i+1].type == "hidden" )
        {
                i = i +1;
                if ( i == document.forms[0].elements.length - 1)
                i = 0;
        }
        document.forms[0].elements[i+1].focus();
        return;
}

function autoFocus()
{
        var tipo= "";
        for(i=0; i < document.forms[0].elements.length; i++)
        {
                tipo= document.forms[0].elements[i].type;
                if(  tipo == 'text' || tipo == 'password' || tipo == 'select-one')
                {
                        document.forms[0].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)  // E' Netscape?
        {
                campo.value= "";
        }else{
                campo.focus();
        }
        ERRO= true;
}
//--------------------------------------------------------------------------//

function formatCamp(campo, tipo)
{
        if( tipo == "account")
                formatAccount(campo);
        else if( tipo == "branch")
                formatBranch(campo);
        else if( tipo == "ag_account")
                formatAg_Account(campo);
        else if( tipo == "cpf")
                formatCPF(campo);
        else if( tipo == "date")
                formatDate( campo);
        else if( tipo == "money")
                formatMoney(campo);
        else if( tipo == "numeric")
                formatNumeric(campo);
        else if( tipo == "cep")
                formatCEP(campo);
        else if( tipo == "email")
                formatEmail(campo);
        else if( tipo == "percent")
                formatPercent(campo);
        else if( tipo == "text")
                formatText(campo);
        else if( tipo == "periodo")
                formatPeriodo(campo);
        else if( tipo == "telefone")
                formatTelefone(campo);
        else
                alert( "Tipo passado para formatação é inválido: " + tipo);
}

//-------------------------------------------------------------------------
//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 "cep":                 maxSize=SIZE_CEP;         break;
                case "numeric":        maxSize= tamanho;         break;
                case "email":                maxSize= tamanho;         break;
                case "money":
                        if( saltaCampo.arguments.length > 3)  // Tamanho foi informado?
                                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 "ag_account": maxSize=SIZE_AG_ACCOUNT; break;
                case "text":                maxSize= tamanho;     break;
                case "default":        maxSize= tamanho;
        }
        (isNav)?tecla = evento.which:tecla = evento.keyCode;
        fieldSize=String(el.value).length;
        if ( fieldSize >= maxSize && tecla >= 48 )
                AutoSkip(el.name);
}
