
/*-----------------------------------------------------------------*
 Focus_Link
 Descricao : Foca no link n determinado pelo item(n), o primeiro link
             da página é o 0
 Parametros: n - integer indice do item(link) a ser focado , o primeiro é o zero.
 *-----------------------------------------------------------------*/
function Focus_Link(n)
{
   if (navigator.appName.substring(0,9) == "Microsoft")
   {
      if ('<% = Mid(Request.ServerVariables("HTTP_USER_AGENT"),31,1) %>' >= '5' )
      {
         document.links.item(n).focus();
      }
   }
}

/*-----------------------------------------------------------------*
 CompletaZeros
 Descricao : Completa um dado numerico com zeros à esquerda
 Parametros: sNum - string com números   iTam - tamanho total da string
 *-----------------------------------------------------------------*/
function CompletaZeros (sNum, iTam)
{
    var num, str;

    if (!IsNumber (sNum)) sNum = '0';
    num = sNum - 0;
    str = "000000000000000000000" + num;
    return str.substring (str.length - iTam, str.length);
}


/*-----------------------------------------------------------------*
  IsNumber
  Descricao   : Verifica se e' um numero
  Parametros  : Numero que contém dígitos de 0 a 9
  Atualizacoes: [00] Versao Inicial    Data: 19/07/2000     Autor: Fabrica
 *-----------------------------------------------------------------*/
function IsNumber (Numero)
{
   var i;
   if (Numero == "")
      return false;
   for (i=0; i < Numero.length; i++)
   {
      if (Numero.charAt(i) < "0" || Numero.charAt(i) > "9")
         return false;
   }
   return true;
}

/*-----------------------------------------------------------------*
  Descricao   : Tira brancos à esquerda e à direita
  Atualizacoes: [00] Versao Inicial    Data: 19/07/2000     Autor: Fabrica
 *-----------------------------------------------------------------*/
function Trim(s)
{
    return s.replace (/^\s+/,'').replace (/\s+$/,'');
}

/*-----------------------------------------------------------------*
 Nome........: VerificaCPFCNPJ
 Descricao...: Verifica se é nunero de CPF ou CNPJ válido.
               Verificamos se o digitado está correto de acordo com seus dígitos verificadores
 Paramentros.: txtcpfcgc: CPF ou CNPJ a ser testado sem a formatacao de / e -
 Retorno.....: sRetorno: true (ok) ou false (nok)
 Atualizacoes: [00] Versao Inicial     Data: 08/02/2000     Autor: Fabrica Software
 *-----------------------------------------------------------------*/
function fVerificaCPFCNPJ (txtCpfCgc, iTipo)
{

   var sAux, iTam;

   sAux = txtCpfCgc;

   //-- Tamanho da string sem o digito verificador
   iTam = sAux.length - 2;

   if (sAux.length <= 1)
      return false;

   if (fValidaDV (sAux.substring (0, iTam) ,iTipo) != sAux.substring (sAux.length-2, sAux.length))
      return false;

   if (iTipo == 1)
      if ( (sAux.substring(0,1) == sAux.substring(1,2)) && (sAux.substring(2,3) == sAux.substring(3,4)) && (sAux.substring(3,4) == sAux.substring(4,5)) && (sAux.substring(4,5) == sAux.substring(5,6)) && (sAux.substring(5,6) == sAux.substring(6,7)) && (sAux.substring(6,7) == sAux.substring(7,8)) && (sAux.substring(7,8) == sAux.substring(8,9)) && (sAux.substring(9,10) == sAux.substring(10,11)) )
      return false;

   return true;
}

/*-----------------------------------------------------------------*
 Nome........: fValidaDV
 Descricao...: Verifica se o dígito verificador do CPF/CGC está correto
 Paramentros.: iValor: Valor do CPF/CGC
               sTipoValidacao: 1 -> CPF; 2 -> CGC
 Retorno.....: sAux: sString contendo apenas os números
 Atualizacoes: [00] Versao Inicial     Data: 08/02/2000     Autor: AlexandreQ - 7Comm
 *-----------------------------------------------------------------*/
function fValidaDV(iValor,sTipoValidacao)
{
   var iCont1,iCont2,iSoma=0,iMult,iLimiteMult
   if (sTipoValidacao==1) iLimiteMult = 12
   if (sTipoValidacao==2) iLimiteMult = 9
   for (iCont1 = 1; iCont1<=2; iCont1++)
   {
      iSoma = 0;
      iMult = 2;
      for (iCont2 = iValor.length; iCont2>=1; iCont2--)
      {
         iSoma = iSoma + (iMult * (iValor.substring(iCont2-1,iCont2)*1));
         iMult++;
         if (iMult > iLimiteMult)
            iMult = 2;
      }
      iValor = iValor + (((iSoma * 10) % 11) % 10);
   }
   return (iValor.substring(iValor.length-2,iValor.length));
}

