
function isValidEmail(strEmail) 
{
    var re; 
    re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/; 
    if (re.test(strEmail) == true) 
    {   return true;    }
    else
    { alert ("O email é inválido");
    return false;   }    
}


function chkNumero(campo, nomeCampo){
    var straux;
    straux = new String(campo);
    i = 0;
    while (i < straux.length ) {
      if (((straux.charAt(i)>='0') && (straux.charAt(i)<='9')))
        i++;
      else {
        alert('O campo ' + nomeCampo + ' deve ser numérico.');
        return false;
      }
    }
    return true;
}


/*------------------------------------------------------------------------------- 
  Busca registros relacionados com a palavra digitada no campo txtBusca do form.
   Determina ainda que a ordenação é por ordem ascendente pelo nome do documento 
  (hidorder = 0) e que não é uma pesquisa detalhada (hiddetalhada = 0).          
------------------------------------------------------------------------------- */ 

function fu_buscapalavra()  {
   document.frmMain.hidorder.value     = "4";       
   document.frmMain.hidraking.value    = "0";
   document.frmMain.hiddetalhada.value = "0";   
   document.frmMain.hidtxtbusca.value  = "";        // modifv9.3
   document.frmMain.action             = "busca_resultado.asp";
   document.frmMain.submit();
}

function fu_buscarpalavras()    {
   document.frmBusca.hidorder.value     = "4";      
   document.frmBusca.hidraking.value    = "0";
   document.frmBusca.hiddetalhada.value = "0";  
   document.frmBusca.hidtxtbusca.value  = "";       // modifv9.3
   document.frmBusca.action             = "busca_resultado.asp";
   document.frmBusca.submit();
}

// usada nos arquivos faq_index e noticia_index
function fu_buscapalavraLocal() {
   document.frmMain.hidorder.value     = "4";       
   document.frmMain.hidraking.value    = "0";
   document.frmMain.hiddetalhada.value = "0";   
   document.frmMain.hidtxtbusca.value  = "";
   document.frmMain.action             = "busca_resultado.asp";
   document.frmMain.submit();
}

//--------------------------------------------------------------------------------
function fu_buscaraking(){
  document.frmMain.txtbusca.value  = "";
  document.frmMain.hidraking.value = "1";
  document.frmMain.action          = "busca_resultado.asp"
  document.frmMain.submit();
}

function buscaraking(){
  document.frmBusca.txtbusca.value  = "";
  document.frmBusca.hidraking.value = "1";
  document.frmBusca.tipoacao.value  = "maisacessadas";
  document.frmBusca.action          = "busca_resultado.asp"
  document.frmBusca.submit();
}

function buscanovidades(){
  document.frmBusca.txtbusca.value  = "";
  document.frmBusca.hidraking.value = "0";
  document.frmBusca.hidorder.value  = "4";  
  document.frmBusca.tipoacao.value  = "novidades";
  document.frmBusca.busca.value     = "novidades";
  document.frmBusca.action          = "busca_resultado.asp";
  document.frmBusca.submit();
}

// usada nos arquivos faq_index e noticia_index
function fu_buscarakingLocal(){
    document.frmMain.txtbusca.value = "";
    document.frmMain.hidraking.value = "1";
    document.frmMain.action = "busca_resultado.asp";                
    document.frmMain.submit();
}   

//--------------------------------------------------------------------------------
// restricting entered data to just letters and numbers - no spaces, commas or 
// other types of characters are allowed.
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function letternumber(e) {
  var key;
  var keychar;
  if (window.event)
    key = window.event.keyCode;
  else if (e)
    key = e.which;
  else
    return true;

  keychar = String.fromCharCode(key);
  keychar = keychar.toLowerCase();
  
  // control keys
  if ((key==null) || (key==0) || (key==8) || 
     (key==9) || (key==13) || (key==27) )
    return true; 
  // alphas and numbers
  else if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) > -1))
    return true;
  else
    return false;
}

//--------------------------------------------------------------------------------
// restricting the field to just numbers.
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec){
  var key;
  var keychar;
  if (window.event)
    key = window.event.keyCode;
  else if (e)
    key = e.which;
  else
    return true;

  keychar = String.fromCharCode(key);
  // control keys
  if ((key==null) || (key==0) || (key==8) || 
      (key==9)    || (key==13) || (key==27) )
    return true;
  // numbers
  else if ((("0123456789").indexOf(keychar) > -1))
    return true;
  else
    return false;
}

