


function CalcDV11( s ) {

 Mult = '';
 i = Soma = DV = 0;

 for (i = 0;i < s.length; i++)
    Mult = (new String((i % 8) + 2)) + Mult;

 for (i = 0;i < s.length; i++) 
    Soma = Soma + (paraInteiro(s.charAt(i)) * paraInteiro(Mult.charAt(i)));

  DV = Soma % 11;
  DV = 11 - DV ;

  if ( DV > 9 ) 
    DV = DV - 10;

  return(new String(DV));
}

function RDEValido( sRDE ) {

  if (sRDE.length != 8 )
    return(false);

  if (sRDE.charAt(0).toUpperCase() != 'R') 
    return(false);

  if ( !eIntPositivo(sRDE.substring(1,8)) )
    return(false);

  return(true);
}

function CGCValido( sCGC )
{
    sCGC = RmTraco(sCGC);
    var
        bOk,
        nOrd,
        nSoma,
        nCount,
        nDigito;
	var
		nMult;

	// inicializa o array de calculo do DV
    nMult = new Array(2);
    nMult[0] = new Array( 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 );
    nMult[1] = new Array( 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3 );


	nOrd = 0;
    nDigito = 0;
    bOk = true;

	if( sCGC.length != 14 )
    	bOk = false;
	else
    while( bOk && (nOrd < 2))
    {
        nSoma = 0;

        for( nCount = 0 ; nCount < 12 ; nCount++ )
            nSoma += (sCGC.charCodeAt(nCount) - "0".charCodeAt(0) ) * nMult[nOrd][nCount] ;

        if( nOrd > 0 )
            nSoma += 2 * nDigito ;

        nDigito = (nSoma * 10) % 11;
        if ( nDigito > 9 )
          nDigito -= 10;

        if( ( nDigito + "0".charCodeAt(0) ) != sCGC.charCodeAt( 12 + nOrd ) )
            bOk = false ;

        nOrd++ ;
    }

    return( bOk );
}



function CPFValido( sCPF ) {

 sCPF = RmTraco(sCPF);
 
 if( sCPF.length > 11 )
	return(false);
	
 s1 = sCPF.substring(0,9);
 s2 = sCPF.substring(9,11);

 d1 = 0;
 for (i=0;i<9;i++)
   d1 += s1.charAt(i)*(10-i);
  d1 = 11 - (d1 % 11);
  if (d1>9) d1 = 0;

  if (s2.charAt(0) != d1)
    return(false);

  d1 *= 2;

  for (i=0;i<9;i++)
    d1 += s1.charAt(i)*(11-i);
  d1 = 11 - (d1 % 11);
  if (d1>9) d1 = 0;

  if (s2.charAt(1) != d1)
    return(false);

  return true;

}

function Pesquisar(url , cap , f1 , f2 , f3 , f4 , fc ) {

  wnd = window.open("","wnd","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,height=400,width=600");

  with (wnd.document) {
    write('<html>');
    write('<head>');
    write('<title>' + cap + '</title>');
    write('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">');
    write('</head>');
    write('<frameset rows="1,*" frameborder="YES" border="0" framespacing="0"> ');
    write('  <frame name="topFrame" scrolling="YES" noresize src="" >');
    write('  <frame name="mainFrame" src="'+ url +'">');
    write('</frameset>');
    write('</html>');
  }
 
  with (wnd.topFrame.document) {
    write('<' + 'script'+' language="javascript">');
    write('var fld1 , fld2 , fld3 , fld4 , pwnd , fc;');
    write('function seleciona( f1 , f2 , f3 , f4) {');
    write('if (fld1 != null) fld1.value = f1;');
    write('if (fld2 != null) fld2.value = f2;');
    write('if (fld3 != null) fld3.value = f3;');
    write('if (fld4 != null) fld4.value = f4;');
    write('if ( fc.length != 0 ) pwnd.setTimeout(fc , 1);');
    write('parent.close();');
    write('}');   
    write('</'+'script'+'>'); 
  }

  if (f1 != null) 
    wnd.topFrame.fld1 = f1;
  if (f2 != null) 
    wnd.topFrame.fld2 = f2;
  if (f3 != null) 
    wnd.topFrame.fld3 = f3;
  if (f4 != null) 
    wnd.topFrame.fld4 = f4;
  if (fc != null) 
    wnd.topFrame.fc = fc
  else
    wnd.topFrame.fc = '';

  wnd.topFrame.pwnd = window;

  wnd.focus();
}