/*-----------------------------------------------------------------*
 Nome........: fFormataCPFCGC
 Descricao...: Formata o CPF/CGC passado
 Paramentros.: sNumero: Valor do CPF/CGC
               iTipo: 1 -> CPF; 2 -> CGC
 Retorno.....: sRetorno: sString contendo o CPF/CGC formatado
 Atualizacoes: [00] Versao Inicial     Data: 08/02/2000     Autor: AlexandreQ - 7Comm
 *-----------------------------------------------------------------*/
function fFormataCPFCGC(sNumero,iTipo)
{
   var sRetorno = ""
   if (iTipo == 1) // CPF
   {
      for (iCont=0; iCont<sNumero.length; iCont++)
      {
         if (iCont == 3 || iCont == 6)
            sRetorno = sRetorno + "."
         if (iCont == 9)
            sRetorno = sRetorno + "-"
         sRetorno = sRetorno + sNumero.charAt(iCont)
      }
   }
   else //CGC
   {
      for (iCont=0; iCont<sNumero.length; iCont++)
      {
         if (iCont == 2 || iCont == 5)
            sRetorno = sRetorno + "."
         if (iCont == 8)
            sRetorno = sRetorno + "/"
         if (iCont == 12)
            sRetorno = sRetorno + "-"
         sRetorno = sRetorno + sNumero.charAt(iCont)
      }
   }
   return (sRetorno)
}

/*-----------------------------------------------------------------------------------------*
 Nome........: ChecaEmail
 Descricao...: Verifica se o E-mail é válido
 Paramentros.: email: String de E-mail
 Retorno.....: true(ok) ou false(nok)
 Atualizacoes: [00] Versao Inicial     Data: 18/05/2001     Autor: Waldyr De Paiva - Fábrica
 *-----------------------------------------------------------------------------------------*/
function ChecaEmail(email)
{
   var aux;
   //checando se a string não é vazia
   if((email.replace (/^\s+/,'').replace (/\s+$/,'') == ""))
   {
      return false;
   }
   //checando se existe pelo menos uma arroba e pelo menos algum ponto
   if((email.indexOf("@") == -1)||(email.indexOf(".") == -1))
   {
      return false;
   }
   //checando se a string tem pelo menos 5 caracteres
   if(email.length<5)
   {
      return false
   }
   //checando se existe brancos
   if(email.indexOf(" ") != -1)
   {
      return false;
   }
   //checando se depois de . não tem outra @, ou um ponto ou espaço
   if((email.substr(email.lastIndexOf(".")+1,1) == "")||(email.substr(email.indexOf(".")+1,1) == "@")||(email.substr(email.indexOf(".")+1,1) == "."))
   {
      return false;
   }
   //checando se depois de @ não tem outra @, ou um ponto ou espaço
   if((email.substr(email.lastIndexOf("@")+1,1) == "")||(email.substr(email.indexOf("@")+1,1) == "@")||(email.substr(email.indexOf("@")+1,1) == "."))
   {
      return false;
   }
   //procurando por mais de uma @
   aux = email.substr(email.indexOf("@")+1);
   if(aux.indexOf("@") != -1)
   {
      return false
   }
   //checando se o primeiro caracter é @
   if(email.substr(0, 1) == "@")
   {
      return false
   }
   return true
}

/*-----------------------------------------------------------------------------------------*
     Funções que permitem o salto dos campos no fim da digitaçã
 *-----------------------------------------------------------------------------------------*/
var bPula = false;   // indica que o campo não possui o foco

function fAtuPulaBlur()
{
   bPula = false;
}

function fPulaCampo( Campo1, Campo2, iTam )
{
   if (bPula)
      if (Campo1.value.length >= iTam)
         Campo2.focus();

   return;
}

function fAtuPulaKeyPress ()
{
   bPula = true;
   return;
}

function fVerificaEnter( Funcao )
{
   if (window.event.keyCode == 13)
   {
      window.event.keyCode = 0;
      eval( Funcao );
   }
}

function sCalculaDigitoMod11(sValor,iDigSaida,sTipoValidacao)
{
  if (sTipoValidacao == 1) iCod = 12
  if (sTipoValidacao == 2) iCod = 9

  for (t=1;t<=iDigSaida;t++)
    {
      soma = 0
      mult = 2
      for (j=sValor.length;j>0;j--)
      {
   soma = soma + (mult * parseInt(sValor.substring(j,j-1),10))
   mult++
   if (mult > iCod) mult = 2
      }
      soma = (soma * 10) % 11
      if (soma == 10) sValor = sValor + "0"
      else sValor = sValor + soma
    }
  return sValor.substring(sValor.length-iDigSaida,sValor.length)
}