//-------------------------------------------------------------------------------------
//Simula o comando Trim do VBScript
//-------------------------------------------------------------------------------------
function getTrim(texto){
 while  ((texto.search(' ') > -1) ) {
        texto = texto.replace(' ','');    
 }
 return (texto) 
}

//-------------------------------------------------------------------------------------
//função para verificar se o objeto está vazio MODIFICADA
//-------------------------------------------------------------------------------------
function chkVazio(campo, msg){ 
  var j = false; 
  var valor = getTrim(campo.value);
  
  if(valor == "") {
   j = true;
    alert(msg);
    campo.focus();
  }
  
  return (j);
}

//-------------------------------------------------------------------------------------
// Verifica se o CPF é válido
//-------------------------------------------------------------------------------------
function chkCpf (campo,valor) {
  strcpf = valor;
  str_aux = "";
  
  for (i = 0; i <= strcpf.length - 1; i++)
    if ((strcpf.charAt(i)).match(/\d/)) 
      str_aux += strcpf.charAt(i);
    else if (!(strcpf.charAt(i)).match(/[\.\-]/)) {
      alert ("O campo CPF apresenta caracteres inválidos");
      campo.focus();
      return false;
    }
  
  if (str_aux.length != 11) {
    alert ("O campo CPF deve conter 11 dígitos");
    campo.focus();
    return false;
  }
  
  soma1 = soma2 = 0;
  for (i = 0; i <= 8; i++) {
    soma1 += str_aux.charAt(i) * (10-i);
    soma2 += str_aux.charAt(i) * (11-i);
  }
  d1 = ((soma1 * 10) % 11) % 10;
  d2 = (((soma2 + (d1 * 2)) * 10) % 11) % 10;
  if ((d1 != str_aux.charAt(9)) || (d2 != str_aux.charAt(10))) {
    alert ("O CPF digitado é inválido");
    campo.focus();
    return false;
  }
 
  return true;
}

//-------------------------------------------------------------------------------------
// Verifica se o CNPJ é válido MODIFICADA
//-------------------------------------------------------------------------------------
function chkCnpj(s) {
    var i;
    //s = limpa_string(numero);
    var c = s.substr(0,12);
    var dv = s.substr(12,2);
    var d1 = 0;

    for (i = 0; i < 12; i++){
        d1 += c.charAt(11-i)*(2+(i % 8));
    }
    
    if (d1 == 0) {
      alert ("O CNPJ digitado é inválido");
      return false;
    }
    
   d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;

    if (dv.charAt(0) != d1) {
       alert ("O CNPJ digitado é inválido");
        return false;
    }

    d1 *= 2;

    for (i = 0; i < 12; i++){
        d1 += c.charAt(11-i)*(2+((i+1) % 8));
    }

    d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;

    if (dv.charAt(1) != d1) {
       alert ("O CNPJ digitado é inválido");
        return false;
    }
   return true;
}



/*------------------------------------------------------
FUNÇÕES QUE NÃO ESTÃO SENDO UTILIZADAS
- Retorna o número de dias conforme o mês e ano
  function getNDias(mes,ano)
- Retorna o tipo de Browser IE = "IE", Outros="Default"
  function getBrowser()
- Verifica se a senha e a confirmação são iguais
  function chkSenha (senha1, senha2)
- Limpa os brancos iniciais e finais do campo, retornando 1 se o campo ficou vazio e 0 se não.
  function setLimpaBrancos (campo)
- Seta o maxlength para um objeto TextArea. Ex.: onKeyUp="textarealimite(this.form.'name',300);"
  function setTextAreaLimite(campo, maxlimite)
- Verifica se campos radio e checkbox estão selecionados
  function chkSelecionado(campo)
- Seta a caixa de texto ser digitado somente números
  function setNumero()
- Valida campo CEP
  function chkCep(campo_cep,campo_uf)
- Verifica a idade mínima, verificando o intervalo entre anos
  function chkIdadeMinima(ano_de, ano_ate, campo)
- Verifica se o campo contém somente letras e números
  function chkAlpNum(campo)
- Insere formatação Currency Ex.: onKeyPress="return(setCurrency(this,'.',',',event))"
  function setCurrency(campo, separador_mil, separador_dec, e)
- Limpa espaços em brancos
  functions LTrim,  RTrim, e Trim
- Verifica os caracteres que não são válidos
  function chkCaracter(campo, msg)
------------------------------------------------------*/