function paraInteiro( s ){ 
  s = rmCharFrente("0" , s );  
  if (eVazio(s))
    return(0)
  else
    return(parseInt(s));
}

function eInteiro( s ){ 
  if (eVazio(s)) 
    return(false);

  s = rmCharFrente("0" , s );
  
  return((eVazio(s)) || (parseInt(s) == s));
}


function eInteiroouVazio( s ){ 
  
  return((parseInt(s) == s) || (eVazio(s)));
}


function eIntPositivo( s ){
  return((eInteiro(s)) && (paraInteiro(s) >= 0));
}



function paraReal( s ){ 
  s = s.replace("," , ".");
  return(parseFloat(s));
}

function eReal( s ) {
//  s = rmCharFrente("0" , s );
  s = s.replace("," , ".");

  return(s == paraReal(s));
}

function fmtReal( s ) {
  s = substchar(s , "." , ",");
  return(s);
}

function eRealPositivo( s ) {
  return((eReal(s)) && (paraReal(s) >= 0));
}

function eVazio( s ){ 
  return ((s == null) || (s.length == 0));
}

function rmChar (c , s) {
    var i;

    var r = "";

    for (i = 0; i < s.length; i++)  {   
      if (c != s.charAt(i) ) r += s.charAt(i) ;         
    }

    return(r);
}

function rmCharFrente (c , s) {
    var i;

    var r = "";

    for (i = 0; i < s.length; i++)  {   
      if (c != s.charAt(i) )  {
        r = s.substring(i , s.length);
        break;
      }  
    }

    return r;
}

function repeteChar( c , n ) {
  s1 = "";
  for (i=0; i < n ; i++)
   s1 += c
 return(s1);
}


function RmTraco( s ) {

  s = rmChar("-" , s);
  s = rmChar("." , s);
  s = rmChar("/" , s);

  return(s);

} 


function eData( s ) {

  dias = new Array( 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );

  i = s.indexOf('/');
  j = s.lastIndexOf('/');

  d = paraInteiro(s.substring(0,i)) ;
  m = paraInteiro(s.substring(i+1,j)) ;
  a = paraInteiro(s.substring(j+1,s.length));

//  d = paraInteiro(s.substring(0,2)) ;
//  m = paraInteiro(s.substring(3,5)) ;
//  a = paraInteiro(s.substring(6,10));

//   Dat = new Date();
//   ddat = Dat.getDate();
//   yyat = Dat.getYear();
//   mmat = Dat.getMonth() + 1;
   

  if ((a % 4 == 0) && ((a % 100 != 0) || ((a % 100 == 0) && (a % 400 == 0))))
    dias[2] = 29;

  if (( a > 1900 ) && ( a < 2100 ) &&  (m > 0 ) && (m < dias.length) && (d > 0) && (d <= dias[m]))
    return(true)
  else
    return(false);

}

function eDataFutura( s ){
  dias = new Array( 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );

  i = s.indexOf('/');
  j = s.lastIndexOf('/');

  d = paraInteiro(s.substring(0,i)) ;
  m = paraInteiro(s.substring(i+1,j)) ;
  a = paraInteiro(s.substring(j+1,s.length));

  Dat = new Date();
  ddat = Dat.getDate();
  yyat = Dat.getYear();
  mmat = Dat.getMonth() + 1;
//   alert(ddat + '/' + mmat +'/'+ yyat);
  if (yyat > a)
	return false;
  else
  {
    if (((yyat == a) && ((mmat == m && ddat < d) || (mmat < m))) || yyat < a)
    	return true;
  }  

  return false;  
}