var combosVisiveis = true;

function ShowCombos(estado) {

        var i;
        var obj;
        var elmID = "SELECT";

        for (i = 0; i < window.document.all.tags(elmID).length; i++) {

            obj = window.document.all.tags(elmID)[i];
            if (! obj || ! obj.offsetParent) {
                continue;
            }
            if (estado) {
                obj.style.visibility = "";
                combosVisiveis = true;
            } else {
                if (obj.name != "Navegue") obj.style.visibility = "hidden";
                combosVisiveis = false;
            }
        }

}

function ClearMenu() {

    ShowCombos(true);
    for (var i = 1; i <= 5; i++) {
        ShowDiv("Menu" + i, false);
    }
}

/*-----------------------------------------------------------------*
 | FiltraTexto       Retorna a String dada, trocando os caracteres |
 |                   acentuados e transformando em maiúsculo.      |
 *-----------------------------------------------------------------*/
function FiltraTexto(Dado) {

   var r = ''
   var asc1 = new String()
   var asc2 = new String()
   asc1 = 'áàãäâÁÀÃÄÂéèêëÉÈÊËìíîïÌÍÎÏòóôõöÒÓÔÕÖùúûüÙÚÛÜýÝçÇñÑ'
   asc2 = 'AAAAAAAAAAEEEEEEEEIIIIIIIIOOOOOOOOOOUUUUUUUUYYCCNN'
   for(i=0;i<=Dado.length-1;i++)
       {
      c = Dado.charAt(i)
      for(j=0;j<=asc1.length-1;j++)
      if(Dado.charAt(i) == asc1.charAt(j))
         c = asc2.charAt(j)
         if((c<'0' || c>'9') && (c<'A' || c>'Z') && (c<'a' || c>'z') && (c != ' ') && (c != ',') && (c != '.') && (c != '/'))
         {
         return "";
         }
         r = r + c
      }

   return r.toUpperCase();
}

/*-----------------------------------------------------------------*
 | ValidaDominio   Retorna true somente se a String contiver os    |
 |                 caracteres do domínio dado, senão retorna false.|
 *-----------------------------------------------------------------*/