//Verifica de um conjunto de dois radios foram checados. Ex.: Sexo ()M ()F 
function chkRadioDuplo(obj, msg)
{
    if(obj[0].checked == false && obj[1].checked == false){
        alert(msg);
        obj[0].focus();
        return false;
    }else {
        return true;
    }
}


//Retorna u número de dias conforme o mês e ano
function getNDias(mes,ano) {
    if (mes==2) {
    if((ano % 4) == 0 ) 
        return 29 
    else 
        return 28
    }else   if (mes < 8) {
    if ((mes % 2) == 0) 
        return 30 
    else 
        return 31
    }else   {
    if ((mes % 2) != 0) 
        return 30 
    else 
        return 31
    }      
}

//-------------------------------------------------------------------------------------
//Retorna o tipo de Browser IE = "IE", Outros="Default"
function getBrowser()
{
    var st = document.cookie ;
    var a;
    var i;
    var tipo_browser;

    if( window.navigator.appName == 'Netscape' )
    {
        tipo_browser = "Default"   
    }
    else
    {   
        tipo_browser = "IE" 
    }
    return tipo_browser
}

//-------------------------------------------------------------------------------------
// Verifica se a senha e a confirmação são iguais
//-------------------------------------------------------------------------------------
function chkSenha (senha1, senha2)
{
  strsenha1 = senha1.value;
  strsenha2 = senha2.value;
  
  if ((!strsenha1) || (strsenha1 == strsenha2)) return true;
  if (strsenha2)
    alert ("A senha e a confirmação devem conter o mesmo valor");
  return false;
}

// Limpa os brancos iniciais e finais do campo, retornando 1 se o campo ficou vazio e 0 se não.
function setLimpaBrancos (campo) {
   var strcampo = eval ("document.forms[0]."+campo+".value");
   var inicio = 0;
   var fim = strcampo.length - 1;
 
   while ((strcampo.charAt(fim).match(/\s/)) && (fim != inicio)) fim--;   
   if (inicio != fim) while (strcampo.charAt(inicio).match(/\s/)) inicio++;
   
   str_aux = "";
   if ((fim) || (!(strcampo.charAt(inicio).match(/\s/))))
     for (; inicio <= fim; inicio++) str_aux += strcampo.charAt(inicio);   
     
   eval ("document.forms[0]."+campo+".value = '"+str_aux+"'");
   return (!str_aux.length)
}

//Seta o maxlength para um objeto TextArea. Ex.: onKeyUp="textarealimite(this.form.'name',300);"
function setTextAreaLimite(campo, maxlimite)
{
    if (campo.value.length > maxlimite)
    campo.value = campo.value.substring(0, maxlimite);
}

//Verifica se campos radio e checkbox estão selecionados
function chkSelecionado(campo,msg)
{
    var checado = "";
    for (var i = 0;i < campo.length; i++)
    {
        if(campo[i].checked)
        {
            checado = "1";
            return true;
        }
    }
    if(checado == "")
    {
        alert(msg);
        campo[0].focus();
        return false;
    }
}



//Seta a caixa de texto ser digitado somente números
function setNumero()
{
    if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
}