function formataData( s){
  i = s.indexOf('/');
  j = s.lastIndexOf('/');

  var data = "";

  if ( i == 1)
  {
    data += "0";
    data += s.charAt(i-1);
  } 
  else
    data = s.substring(0,i);

  data += "/";

  if (j == 3 || j == 4)
  {
    data += "0";
    data += s.charAt(j-1);
  }
  else
    data += s.substring(i+1,j) ;

  data += "/";
  
  data += s.substring(j+1,s.length);

  return data;
}


function eHora( s ) {

  t = s.substring(2,3);
  s = rmChar(":" , s);
  c = s.length;	
  h = paraInteiro(s.substring(0,2)) ;
  m = s.substring(2,4) ;
  
  if (( h >= 8 ) && ( h <= 18 ) &&  (m >= 0 ) && (m < 60) && (c == 4) && (t == ':'))
    return(true);
  else
    return(false);

} 

function paraData( s ) {
  d = paraInteiro(s.substring(0,2)) ;
  m = paraInteiro(s.substring(3,5)) ;
  a = paraInteiro(s.substring(6,10));

  return(new Date(a , m - 1 , d));
}

function substchar(str , proc , subst) {
  strret = "";
  for (i = 0; i < str.length; i++)
    if (str.charAt(i) == proc)
      strret += subst
    else
      strret += str.charAt(i);

  return(strret); 
}


function trim(palavra)
{
	return(lTrim(rTrim(palavra)));
}


function lTrim(palavra)
{
	if(palavra.length == 0)
	{
		return(palavra);
	}
	else
	{
		if(palavra.substr(0, 1) == ' ')
		{
			return(lTrim(palavra.substr(1, palavra.length - 1)));
		}
		else
		{
			return(palavra);
		}
	}
}

function rTrim(palavra)
{
	if(palavra.length == 0)
	{
		return(palavra);
	}
	else
	{
		if(palavra.substr(palavra.length - 1, 1) == ' ')
		{
			return(rTrim(palavra.substr(0, palavra.length - 1)));
		}
		else
		{
			return(palavra);
		}
	}
}


function removebrancos( text )
{
 	var i, s = "";

    for( i = 0 ; i < text.value.length ; i++ )
    {
    	if( text.value.charAt(i) != ' ' )
     		s += text.value.charAt(i);
    }

    text.value = s;
}