function ValidaDominio(strDado, dominio) {
    var i, j, c;
    strDado = strDado.toUpperCase();
    if (strDado.length > 0) {
        for (i = 0; i < strDado.length; i++) {
            c = strDado.substr(i,1);
            for (j = 0; j < dominio.length; j++) {
                if (c == dominio.substr(j,1)) break;
            }
            if (j >= dominio.length) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

/*-----------------------------------------------------------------*
 | ValidaTexto     Retorna true somente se a String contiver os    |
 |                 caracteres do domínio dado respeitando o tipo   |
 |                 informado, senão retorna false.                 |
 *-----------------------------------------------------------------*/
function ValidaTexto(strDado, tipo) {

    if (tipo == "T") {
        return ValidaDominio(strDado, "ABCDEFGHIJKLMNOPQRSTUVYZXW ");
    } else if (tipo == "N") {
        return ValidaDominio(strDado, "0123456789");
    } else if (tipo == "TN") {
        return ValidaDominio(strDado, "ABCDEFGHIJKLMNOPQRSTUVYZXW0123456789 ");
    } else {
        return false;
    }
}

/*-----------------------------------------------------------------*
 | isNumber      Retorna True se o String dada for um número      |
 |                com casas decimais dadas.                        |
 *-----------------------------------------------------------------*/
function isNumberVA(sNumero, iDecimais) {
  var bRet
  var i
  bRet = true
  if (iDecimais > 0)
    {
    if ((sNumero.length < iDecimais + 2) || (sNumero.indexOf(",", 0) == -1))
      bRet = false
    }
  if (bRet)
    {
    i = 0
    while(i < sNumero.length && bRet)
      {
      if (iDecimais > 0)
        {
        if (i == sNumero.length - (iDecimais + 1))
          {
          if (sNumero.charAt(i) != ",")
            bRet = false
          }
        else
          {
          if (sNumero.charAt(i) < "0" || sNumero.charAt(i) > "9")
            bRet = false
          }
        }
      else
        {
        if (sNumero.charAt(i) < "0" || sNumero.charAt(i) > "9")
          bRet = false
        }
      i++
      }
    }
  return bRet
}

/*-----------------------------------------------------------------------------
 Nome:      fPassaAlfaNumerico(strTipo)
 Data:      07/05/2004
 Autor:     Fábrica de Software - Renato C. Castelo
 Descrição: Não deixa o usuário digitar caracteres especiais, somente letras,
            números e espaço, e não tira a funcionalidade das demais teclas
            (Caps Lock, Shift, Tab, ...).
            Teclas: 33 - 47    ! " # $ % & ' ( ) * + , - . /
                    58 - 64    : ; < = > ? @
                    91 - 96    [ \ ] ^ _ `
                    123 ...    { | } ~ ...
            A função deve estar no evento OnKeyPress.
 Parâmetro: strTipo
            "a" => letras e espaços
            "n" => números
            diferente de "a" e "n"  => letras, números e espaços
 Atualizações:
   Data:      11/05/2004
   Autor:     Fábrica de Software - Renato C. Castelo
   Descrição: Incluído parâmetro strTipo. Valida de acordo com o tipo
              informado.
-----------------------------------------------------------------------------*/
function fPassaAlfaNumerico(strTipo) {
    if ( ( (event.keyCode >= 33 ) && (event.keyCode <= 47 ) ) ||
         ( (event.keyCode >= 58 ) && (event.keyCode <= 64 ) ) ||
         ( (event.keyCode >= 91 ) && (event.keyCode <= 96 ) ) ||
         ( (event.keyCode >= 123)                           ) ) {
        event.returnValue = 0;
    }
    //-- Letras
    if( (strTipo == "a") || (strTipo == "A") ) {
        if ( (event.keyCode >= 48 ) && (event.keyCode <= 57 ) ) {
            event.returnValue = 0;
        }
    }
    //-- Números
    if( (strTipo == "n") || (strTipo == "N") ) {
        if ( ( (event.keyCode >= 65 ) && (event.keyCode <= 90 ) ) ||
             ( (event.keyCode >= 97 ) && (event.keyCode <= 122) ) ||
             ( (event.keyCode == 32 )                           ) ) {
            event.returnValue = 0;
        }
    }
}


/*-----------------------------------------------------------------*
 | Retorna true se o radio foi checked                             |
 *-----------------------------------------------------------------*/
function fVerificaRadioChecked(radio) {
   var retorno = false;
   	
   if (! isNaN(radio.length)) {   
        for (i=0;i<radio.length;i++) {
            if (radio[i].checked) {
                retorno = true;
            }
        }   
	} else {
        if (radio.checked) {
            retorno = true;
        }
	}        

    return retorno;
}    


/*-----------------------------------------------------------------*
 | Retorna o valor do radio selecionado                            |
 *-----------------------------------------------------------------*/
function getValueSelectedRadio(radio) {
    if (! isNaN(radio.length)) {   
    	for (i = 0; i < radio.length; i++) {
    		if (radio[i].checked) {
    			return radio[i].value;
    		}
    	}
	} else {
        if (radio.checked) {
            return radio.value;
        } else {
        	return "";
        }
	}        
}

/*-------------------------------------------------------------------*
 | checaTamMax        Controla o length do textarea, não permitindo  |
 |                    a digitação que o parâmetro passado            |
 *------------------------------------------------------------------*/
function checaTamMax(control,tam) {
    if (control.value.length >= tam)
        control.value = control.value.substring(0,tam);
}

/*-----------------------------------------------------------------*
 | Retorna o valor do radio selecionado                            |
 *-----------------------------------------------------------------*/
function selecionaCombo(combo, valor) {
    if (! isNaN(combo.length)) {
    	for (i = 0; i < combo.length; i++) {
    		if (combo[i].value == valor) {
    			combo[i].selected = true;
    		}
    	}
	} else {
		if (combo.value == valor) {
			combo.selected = true;
		}
	}        
}

function saibaMais(link) {
    janela = window.open("/sitcs_internetstatic/contribuinte/saiba_mais/" + link,'mais','scrollbars=yes,width=500,height=480,top=50,left=180,tollbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no');
    janela.focus();
}

function ShowDiv(idDiv, oper) {

    var el;
    var i;
    var d = document;

    if(d.getElementById) {
        // Netscape > 6:
        el = d.getElementById(idDiv);
        if (el == null) return;
        el.style.visibility = (oper) ? "visible" : "hidden";
    } else {
        if (d.layers) {
            // Netscape < 6:
            for (i=0; i<d.layers.length; i++) {
                if (d.layers[i].id == idDiv) {
                    d.layers[i].visibility = (oper) ? "show" : "hide";
                }
            }
        } else {
            // IE:
            eval(idDiv + ".style.visibility='" + ((oper) ? "visible" : "hidden") + "';");
        }
    }
}