//Valida o campo CEP
function chkCep(campo_cep,campo_uf)
{
  if (!chkNumero(campo_cep)) {
    campo_cep.value = "";
    return false;
  }
  
  if(campo_cep.value.length < 8)
  {
    alert('Por favor digite o cep com 8 dígitos.');
    campo_cep.value = "";
    return false;
  }
  
  var valor_inicial = campo_cep.value;
  valor_inicial = valor_inicial.substring(0,5);
  var valor = parseInt(valor_inicial);
  var est = campo_uf.options[campo_uf.selectedIndex].value;
  var erro = true;
  
 if (valor >= 0 && valor <= 19999) {
    if (est == "SP") {
      erro = false;
    }
  }
  else if (valor >= 20000 && valor <= 29999) {
    if (est == "RJ" || est == "ES") {
      erro = false;
    }
  }
  else if (valor >= 30000 && valor <= 39999) {
    if (est == "MG") {
      erro = false;
    }
  }
  else if (valor >= 40000 && valor <= 49999) {
    if (est == "BA" || est == "SE") {
      erro = false;
    }
  }
  else if (valor >= 50000 && valor <= 59999) {
    if (est == "PE" || est == "AL" || est == "PB" || est == "RN") {
      erro = false;
    }
  }
  else if (valor >= 60000 && valor <= 69999) {
    if (est == "CE" || est == "PI" || est == "MA" || est == "PA" || est == "AP" || est == "AM" || est == "RR" || est == "AC") {
      erro = false;
    }
  }
  else if (valor >= 70000 && valor <= 79999) {
    if (est == "DF" || est == "GO" || est == "TO" || est == "MT" || est == "RO" || est == "MS") {
      erro = false;
    }
  }
  else if (valor >= 80000 && valor <= 89999) {
    if (est == "PR" || est == "SC") {
      erro = false;
    }
  }
  else if (valor >= 90000 && valor <= 99999) {
    if (est == "RS") {
      erro = false;
    }
  }
  if (erro) {
    campo_cep.value = "";
    alert ("O CEP não corresponde ao estado selecionado.");
    return false;

  }
  else
  {
    return true;
  }
  return true;
}

//Verifica a idade mínima, verificando o intervalo entre anos
function chkIdadeMinima(ano_de, ano_ate, campo)
{
    var data = new String();
    var data_num = new Number();
    data = campo.value;
    data = data.substr(6,4);
    data_num = data;
    if((data_num < parseInt(ano_de))||(data_num > parseInt(ano_ate)))
    {
        alert("Idade mínima excedida\nou data inválida!");
        campo.focus();
        return false;
    }
    else
    {
        return true;
    }
}

//Verifica se o campo contém somente letras e números
function chkAlpNum(campo)
{
    var valid = "abcdefghijklmnopqrstuvwxyz0123456789"
    var ok = "yes";
    var temp;
    for (var i=0; i < campo.value.length; i++)
    {
        temp = "" + campo.value.substring(i, i+1);
        if (valid.indexOf(temp) == "-1") ok = "no";
    }
    if (ok == "no")
    {
        alert("Esse campo só aceita caracteres e números.");
        campo.focus();
        campo.select();
        return false;
    }
    else
    {
        return true;
    }
}

//Insere formatação Currency Ex.: onKeyPress="return(setCurrency(this,'.',',',event))"
function setCurrency(campo, separador_mil, separador_dec, e)
{
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    
    if (whichCode == 13) return true;  // Enter
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    len = campo.value.length;
    for(i = 0; i < len; i++)
        if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_dec)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) campo.value = '';
    if (len == 1) campo.value = '0'+ separador_dec + '0' + aux;
    if (len == 2) campo.value = '0'+ separador_dec + aux;
    if (len > 2)
    {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--)
        {
            if (j == 3)
            {
                aux2 += separador_mil;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        campo.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            campo.value += aux2.charAt(i);
            campo.value += separador_dec + aux.substr(len - 2, len);
    }
    return false;
}

function chkEmail(emailStr)
{
    var emailPat=/^(.+)@(.+)$/
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    var validChars="\[^\\s" + specialChars + "\]"
    var quotedUser="(\"[^\"]*\")"
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
    var atom=validChars + '+'
    var word="(" + atom + "|" + quotedUser + ")"
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
    var matchArray=emailStr.match(emailPat)
    if (matchArray==null) {
        //alert("O endereço de E-mail está incorreto (veirfque @ e .'s)")
        return false
    }
    
    var user=matchArray[1]
    var domain=matchArray[2]

    if (user.match(userPat)==null) {
        alert("Erro no endereço de E-mail:\nO nome do usuário não está correto.")
        return false
    }

    var IPArray=domain.match(ipDomainPat)
    if (IPArray!=null) {
      for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                alert("Erro no endereço de E-mail:\nO endereço IP de destino não é válido.")
                return false
            }
        }
        return true
    }

    var domainArray=domain.match(domainPat)
    if (domainArray==null) {
        alert("Erro no endereço de E-mail:\nO domínio não é válido.")
        return false
    }

    var atomPat=new RegExp(atom,"g")
    var domArr=domain.match(atomPat)
    var len=domArr.length
    if (domArr[domArr.length-1].length<2 || 
        domArr[domArr.length-1].length>3) {
        alert("Erro no endereço de E-mail:\nO endereço precisa terminar com três letras referente ao domínio\nou duas letras referente ao país")
        return false
    }

    if (len<2) {
        var errStr="Erro no endereço de E-mail:\nEstá faltando o nome do provedor."
        alert(errStr)
        return false
    }
    return true;
}