/*
 Nome........: ValidaEmail
 Descricao...: Verifica a validade de um endereco de e-mail.
 Paramentros.: 
 Retorno.....: Retorna True se o e-mail for valido e False se o e-mail nao for valido.
 Autor.......:
 Data........: 
 Obs.........:
*/
function ValidaEmail (strEmail, strLingua) {
/* A sentença descrita abaixo é usada para validar se o endereço de e-mail informado
   obedece ao formato usuario@dominio. É tambem utilizado para separar o nome do usuário
   do dominio.*/
var strEmailPadrao=/^(.+)@(.+)$/

/* A sentença descrita abaixo define a maáscara para filtrar todos os caracteres especiais.
   Nós não queremos permitir esses caracteres nos endereços de e-mail.
   Caracteres especiais incluem: ( ) < > @ , ; : \ " . [ ] */
var strCharsEspeciais="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

/* A sentença seguinte representa o grupo de caracteres permitidos no nome do usuário
   ou domínio. Definindo quais caracteres não são permitidos. */
var strCharsValidos="\[^\\s" + strCharsEspeciais + "\]"

/* A sentença seguinte verifica se o "usuário" é quoted string (e-mail entre Aspas).
   Caso em que não existe nenhuma regra definindo quais são os caracteres permitidos ou 
   não permitidos. Qualquer caracter passa. Ex.: "jiminy cricket@disney.com" eh um e-mail
   válido. */
var quotedUser="(\"[^\"]*\")"

/* A sentença seguinte se aplica para domínios que são Endereços IP, ao invés de nomes
   simbólicos. Ex.: joe@[123.124.233.4] é um endereço de e-mail válido.
   ATENÇÃO: Os colchetes sao obrigatórios.  */
var strDominioIP=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

/* A sentença seguinte representa uma série de caracteres não especiais. */
var atom=strCharsValidos + '+'

/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string.*/ // <----- TRADUZIR 
var strPalavra="(" + atom + "|" + quotedUser + ")"

// A sentença seguinte descreve a estrutura para o nome do usuário.
var strFormatoUser=new RegExp("^" + strPalavra + "(\\." + strPalavra + ")*$")

/* A sentença seguinte descreve a estrutura para um domínio simbólico, ao invés do
   domínio utilizando Endereco IP, demonstrado acima. */
var strFormatoDominio=new RegExp("^" + atom + "(\\." + atom +")*$")

/* Finalmente, vamos iniciar a verificação se o e-mail fornecido é válido.*/
var VetorValidacao=strEmail.match(strEmailPadrao)

if (VetorValidacao==null) 
{
  /* Muito/Poucos @'s ou outra coisa, como pontos; basicamente, esse endereço 
     não apresenta o formato de um endereço válido de e-mail. */
	//alert("Endereço de Email incorreto! (Verifique @ e .'s)")
	if (strLingua == "P")
	  window.alert("Endereço eletrônico inválido.");
	else
	  window.alert("Invalid e-mail address.");
	return false
}
var strUsuario=VetorValidacao[1]
var strDominio=VetorValidacao[2]

// Verificando se o "usuário" é válido.
if (strUsuario.match(strFormatoUser)==null) 
{ 
    //alert("O nome do usuário não é válido.")
    //window.alert("Endereço eletrônico inválido.")
  	if (strLingua == "P")
	  window.alert("Endereço eletrônico inválido.");
	else
	  window.alert("Invalid e-mail address.");
    return false
}

/* Se o endereço de e-mail é um Endereço IP (oposto ao nome do domínio simbólico)
   verifique se o Endereço IP é válido.*/   
var VetorIP=strDominio.match(strDominioIP)
if (VetorIP!=null)
{
    // É um Endereço IP.
	  for (var i=1;i<=4;i++)
	  {
	    if (VetorIP[i]>255) 
	    {
	        //alert("Endereço IP inválido!") 
		//window.alert("Endereço eletrônico inválido.")
    	if (strLingua == "P")
	      window.alert("Endereço eletrônico inválido.");
	    else
	      window.alert("Invalid e-mail address.");
		return false
	    }
      }
      return true
}

// O Domínio é um nome simbólico.
var VetorDominio=strDominio.match(strFormatoDominio)
if (VetorDominio==null) 
{
    //alert("O nome do domínio não é válido!")
    //window.alert("Endereço eletrônico inválido.")
	if (strLingua == "P")
	  window.alert("Endereço eletrônico inválido.");
	else
	  window.alert("Invalid e-mail address.");
    	
    return false
}
/* O nome do domínio parece válido, mas agora certifique-se que termine em uma palavra com
   três caracteres (como: com, edu, gov,...) ou uma palavra de dois caracteres, representando 
   o país (como: br, uk, nl,...), e se o domínio ou o país é precedido por um host name. */

/* Agora precisamos desmembrar o dominio para validadarmos as partes.*/
var atomPat=new RegExp(atom,"g")
var DomVet=strDominio.match(atomPat)
var tam=DomVet.length
if (DomVet[DomVet.length-1].length<2 || 
    DomVet[DomVet.length-1].length>3) 
{
   // O endereço tem que terminar em uma palavra de dois ou três caracteres.
   //alert("O endereço deve terminar em um domínio com três caracteres ou em um país com dois caracteres.")
   //window.alert("Endereço eletrônico inválido.")
       	if (strLingua == "P")
	      window.alert("Endereço eletrônico inválido.");
	    else
	      window.alert("Invalid e-mail address.");

   return false
}

// Certificando que o domínio é precedido por um hostname.
if (tam<2) 
{
   var errStr="Este endereço não possui hostname!"
   //alert(errStr)
   //window.alert("Endereço eletrônico inválido.")
       	if (strLingua == "P")
	      window.alert("Endereço eletrônico inválido.");
	    else
	      window.alert("Invalid e-mail address.");

   return false
}

// Se vc chegou até aqui, todo o resto é válido!
return true;
}