//Fuctions to mimmick LTrim,  RTrim, and Trim...
function LTrim(str)
/*
        PURPOSE: Remove leading blanks from our string.
        IN: str - the string we want to LTrim
*/
{
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...

            var j=0, i = s.length;

            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;


            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }

        return s;
}

function RTrim(str)
/*
        PURPOSE: Remove trailing blanks from our string.
        IN: str - the string we want to RTrim

*/
{
        // We don't want to trip JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in Whitespace
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...

            var i = s.length - 1;       // Get length of string

            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;


            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }

        return s;
}


function Trim(str)
/*
                PURPOSE: Remove trailing and leading blanks from our string.
                IN: str - the string we want to Trim

                RETVAL: A Trimmed string!
*/
{
     return RTrim(LTrim(str));
}


/*Valida caracter*/
function chkCaracter(campo, msg)
{
  var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ0123456789-.@ \t\r\n\f";
  var checkStr = campo.value;
  var allValid = true;

  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    alert(msg);
    campo.focus();
    return (false);
  }
  return (true);
}


//************************************************************************** INI
// Max - 14/Set/2005 - Funções para controlar areas(DIV) para mostrar e
//                     ocultrar informações sem recarregar a página.

 function show_layer(fname,visible)
 {
   if (document.layers) { // Netscape
     if( visible ) { s = 'show' ; b = 'block' ; } else { s = 'hide' ; b = 'none' ; }
     document.layers[eval('"'+fname+'"')].visibility = s ;
   } else if (document.all) { // Internet Explorer
     if( visible ) { s = 'visible' ; b = 'block' ; } else { s = 'hidden' ; b = 'none' ; } 
     document.all[eval('"'+fname+'"')].style.visibility = s ;
   } else if (document.getElementById) { // Netscape 6
     if( visible ) { s = 'visible' ; b = 'block' ; } else { s = 'hidden' ; b = 'none' ; } 
     document.getElementById(eval('"'+fname+'"')).style.visibility = s ;
   }
 }
 
 function set_display(fname,b)
 {
   (b) ? s = 'block' : s = 'none' ; 
   if (document.layers) { // Netscape
     document.layers[eval('"'+fname+'"')].display = s ;
   } else if (document.all) { // Internet Explorer
     document.all[eval('"'+fname+'"')].style.display = s ;
   } else if (document.getElementById) { // Netscape 6
     document.getElementById(eval('"'+fname+'"')).style.display = s ;
   }
 } 

function AbreFecha(namework,acao)
{
  var campo  = document.getElementById(namework);
  if(acao==0) {
    show_layer(namework,false);set_display(namework,false);
    campo.value=1;
  } else {
    show_layer(namework,true);set_display(namework,true);
    campo.value=0;
  }

}

function AbreMais(NomeArea)
{
  AbreFecha(NomeArea,1);
  AbreFecha(NomeArea+'_1',0);
  AbreFecha(NomeArea+'_2',1);
}  

function AbreMenos(NomeArea)
{
  AbreFecha(NomeArea,0);
  AbreFecha(NomeArea+'_1',1);
  AbreFecha(NomeArea+'_2',0);
}

function RemoverUsuario(valor)
//************************************************************************** INI
// Marcos - 05/Dez/2005 -  Função para excluir usuário
//                      
{
    document.Principal.Usuario.value = valor;
    document.Principal.submit();
}


// Marcos - 05/Dez/2005 
//************************************************************************** INI

