
/*******************************************************************
 *                                                                 *
 *   Basico.asp  -  Funções Básicas em JavaScript para uso Geral   *
 *                                                                 *
 *                  V1.5  -  Jan/2000                              *
 *                                                                 *
 *******************************************************************/

/*-----------------------------------------------------------------*
 | ContidoNoDominio    Retorna True se a String dada só contiver   |
 |                     caracteres do domínio dado                  |
 *-----------------------------------------------------------------*/
function ContidoNoDominio(StrDado, Dominio)
	{
	var i, j;

	if (StrDado == "") return false;

	for (i=0; i<StrDado.length; i++)
		{
		for (j=0; j<Dominio.length; j++)
			{
			if (StrDado.substr(i,1) == Dominio.substr(j,1)) break;
			}
		if (j >= Dominio.length) return false;
		}
	return true
	}

/*-----------------------------------------------------------------*
 | ContemDominio    Retorna True se a String dada contiver algum   |
 |                  caractere do domínio dado                      |
 *-----------------------------------------------------------------*/
function ContemDominio(StrDado, Dominio)
	{
	var i, j;

	if (StrDado != "")
		{
		for (i=0; i<StrDado.length; i++)
			{
			for (j=0; j<Dominio.length; j++)
				{
				if (StrDado.substr(i,1) == Dominio.substr(j,1)) return true;
				}
			}
		}

	return false;
	}

/*-----------------------------------------------------------------*
 | IsStrNum     Retorna True se a String dada só contiver números  |
 |                                                                 |
 *-----------------------------------------------------------------*/
function IsStrNum(Dado)
	{
	return ContidoNoDominio(Dado, " 0123456789");
	}

/*-----------------------------------------------------------------*
 | IsStrInt	    Retorna True se a String dada só contiver          |
 |              Caracteres para Número inteiro                     |
 *-----------------------------------------------------------------*/
function IsStrInt(Dado)
	{
	return ContidoNoDominio(Dado, " +-0123456789");
	}

/*-----------------------------------------------------------------*
 | IsStrFloat   Retorna True se a String dada só contiver          |
 |              Caracteres para Número em Ponto-Flutuante          |
 *-----------------------------------------------------------------*/
function IsStrFloat(Dado)
	{
	return ContidoNoDominio(Dado, " +-0123456789Ee,.");
	}

/*-----------------------------------------------------------------*
 | IsStrCurr    Retorna True se a String dada só contiver          |
 |              Caracteres para Número Currency                    |
 *-----------------------------------------------------------------*/
function IsStrCurr(Dado)
	{
	return ContidoNoDominio(Dado, " +-0123456789,.");
	}

/*-----------------------------------------------------------------*
 | IsStrData    Retorna True se a String dada for uma data válida  |
 |              no formato DD/MM/AAAA                              |
 *-----------------------------------------------------------------*/
function IsStrData(Dado)
	{
    var DiasMes = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
    var Dia, Mes, Ano;
    var Result = false;

	// Pré-analisa o String:
	if (Dado != "")
		{
		if ((Dado.length == 10) && (Dado.substr(2,1) == "/") && (Dado.substr(5,1) == "/"))
			{
			// Levanta Campos:
			if (IsStrNum(Dado.substr(0,2))) Dia = Dado.substr(0,2);
			if (IsStrNum(Dado.substr(3,2))) Mes = Dado.substr(3,2);
			if (IsStrNum(Dado.substr(6,4))) Ano = Dado.substr(6,4);

			// Analisa Ano e Mês:
			if ((Ano > 0) && (Mes >= 1) && (Mes <= 12))
				{
				// Analisa Dia:
				if ((Dia >= 1) && (Dia <= DiasMes[Mes - 1]))
					{
					// Analisa os casos não-bissextos:
					if ((Mes == 2) && ((Ano%4 != 0) || (Ano%100 == 0) && (Ano%400 != 0)))
						{
						if (Dia <= 28) Result = true;
						}
					else
						{
						Result = true;
						}
					}
				}
			}
		}
	return Result;
	}

/*-----------------------------------------------------------------*
 | IsStrHora    Retorna True se a String dada for uma data válida  |
 |              no formato HH:MM ou HH:MM:SS                       |
 *-----------------------------------------------------------------*/
function IsStrHora(Dado)
	{
    var Hor, Min, Seg;
    var Result = false;

	// Pré-analisa o String:
	if (Dado != "")
		{
		if (((Dado.length == 5) || (Dado.length == 8)) && (Dado.substr(2,1) == ":"))
			{
			// Levanta Campos:
			if (IsStrNum(Dado.substr(0,2))) Hor = Dado.substr(0,2); else Hor = -1;
			if (IsStrNum(Dado.substr(3,2))) Min = Dado.substr(3,2); else Min = -1;

			// Analisa a Hora:
			if ((Hor >= 0) && (Hor <= 23))
				{
				// Analisa o Minuto:
				if ((Min >= 0) && (Min <= 59))
					{
					// Verifica se tem segundo:
					if (Dado.length == 8)
						{
						// Pré-analisa:
						if (Dado.substr(5,1) == ":")
							{
							// Levanta e verifica segundos:
							if (IsStrNum(Dado.substr(6,2))) Seg = Dado.substr(6,2); else Seg = -1;
							if ((Seg >= 0) && (Seg <= 59))
								{
								Result = true;
								}
							}
						}
					else
						{
						Result = true;
						}
					}
				}
			}
		}
	return Result;
	}

/*-----------------------------------------------------------------*
 | SeparaNomeArq       Separa o Nome de Arquivo do Path completo   |
 |                                                                 |
 *-----------------------------------------------------------------*/
function SeparaNomeArq(PathDado)
	{
	var i

	if (PathDado.length == 0) return "";

	for (i=PathDado.length-1; i>=0; i--)
		{
		if (PathDado.substr(i,1) == "\\" || PathDado.substr(i,1) == ":")
			{
			return PathDado.substr(i + 1);
			}
		}
	return PathDado;
	}

/*-----------------------------------------------------------------*
 | StrD      Acerta a String na Largura dada com                   |
 |           Alinhamento à Direita:                                |
 *-----------------------------------------------------------------*/
function StrD(Dado, Larg)
	{
    var Result;
	var i;

    if (Dado.length >= Larg)
        {
        Result = Dado.substr(Dado.length - Larg,Larg);
		}
    else
		{
		Result = "";
		for (i=Larg-Dado.length; i>0; i--)
			{
			Result = Result + " ";
			}
        Result = Result + Dado;
		}
	return Result;
	}

/*-----------------------------------------------------------------*
 | StrE      Acerta a String na Largura dada com                   |
 |           Alinhamento à Esquerda:                               |
 *-----------------------------------------------------------------*/
function StrE(Dado, Larg)
	{
    var Result;
	var i;

    if (Dado.length >= Larg)
        {
        Result = Dado.substr(0,Larg);
		}
    else
		{
		Result = Dado;
		for (i=Larg-Dado.length; i>0; i--)
			{
			Result = Result + " ";
			}
		}
	return Result;
	}

/*-----------------------------------------------------------------*
 | StrNum    Retorna o valor Numérico em String Dado,              |
 |           formatado na Largura dada:                            |
 *-----------------------------------------------------------------*/
function StrNum(Dado, Larg)
  {
  var Result, sDado, i;

  sDado = Dado.toString();
  if (sDado.length >= Larg)
    {
    Result = sDado.substr(sDado.length - Larg,Larg);
    }
  else
    {
    Result = "";
    for (i=Larg-sDado.length; i>0; i--)
      {
      Result = Result + "0";
      }
    Result = Result + sDado.toString();
    }
  return Result;
  }

/*-----------------------------------------------------------------*
 | PassaDominio        Retorna a String dada, somente com os       |
 |                     caracteres do domínio dado                  |
 *-----------------------------------------------------------------*/
function PassaDominio(StrDado, Dominio)
	{
	var i, j, c;
	var Result;

	Result = "";
	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)
			{
			Result = Result + c;
			}
		}
	return Result;
}


/*-----------------------------------------------------------------*
 | BloqueiaDominio     Retorna a String dada retirando os          |
 |                     caracteres do domínio dado                  |
 *-----------------------------------------------------------------*/
function BloqueiaDominio(StrDado, Dominio)
	{
	var i, j;

	Result = "";
	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)
			{
			Result = Result + c;
			}
		}
	return Result;
	}

/*******************************************************************
 *  Funções de Filtro para uso com Text-Boxes:                     *
 *  Utilize-as sob os eventos OnKeyUp e OnChange simultaneamente.  *
 *******************************************************************/

function FiltroNum(Objeto)
	{
	Objeto.value = PassaDominio(Objeto.value, "0123456789");
	}

function FiltroInt(Objeto)
	{
	Objeto.value = PassaDominio(Objeto.value, "0123456789+-");
	}

function FiltroCurr(Objeto)
	{
	Objeto.value = PassaDominio(Objeto.value, "0123456789+-,.");
	}

function FiltroVlr(Objeto)
	{
	Objeto.value = PassaDominio(Objeto.value, "0123456789.");
	}

function FiltroFloat(Objeto)
	{
	Objeto.value = PassaDominio(Objeto.value, "0123456789+-Ee,.");
	}

function FiltroData(Objeto)
	{
	Objeto.value = PassaDominio(Objeto.value, "0123456789/");
	}

function FiltroHora(Objeto)
	{
	Objeto.value = PassaDominio(Objeto.value, "0123456789:");
	}

function FiltroUp(Objeto)
	{
	Objeto.value = Objeto.value.toUpperCase();
	}



//limita tamanho para textarea
//-----------------------------------------------------------------------
function fMaxTamCampo(TamMax,ValCampo)
{
	Campo = ValCampo.value
	TamanhoCampo = Campo.length
	if (TamanhoCampo > TamMax)
		{
		ValorCampo = Campo.substring(0,TamMax)
		ValCampo.value = ValorCampo
		alert("O limite máximo do campo é de " +TamMax+ " caracteres.")
	}
}
//-----------------------------------------------------------------------


function ValidaEMail(EMail)
  {
  if (EMail.indexOf("@") < 0) return false;
  if (EMail.indexOf(".") < 0) return false;
  if (ContemDominio(EMail, " ;,:/$!#%^&*()+[]{}|\\~`'\"")) return false;
  return true;
  }

/*-----------------------------------------------------------------*
 | isNumber		  Retorna True se o String dada for um número      |
 |                com casas decimais dadas.                        |
 *-----------------------------------------------------------------*/
function isNumber(sNumero, iDecimais)
  {
  var bRet
  var i
  bRet = true
  if (iDecimais > 0)
    {
    if (sNumero.length < iDecimais + 2 || (sNumero.indexOf(".", 0) == -1 && 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) != "." && 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........: FmtData
 Descricao...: Insere a máscara de data no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em dd/mm/yyyy, não permitindo a digitação
               de caracteres alfa
*/

function FmtData_old(Dado)
  {
   	var Result = Dado;

	 	for (i=1; i<=Dado.length; i++)
		{
			if (i == 2)
			{
				Result = Dado.substr(0, 2) + "/" + Dado.substr(2, i);
			}
			if (i >= 4)
			{
				Result = Dado.substr(0, 2) + "/" + Dado.substr(2, 2) + "/" + Dado.substr(4, 4);
			}
		}
   return Result;
  }

function Fmtcep(Dado)
  {
  var Result = Dado;
  var l = Dado.length;

  if((l > 2) && (l < 6))
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3);
    }
  if(l >= 6)
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3) + "-" + Dado.substr(5, 3);
	}
  return Result;
  }



function FmtData(Dado)
  {
  var Result = Dado;
  var l = Dado.length;

  if((l > 2) && (l < 5))
    {
	Result = Dado.substr(0, 2) + "/" + Dado.substr(2, 2);
    }
  if(l >= 5)
    {
	Result = Dado.substr(0, 2) + "/" + Dado.substr(2, 2) + "/" + Dado.substr(4, 4);
	}
  return Result;
  }


/*
 Nome........: FmtDataMesAno
 Descricao...: Insere a máscara de data no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em mm/yyyy, não permitindo a digitação
               de caracteres alfa
*/
function FmtDataMesAno(Dado)
  {
   	var Result = Dado;

	 	for (i=1; i<=Dado.length; i++)
		{
			if (i == 2)
			{
				Result = Dado.substr(0, 2) + "/" + Dado.substr(2, i);
			}
			if (i > 2)
			{
				Result = Dado.substr(0, 2) + "/" + Dado.substr(2, 4);
			}
		}
   return Result;
  }

  /*
 Nome........: FmtHora
 Descricao...: Insere a máscara de hora no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em hh:mm, não permitindo a digitação
               de caracteres alfa
*/

function FmtHora(Dado)
  {
   	var Result = Dado;

	 	for (i = 1; i <= Dado.length; i++)
		{

			if (i >= 3)
			{
				Result = Dado.substr(0, 2) + ":" + Dado.substr(2, 2);
			}
		}
   return Result;
  }

var bPula = true;

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


function fPulaCampo(campo1,campo2,iTam,tpcampo)
	{
		if(bPula)
		{

			if (tpcampo == "data")
				{
			    	Filtro(campo1,'data');
				}
				if (tpcampo == "hora")
				{
			    	Filtro(campo1,'hora');
				}
			if (campo1.value.length >= iTam)
			{
				campo2.focus();
			}

		}

		return;

	}


/*-----------------------------------------------------------------*
 | CalculaDigitoMod11(Dado, NumDig, LimMult)					   |
 |    Retorna o(s) NumDig Dígitos de Controle Módulo 11 do	   	   |
 |	  Dado, limitando o Valor de Multiplicação em LimMult:         |
 |		    													   |
 |		    Números Comuns::   			iDigSaida	 iCod          |
 |			  CGC					  	  2			   9		   |
 |   		  CPF					  	  2			  12		   |
 |			  C/C,Age - CAIXA			  1 		   9           |
 |			  habitação/bloqueto		  1 		   9           |
 *-----------------------------------------------------------------*/
function CalculaDigitoMod11(Dado, NumDig, LimMult)
  {
  var Mult, Soma, i, n;

  for(n=1; n<=NumDig; n++)
    {
    Soma = 0;
    Mult = 2;
    for(i=Dado.length-1; i>=0; i--)
      {
      Soma += (Mult * parseInt(Dado.charAt(i)));
      if(++Mult > LimMult) Mult = 2;
      }
    Dado += ((Soma * 10) % 11) % 10;
    }
  return Dado.substr(Dado.length-NumDig, NumDig);
  }

function CalculaDigitoMod10(sValor)
{
 mult = 2
 soma = 0
 str = new String()
 sValor = sZapDummy(sValor)

 for (t=sValor.length;t>=1;t--)
 {
 str = (mult*parseInt(sMid(sValor,t,1))) + str
 mult--
 if (mult<1) mult = 2
 }

 for (t=1;t<=str.length;t++)
 soma = soma + parseInt(sMid(str,t,1))
 soma = soma % 10
 if (soma != 0)
   soma = 10 - soma
 str = soma   //casting
 return str
}


function Mod10(valor)
{
  val = valor.substring( 0 , valor.length - 1 )
  dig = valor.substring( valor.length - 1 , valor.length )
  str = new String
  fator = 2
  soma = 0
  for(i = val.length; i > 0; i--)
  {
  str = fator * parseInt(val.substring(i, i - 1)) + str
  fator--
  if(fator < 1) fator = 2
  }
  for(i = 0; i < str.length; i++) soma = soma + parseInt(str.charAt(i))
  soma = soma % 10
  if(soma != 0) soma = 10 - soma
  str = soma //aqui existe uma espécie de "casting" (conversão)
  return str == dig
}



function isBissexto(iAno)
{
  var bRet
  bRet = false
  if (iAno % 4 == 0 && (iAno % 100 !=0 || iAno % 400 ==0 ))
    bRet = true
  return bRet
}


function isDate(sData)
{
  var bRet
  var i
  bRet = true
  if (sData.length != 10)
    bRet = false
  if (bRet)
  {
    i = 0
    while (i < sData.length && bRet)
    {
      if (i == 2 || i == 5)
      {
        if (sData.charAt(i) != "/")
          bRet = false
      }
      else
      {
        if (!isNumber(sData.charAt(i), 0))
          bRet = false
      }
      i++
    }
  }
  if (bRet)
  {
    iDia = parseInt(sData.substring(0, 2), 10)
    iMes = parseInt(sData.substring(3, 5), 10)
    iAno = parseInt(sData.substring(6, 10), 10)
    if (iMes < 1 || iMes > 12)
      bRet = false
    if (iAno < 1)
      bRet = false
  }
  if (bRet)
  {
    if (iMes == 1 || iMes == 3 || iMes == 5 || iMes == 7 || iMes == 8 || iMes == 10 || iMes == 12)
    {
      if (iDia < 1 || iDia > 31)
        bRet = false
    }
    if (iMes == 2)
    {
      if (isBissexto(iAno))
      {
        if (iDia < 1 || iDia > 29)
          bRet = false
      }
      else
      {
        if (iDia < 1 || iDia > 28)
          bRet = false
      }
    }
    if (iMes == 4 || iMes == 6 || iMes == 9 || iMes == 11)
    {
      if (iDia < 1 || iDia > 30)
        bRet = false
    }
  }
  return bRet
}


function sRight(sExpressao,iNumeros)
{
  if (sExpressao.length >= iNumeros ) return sExpressao.substring(sExpressao.length - iNumeros,sExpressao.length)
}

function sLeft(sExpressao,iNumeros)
{
  if (sExpressao.length >= iNumeros ) return sExpressao.substring(0,iNumeros)
}

function sMid(sExpressao,iNumeros,iTamanho)
{
  var aux = new String()
  if ((sExpressao.length >= iNumeros) && (iNumeros >=0) && (iTamanho > 0))
  {
    iNumeros--
    aux = sExpressao.substring(iNumeros,iNumeros+iTamanho)
  }
    return aux
}

function sZapDummy(sStringNum)
{
  var sAux = new String()
  for (t=1;t<=sStringNum.length;t++)
  if (!isNaN(parseInt(sMid(sStringNum,t,1))))
    sAux = sAux + sMid(sStringNum,t,1)
  return sAux
}

function Filtro(Objeto,tpCampo) {
    if (navigator.appName.substr(0,9) != "Microsoft") {
        return;
    }

    if (window.event.keyCode == 37 || window.event.keyCode == 8
            || window.event.keyCode == 36 || window.event.keyCode == 46
            || window.event.keyCode == 16 || window.event.keyCode == 9)
        return;

    if (window.event.keyCode == 111 || window.event.keyCode == 191) {
	    if (tpCampo == "data") {
		    if (Objeto.value.length == 3 || Objeto.value.length == 6) {
			    return;
		    }
		    if (Objeto.value.length == 4 || Objeto.value.length == 7) {
			    var newpos = Objeto.value.length - 1;
			    Objeto.value = Objeto.value.substring(0,newpos);
			    return;
		    }
	    }
    }

    if (window.event.keyCode == 39) {
	    if (tpCampo == "data") {
            if (Objeto.value.length == 2 || Objeto.value.length == 5) {
			    Objeto.value = Objeto.value + "/";
            }
        }
        return;
    }

	if (tpCampo == "orgaoEmissor") {
    	Objeto.value = PassaDominio(Objeto.value, "0123456789ABCDEFGHIJLMNOPQRSTUVXZabcdefghijlmnopqrstuvxz");
		Objeto.value = FmtLacre(Objeto.value);
		return;
	}

	Objeto.value = PassaDominio(Objeto.value, "0123456789");
	if (tpCampo == "data") {
		Objeto.value = FmtData(Objeto.value);
	}
	if (tpCampo == "cep") {
		Objeto.value = Fmtcep(Objeto.value);
	}
	if (tpCampo == "DataMesAno") {
		Objeto.value = FmtDataMesAno(Objeto.value);
	}
	if (tpCampo == "valor") {
		Objeto.value = FmtCurr(Objeto.value);
	}
	if (tpCampo == "hora") {
		Objeto.value = FmtHora(Objeto.value);
	}
	if (tpCampo == "lacre") {
		Objeto.value = FmtLacre(Objeto.value);
	}
	if (tpCampo == "cpf") {
	    Objeto.value = FmtCpf(Objeto.value);
	}
}

function FmtLacre(Dado)
{
	var Result, i;

	Dado = TiraTracos(Dado);

	if (Dado.length > 2)
	{
		Result = "-" + Dado.substr(Dado.length-2, 2);
		Result = Dado.substr(0, Dado.length-2) + Result;
	}
	else
	{
		Result = Dado;
	}
	return Result;
}

function FmtCurr(Dado)
  {
  var Result, i;

  if (Dado.length > 2)
    {
    Result = "," + Dado.substr(Dado.length-2, 2);
    for (i=5; i<=Dado.length; i+=3)
      {
      Result = Dado.substr(Dado.length-i, 3) + Result;
      if (Dado.length > i) Result = "." + Result;
      }
    Result = Dado.substr(0, Dado.length-i+3) + Result;
    }
  else
    {
    Result = Dado;
    }
  return Result;
}

function TiraPontos (NumeroFormatado)
{
    var s
    s  = NumeroFormatado.split (".");
    return s.join("");
}

function TiraVirgula (NumeroFormatado)
{
    var s
    s  = NumeroFormatado.split (",");
    return s.join("");
}

function TiraTracos (NumeroFormatado)
{
    var s
    s  = NumeroFormatado.split ("-");
    return s.join("");
}

function printit()
{
	window.print();
}

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();
}

/* --------------------------------------------------------
	Nome: gfunCalcCEI
	Descricao: Verifica se o nro do CEI eh valido
	Parametros: Numero do CEI sem Formatacao
-------------------------------------------------------- */

function gfunCalcCEI(strCei)
{
	var numLen;
	var strChar;
	var numSomat;
	var strAux;
	var strCharAux;
	var strSomat;
	var numLenumSomat;
	var numAux;
	var numDigit;

	numLen = strCei.length;

	//Verifica se o tamanho do CEI eh de 12 posicoes
	if	(numLen != 12)
	{
		return false;
	}

	// Calcula o digito verificador
	strAux = "74185216374"
	numSomat = 0;
	for (i = 0; i < 11; i++)
	{
		strChar = strCei.charAt(i)
		strCharAux = strAux.charAt(i)
		numSomat += (eval(strChar)) * (eval(strCharAux));
	}
	strSomat = numSomat + "";
	numLenumSomat = strSomat.length;
	numAux = parseInt(strSomat.charAt(numLenumSomat - 1)) + parseInt(strSomat.charAt(numLenumSomat - 2));

	if	((numAux >= 11) && (numAux <= 18))
		numDigit = 20 - numAux;
	else
		if	(numAux == 10)
			numDigit = 1;
		else
			numDigit = 10 - numAux;

	if (numDigit == 10)
	{
	   numDigit = 1
	}

	//	Condicao para atender ao SFG. Aceitar o digito informado (0 ou 1), mesmo que o
	//	resultado do calculo seja igual a 1

	if ((strCei.charAt(11) < "2"))
	{
	 if ((numDigit == 0) || (numDigit == 1))
	 {
		numDigit = eval(strCei.charAt(11));
		return true;
	 }
	}

	// Fim-condicao
	if	(eval(strCei.charAt(11)) != numDigit)
	{
		return false;
	}

	return true;
}

/*--------------------------------------------
'nome...: Recarrega combo com valor informado
----------------------------------------------*/
function recCombo(campo,valor)
{
	for (i=0;i < eval(campo + '.options.length') ;i++)
	{
		if (eval(campo + '[i].value') == valor)
		{
			eval(campo + '.options[i].selected = true');
			break;
		}
	}
	return;
}


/*--------------------------------------------
'nome...: Recarrega combo com valor informado
----------------------------------------------*/
function recComboConvenio(campo,valor)
{
	for (i=0;i < eval(campo + '.options.length') ;i++)
	{
		if (eval(campo + '[i].value').substring(0,6) == valor)
		{
			eval(campo + '.options[i].selected = true');
			break;
		}
	}
	return;
}
/*-----------------------------------------------------------------*
'nome...: RTRIM
 *-----------------------------------------------------------------*/
function RTrim(StrDado) {
    TemEspaco = true;

    sCampo = StrDado
	if (sCampo != "") {
        while (TemEspaco) {

            if (sCampo.substr(sCampo.length - 1,1) == ' ') {
                sCampo = sCampo.substr(0,sCampo.length - 1);
            }
            else {
                TemEspaco = false;
            }
        }
    }
	return sCampo;
}

var iTimerOtico;
var oldServOtico;
function SaibaMaisOtico() {
    oldServOtico = document.FormMenu.serv.value;
    document.FormMenu.serv.value = "LeituraOptica";
    TelaAjuda();
    iTimerOtico = window.setTimeout("atualizaSaibaMais()", 2000);
    document.FormMenu.serv.value = oldServOtico;
}

function atualizaSaibaMais() {
    document.FormMenu.serv.value = oldServOtico;
    window.clearTimeout(iTimerOtico);
}

function fPulaCampoOtico(nomeform,campo1,campo2,tam,tpcampo) {
    if (!eval('document.' + nomeform + '.chkLeitorOptico.checked')) {
        campo1 = eval('document.' + nomeform + '.' + campo1);
        campo2 = eval('document.' + nomeform + '.' + campo2);
        fPulaCampo(campo1,campo2,tam,tpcampo);
    }
    return;
}

function verificaAgend(nomeForm,dataAgend) {
    if (dataAgend != "") {
        nomeForm.rdoAgendamento[1].checked = true;
    }
}

function alteraAgend(nomeForm, dataAgend) {
    if (nomeForm.rdoAgendamento[1].checked) {
        dataAgend.disabled = false;
        dataAgend.focus();
    } else {
        dataAgend.value = "";
        dataAgend.disabled = true;
    }
}

function verificaBrowserImpressao() {
    if (navigator.appName.substr(0,9) != "Microsoft") {
	    window.print();
	    history.back();
    }
}

function imprimeDireto(uri,altura,largura) {
    janela = window.open(uri,"Imprimir","top=10,left=10,width="+largura+",height="+altura+",maximized=no,toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,scrolling=yes,resizable=yes");
    janela.focus();
}

function imprimeTeste(nomeForm, uri) {
    nomeForm.action=uri;
	nomeForm.submit();
}

function focoProximoElemento(nomeForm, nomeCampo) {
    for (i = 0; i < nomeForm.length-1; i++) {
        if (nomeForm.elements[i].name == nomeCampo) {
            if ((nomeForm.elements[i+1].type != "hidden")
                    && (nomeForm.elements[i+1].name != nomeCampo)) {
                nomeForm.elements[i+1].focus();
                break;
            } else {
                nomeCampo = nomeForm.elements[i+1].name;
            }
        }
    }
}

function limpaCamposTxt(nomeForm) {
    for (i = 0; i < nomeForm.length; i++) {
        if (nomeForm.elements[i].type == "text") {
            nomeForm.elements[i].value = "";
        }
    }
}

/* Retorna o DV do IPTU (tipo="1") / ISS (tipo="0") */
function calculaDAC11A(numero, tipo) {
    var intPeso = 2;
    var intCalcula = 0;

    for (var intPosicao = (numero.length-1); intPosicao >= 0; intPosicao --) {
        // soma o produto das multiplicações do dígito pelo peso
        intCalcula += (intPeso * parseInt(numero.charAt(intPosicao), 10));
        intPeso ++;
        if (intPeso == 11) {
            intPeso = 1;
        }
    }

    // divide a soma dos produtos por 11
    intCalcula = intCalcula % 11;

    // monta retorno a partir de intCalcula
    if (intCalcula == 0) {
        return "0";
    } else if (intCalcula == 1) {
        return tipo;
    } else {
        return 11 - intCalcula;
    }
}

function CalculaDigitoMod1129(valor) {
    mult = 2;
    somaTotal = 0;
    for (j=valor.length;j>0;j--) {
        soma = (mult * parseInt(valor.substring(j,j-1),10));
        if (parseInt(soma,10) > 9) {
            soma = soma.toString();
            soma = parseInt(soma.substring(0,1),10)
                    + parseInt(soma.substring(1,2),10);
        }
        somaTotal = somaTotal + soma;
        mult++;
        if (mult > 9) mult = 2;
    }
    resto = somaTotal % 11;

    if (resto == 0 || resto == 1) {
        dig = 1;
    } else {
        dig = 11 - resto;
    }
    return dig;
}
// Sets cookie values. Expiration date is optional
function setCookie(name, value) {
    var today = new Date();
    var expires = new Date();
    expires.setTime(today.getTime() + 1000*60*60*48*365);
    document.cookie = name + "=" + escape(value)
        + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
}

//The following function returns a cookie value, given the name of the cookie
function getCookie(Name) {
    var search = Name + "="
    if (document.cookie.length > 0) {
        // if there are any cookies
        offset = document.cookie.indexOf(search)
        if (offset != -1) {
            // if cookie exists
            offset += search.length
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset)
            // set index of end of cookie value
            if (end == -1)
            end = document.cookie.length
            return unescape(document.cookie.substring(offset, end))
        }
    }
    return "";
}

/*-----------------------------------------------------------------*
 | 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;
}

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

function fVerificaEnter( oEvent, funcao) {
	if (oEvent.keyCode == 13) {
		oEvent.returnValue = 0;
		eval(funcao);
	}
}

/*-----------------------------------------------------------------------------
 Nome:      fPassaAlfaNumerico2(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: 32 - 47    espaco ! " # $ % & ' ( ) * + , - . /
                    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 >= 32 ) && (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;
        }
    }
}*/

function fPassaAlfaNumerico(oEvent, strTipo) {
	  if ( ( (oEvent.keyCode >= 32 ) && (oEvent.keyCode <= 47 ) ) ||
         ( (oEvent.keyCode >= 58 ) && (oEvent.keyCode <= 64 ) ) ||
         ( (oEvent.keyCode >= 91 ) && (oEvent.keyCode <= 96 ) ) ||
         ( (oEvent.keyCode >= 123) 						   )) {
        oEvent.returnValue = 0;
    }
    //-- Letras
    if( (strTipo == "a") || (strTipo == "A") ) {
        if ( (oEvent.keyCode >= 48 ) && (oEvent.keyCode <= 57 ) ) {
            oEvent.returnValue = 0;
        }
    }
    //-- N?meros
    if( (strTipo == "n") || (strTipo == "N") ) {
        if ( ( (oEvent.keyCode >= 65 ) && (oEvent.keyCode <= 90 ) ) ||
             ( (oEvent.keyCode >= 97 ) && (oEvent.keyCode <= 122) ) ||
             ( (oEvent.keyCode == 32 )                           ) ) {
            oEvent.returnValue = 0;
        }
    }
}

function TamanhoMaximo(campo, valor) {
    if (campo.value.length > valor) {
        campo.value = campo.value.substring(0,valor);
    }
}

/*-----------------------------------------------------------------*
  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+$/,'');
}

/*-----------------------------------------------------------------*
 | ComparaDatas    Retorna 0 se strData1 e strData2 forem iguais   |
 |				   Retorna 1 se a strData1 for maior que strData2  |
 |				   Retorna 2 se a strData1 for menor que strData2  |
 *-----------------------------------------------------------------*/
function ComparaDatas (strData1, strData2) {
    // Verifica se os inteiros s?o iguais
    if (strData1 == strData2) {
        return 0;
    }

    // Colocar as datas no formato aaaammdd para compara??o
    strData1 = strData1.substr(6, 4) + strData1.substr(3, 2) +
            strData1.substr(0, 2)

    strData2 = strData2.substr(6, 4) + strData2.substr(3, 2) +
            strData2.substr(0, 2)

    // Monta o retorno
    return strData1 > strData2 ? 1 : 2;
}

/*
 Nome........: ValidaNomeArquivo
 Descricao...: Valida extens?o de arquivo
 Parametros..: nomeArquivo - Nome do Arquivo
               listaExtensao - Lista de extensao v?lidas para o nome do arquivo
               separados por v?rgula e sem espa?os entre as extens?es. Ex:".jpg,.doc"
 Retorno.....: Retorna true
*/

function ValidaNomeArquivo(nomeArquivo, listaExtensao) {
    var arrExtensao = listaExtensao.split(",");
    var ponto = nomeArquivo.lastIndexOf(".");
    for(i=0;i<arrExtensao.length;i++) {
        if(nomeArquivo.substring(ponto).toLowerCase() == arrExtensao[i]) {
            return true;
        }
    }
}

/*
 Nome........: validaVazio
 Descricao...: Valida se campo esta vazio ou nao
 Parametros..: Objeto - campo a ser validado
               mensagem - mensagem de erro caso campo esteja vazio
 Retorno.....: Retorna true - se campo n?o vazio, false - se campo vazio
*/


function validaVazio(Objeto, mensagem)
{
	if(Objeto.value == "") {
		alert(mensagem);
		Objeto.focus();
		return false;
	}
	return true;
}


// valida CPF

function fConsisteCPF(intNumeroCPF) {
	var intDigitoCPF;

	//retira os caracteres '.','/' e '-' da string
	intNumeroCPF = fTrocaListaCaracterPorString(intNumeroCPF, "\./\-", "", "i")
	//separa o d?gito verificador
	intDigitoCPF = intNumeroCPF.substr(intNumeroCPF.length-2);
	//separa o n?mero sem d?gito verificador
	intNumeroCPF = intNumeroCPF.substring(0, intNumeroCPF.length-2);

	//calcula o d?gito verificador e verifica se ? igual ao recebido
	if ( fCalculaDigitoMod11(intNumeroCPF, 1) == intDigitoCPF ) {
		return true;
	} else {
		return false;
	}
}

// utilizada no teclado

function ShowDiv(idDiv, oper) {

    var el;
    var i;
    var d = document;

    if(d.getElementById) {
        // Netscape > 6:
        el = d.getElementById(idDiv);
        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") + "';");
        }
    }
}

function ShowDiv2(idDiv, oper) {

    var el;
    var i;
    var d = document;

    if(d.getElementById) {
        // Netscape > 6:
        el = d.getElementById(idDiv);
        el.style.visibility = (oper) ? "visible" : "hidden";
        el.style.position = (oper) ? "relative" : "absolute";
    } 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";
                    d.layers[i].position = (oper) ? "relative" : "absolute";
                }
            }
        } else {
            // IE:
            eval(idDiv + ".style.visibility='" + ((oper) ? "visible" : "hidden") + "';");
            eval(idDiv + ".style.position='" + ((oper) ? "relative" : "absolute") + "';");
        }
    }
}

// foco no campo recebendo par = document.form.nomeCampo

function focaliza(par) {
    par.focus();
}

/**
 * Valida com v?rias regras a Senha Internet Informada
 *
 * entrada: senhaInternet --> String composta de 6 a 8 caracteres.
 * saida:  	true - senha v?lida
 *      	false - senha inv?lida
 */

function ValidaSenhaInternet(senha) {

    var numerosIda;
    var letrasMaiusculasIda;
    var letrasMinusculasIda;
    var numerosVolta;
    var letrasMaiusculasVolta;
    var letrasMinusculasVolta;
    var sequencial;
    var numCaracteresIguais;

    // Carrega as variaveis de ida e volta
    numerosIda = "0123456789";
    numerosVolta = "9876543210";
    letrasMaiusculasIda = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    letrasMaiusculasVolta = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
    letrasMinusculasIda = letrasMaiusculasIda.toLowerCase();
    letrasMinusculasVolta = letrasMaiusculasVolta.toLowerCase();

    sequencial = numerosIda + "||"
                + letrasMaiusculasIda + "||"
                + letrasMinusculasIda
                + numerosVolta + "||"
                + letrasMaiusculasVolta + "||"
                + letrasMinusculasVolta;

    window.status = "";

    // Verificando a inclus?o de caracteres especiais...
    for (i=0; i<senha.length; i++) {
        if (sequencial.indexOf(senha.charAt(i)) == -1 || senha.charAt(i) == '|') {
            //window.status = "Existe(m) caracter(es) especial(is)!";
            return false;
        }
    }

    // Verificando se a senha ? alfanumerica...
    if (IsNumber(senha)) {
        //window.status = "A senha nao e alfanumerica!";
        return false;
    }

    for (i=0; i<senha.length; i++) {
        var c = senha.charAt(i);
        if (i+2 < senha.length) {
            // Verificando se tem 3 caracteres iguais sequ?nciais...
            if (c == senha.charAt(i+1) && c == senha.charAt(i+2)) {
                //window.status = "A senha veio com 3 caracteres iguais sequenciais!";
                return false;
            }

            // Verificando se tem n?meros ou letras sequ?ncias...
            if (sequencial.indexOf(senha.substring(i,i+3)) != -1)  {
                //window.status = "A senha veio com 3 caracteres iguais sequenciais!";
                return false;
            }
        }

        // Verificando se tem 3 caracteres iguais alternados...
        numCaracteresIguais = 0;
        for (j=0; j<senha.length; j++) {
            if (c == senha.charAt(j)) {
                numCaracteresIguais++;
            }
            if (numCaracteresIguais > 2) {
                //window.status = "Existem 3 caracteres iguais alternados!";
                return false;
            }
        }

        // Verificando os alternados...
        var indiceAnterior = -1;
        var indicePosterior = -1;
        var indiceAtual = sequencial.indexOf(c);
        if (i>0 && indiceAtual!=0) {
            indiceAnterior  = senha.indexOf(sequencial.charAt(indiceAtual-1));
        }
        if (indiceAtual != 121) {
            indicePosterior = senha.indexOf(sequencial.charAt(indiceAtual+1));
        }

        // Verificando se os indices anteriores e posteriores sao diferentes de -1 e i maior que zero
        if ((indiceAnterior > -1 && indicePosterior > -1) && (i > 0)) {
            // Verificando n?meros ou letras sequ?nciais alternados. ex: a1b4c7, a1n2m3, a3c2g1, 1c3ba5...
            if ((indiceAnterior < i && i < indicePosterior) || (indiceAnterior > i && i > indicePosterior)) {
                //window.status = "A senha informada cont?m n?meros ou letras sequ?nciais alternados!";
                return false;
            }
        }
    }
    //window.status = "Senha internet valida!";
    return true;
}

/**
 * Valida com v?rias regras a Senha ou Assinatura da conta Informada
 *
 * entrada: senha --> String composta de 6.
 * saida:  	true - senha v?lida
 *      	false - senha inv?lida
 */

function ValidaSenha(senha) {

    var numerosIda;
    var letrasMaiusculasIda;
    var letrasMinusculasIda;
    var numerosVolta;
    var letrasMaiusculasVolta;
    var letrasMinusculasVolta;
    var sequencial;
    var numCaracteresIguais;

    // Carrega as variaveis de ida e volta
    numerosIda = "0123456789";
    numerosVolta = "9876543210";

    sequencial = numerosIda + "||"
                + numerosVolta ;

    window.status = "";

    // Verificando a inclus?o de caracteres especiais...
    for (i=0; i<senha.length; i++) {
        if (sequencial.indexOf(senha.charAt(i)) == -1 || senha.charAt(i) == '|') {
            //window.status = "Existe(m) caracter(es) especial(is)!";
            return false;
        }
    }

    // Verificando se a senha ? alfanumerica...
    if (!IsNumber(senha)) {
        //window.status = "A senha nao e alfanumerica!";
        return false;
    }

    for (i=0; i<senha.length; i++) {
        var c = senha.charAt(i);
        if (i+2 < senha.length) {
            // Verificando se tem 3 caracteres iguais sequ?nciais...
            if (c == senha.charAt(i+1) && c == senha.charAt(i+2)) {
                //window.status = "A senha veio com 3 caracteres iguais sequenciais!";
                return false;
            }

            // Verificando se tem n?meros ou letras sequ?ncias...
            if (sequencial.indexOf(senha.substring(i,i+3)) != -1)  {
                //window.status = "A senha veio com 3 caracteres iguais sequenciais!";
                return false;
            }
        }

        // Verificando se tem 3 caracteres iguais alternados...
        numCaracteresIguais = 0;
        for (j=0; j<senha.length; j++) {
            if (c == senha.charAt(j)) {
                numCaracteresIguais++;
            }
            if (numCaracteresIguais > 2) {
                //window.status = "Existem 3 caracteres iguais alternados!";
                return false;
            }
        }

        // Verificando os alternados...
        var indiceAnterior = -1;
        var indicePosterior = -1;
        var indiceAtual = sequencial.indexOf(c);
        if (i>0 && indiceAtual!=0) {
            indiceAnterior  = senha.indexOf(sequencial.charAt(indiceAtual-1));
        }
        if (indiceAtual != 121) {
            indicePosterior = senha.indexOf(sequencial.charAt(indiceAtual+1));
        }

        // Verificando se os indices anteriores e posteriores sao diferentes de -1 e i maior que zero
        if ((indiceAnterior > -1 && indicePosterior > -1) && (i > 0)) {
            // Verificando n?meros ou letras sequ?nciais alternados. ex: a1b4c7, a1n2m3, a3c2g1, 1c3ba5...
            if ((indiceAnterior < i && i < indicePosterior) || (indiceAnterior > i && i > indicePosterior)) {
                //window.status = "A senha informada cont?m n?meros alternados!";
                return false;
            }
        }
    }
    //window.status = "Senha valida!";
    return true;
}

/*-----------------------------------------------------------------*
  IsNumber
  Descricao   : Verifica se e' um numero
  Parametros  : Numero que cont?m d?gitos de 0 a 9
 *-----------------------------------------------------------------*/
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;
}

/*-----------------------------------------------------------------*
  IsString
  Descricao   : Verifica se e' numero
  Parametros  : numero
 *-----------------------------------------------------------------*/
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;
}

/*-----------------------------------------------------------------*
  IsString
  Descricao   : Verifica se e' string
  Parametros  : string
 *-----------------------------------------------------------------*/
function IsString (valor) {
    var alfa = false;
    var numerico = false;

    if (valor == "") {
        return false;
    }

    for (i=0; i < valor.length; i++) {
        if (valor.charAt(i) < "0" || valor.charAt(i) > "9") {
            alfa = true;
        } else {
            numerico=true;
        }
    }

    if (alfa && numerico) {
        return false;
    } else {
        return true;
    }
}

/**

 * Valida com v?rias regras o Usuario Internet Informado

 *

 * entrada: usuarioInternet --> String composta de 10 a 20 caracteres.

 * saida:            true - usuario v?lido

 *          false - usuario inv?lido

 */



function ValidaUsuarioInternet(usuario) {



    var numerosIda;

    var letrasMaiusculasIda;

    var letrasMinusculasIda;

    var numerosVolta;

    var letrasMaiusculasVolta;

    var letrasMinusculasVolta;

    var sequencial;

    var numCaracteresIguais;



    // Carrega as variaveis de ida e volta

    numerosIda = "0123456789";

    numerosVolta = "9876543210";

    letrasMaiusculasIda = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    letrasMaiusculasVolta = "ZYXWVUTSRQPONMLKJIHGFEDCBA";

    letrasMinusculasIda = letrasMaiusculasIda.toLowerCase();

    letrasMinusculasVolta = letrasMaiusculasVolta.toLowerCase();



    sequencial = numerosIda + "||"

                + letrasMaiusculasIda + "||"

                + letrasMinusculasIda

                + numerosVolta + "||"

                + letrasMaiusculasVolta + "||"

                + letrasMinusculasVolta;



    // Verificando a inclus?o de caracteres especiais...

    for (i=0; i<usuario.length; i++) {

        if (sequencial.indexOf(usuario.charAt(i)) == -1 || usuario.charAt(i) == '|') {

            // window.status = "Digite somente letras e n?meros";

            return false;

        }

    }



    // Verificando se a usuario ? alfanumerica...

    if (IsNumber(usuario)) {

        // window.status = "Deve conter letras do alfabeto";

        return false;

    }



    return true;



}

/**

 *  FIM

*/

function CalculaDigitoMod11_v4(valor) {
    mult = 2;
    somaTotal = 0;
    for (j=valor.length;j>0;j--) {
        soma = (mult * parseInt(valor.substring(j,j-1),10));
        somaTotal = somaTotal + soma;
        mult++;
        if (mult > 9) mult = 2;
    }
    resto = somaTotal % 11;

    if (resto == 0 || resto == 1) {
        dig = 0;
    } else {
        dig = 11 - resto;
    }

    return dig;
}

function changeKey (textControl, evt, keyChecker) {
  var keyCode = evt.keyCode ? evt.keyCode :
                evt.charCode ? evt.charCode :
		evt.which ? evt.which : void 0;
  var key;
  if (keyCode) {
    key = String.fromCharCode(keyCode);
  }
  var keyCheck = keyChecker(keyCode, key);
  if (keyCode && window.event && !window.opera) {
    if (keyCheck.cancelKey) {
      return false;
    }
    else if (keyCheck.replaceKey) {
      window.event.keyCode = keyCheck.newKeyCode;
      if (window.event.preventDefault) {
        window.event.preventDefault();
      }
      return true;
    }
    else {
      return true;
    }
  }
  else if (typeof textControl.setSelectionRange != 'undefined') {
    if (keyCheck.cancelKey) {
      if (evt.preventDefault) {

        evt.preventDefault();
      }
      return false;
    }
    else if (keyCheck.replaceKey) {
      // cancel the key event and insert the newKey for the current
      // selection
      if (evt.preventDefault) {
	  evt.preventDefault();
      }
      var oldSelectionStart = textControl.selectionStart;
      var oldSelectionEnd = textControl.selectionEnd;
      var selectedText = textControl.value.substring(oldSelectionStart,
                                                     oldSelectionEnd);
      var newText = typeof keyCheck.newKey != 'undefined'
                    ? keyCheck.newKey
                    : String.fromCharCode(keyCheck.newKeyCode);
      textControl.value =
        textControl.value.substring(0, oldSelectionStart) +
        newText +
        textControl.value.substring(oldSelectionEnd);
      textControl.setSelectionRange(oldSelectionStart + newText.length,
                                    oldSelectionStart + newText.length);
      return false;
    }
    else {
      return true;
    }
  }
  else if (keyCheck.cancelKey) {
    if (evt.preventDefault) {
      evt.preventDefault();
    }
    return false;
  }
  else {
    return true;
  }
}

function lettersToUpperCase (keyCode, key) {
  var newKey = key.toUpperCase();
  if (newKey != key) {
    return { replaceKey: true,
             newKeyCode: newKey.charCodeAt(),
             newKey: newKey };
  }
  else {
    return { cancelKey: false };
  }
}

function lnk(param) {


    logado = "";

    if (param != "") {
        if(logado == "true") {
            confirmar_saida(param, 'SaidaIBC','scrollbars=no,width=329,height=230,top=170,left=235,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no');
        } else {
            location.href = param;
        }
    }
}

var janelaIBC = null;
function confirmar_saida(param, name, config) {
    janelaIBC = window.open('<%=apl.getPropriedade(AplDefs.URL_IAS)%>' + 'redireciona.processa?param=' + param, name, config);
}

/*-----------------------------------------------------------------------------
Validação de Incrição Estadual no formato: MMMSSSSSDNND
-----------------------------------------------------------------------------*/
function validaIE1(numero) {
        if (numero.length != 12) {
            return false;
        }

        var MMM = sLeft(numero,3);
        var SSSSS = sMid(numero,4,5);
        var D1 = sMid(numero,9,1);
        var NN = sMid(numero,10,2);
        var D2 = sRight(numero,1);

        if ((MMM < 100) || (MMM > 794 && MMM < 801) || (MMM > 899 && MMM != 999)
            || (!isNumber(SSSSS,0)) || (!isNumber(NN,0))) {
            return false;
        }

        var DV1 = 0;
        var DV2 = 0;
        var pesos1 = [1,3,4,5,6,7,8,10];
        var pesos2 = [3,2,10,9,8,7,6,5,4,3,2];

        for (i = 0; i < 8; i++) {
            DV1 = parseInt(DV1,10) + (parseInt(numero.charAt(i),10) * pesos1[i]);
        }
        DV1 = DV1 % 11;
        if (parseInt(DV1,10) == 10) {
            DV1 = 0;
        }

        if (parseInt(DV1,10) != parseInt(D1,10)) {
            return false
        }

        for (i = 0; i < 11; i++) {
            DV2 = parseInt(DV2,10) + (parseInt(numero.charAt(i),10) * pesos2[i]);
        }
        DV2 = DV2 % 11;
        if (parseInt(DV2,10) == 10) {
            DV2 = 0;
        }

        if (parseInt(DV2,10) != parseInt(D2,10)) {
            return false
        }

        return true;
}

/*-----------------------------------------------------------------------------
Validação de Inscrição Estadual no formato: 0MMMSSSSDOOO
-----------------------------------------------------------------------------*/
function validaIE2(numero) {
        if (numero.length != 12) {
            return false;
        }

        var MMM = sMid(numero,2,3);
        var SSSS = sMid(numero,5,4);
        var D1 = sMid(numero,9,1);
        var OOO = sRight(numero,3);

        if ((MMM < 100) || (MMM > 794 && MMM < 801) || (MMM > 899 && MMM != 999)
            || (!isNumber(SSSS,0)) || (!isNumber(OOO,0))) {
            return false;
        }

        var DV1 = 0;
        var pesos1 = [1,3,4,5,6,7,8,10];

        for (i = 0; i < 8; i++) {
            DV1 = parseInt(DV1,10) + (parseInt(numero.charAt(i),10) * pesos1[i]);
        }
        DV1 = DV1 % 11;
        if (parseInt(DV1,10) == 10) {
            DV1 = 0;
        }

        if (parseInt(DV1,10) != parseInt(D1,10)) {
            return false
        }

        return true;
}

/*-----------------------------------------------------------------------------
Cálculo de Digito Verificador de Còdigod e Município
-----------------------------------------------------------------------------*/
function calculaDVCodMunicipio(numero) {
    if (numero.length != 4) {
        return false;
    }

    var peso = [4,3,2];
    var DV = 0;
    for (i = 0; i < 3; i++) {
        DV = parseInt(DV,10) + (parseInt(numero.charAt(i),10) * peso[i]);
    }
    DV = DV % 11;
    if (parseInt(DV,10) == 10) {
        DV = 0;
    }

    if (parseInt(DV,10) != parseInt(sRight(numero,1))) {
        return false;
    }

    return true;
}

/*-----------------------------------------------------------------------------
	Cálculo de Dígito Verificador de Numero de Declaração
-----------------------------------------------------------------------------*/
function calculaDVDeclaracao(numero) {
    if (numero.length != 9) {
        return false;
    }

    var DV = 0;
    var pesos = [1,3,4,5,6,7,8,10];

    for (i = 0; i < 8; i++) {
        DV = parseInt(DV,10) + (parseInt(numero.charAt(i),10) * pesos[i]);
    }
    DV = DV % 11;
    if (parseInt(DV,10) == 10) {
        DV = 0;
    }

    if (parseInt(DV,10) != parseInt(sRight(numero,1),10)) {
        return false
    }

    return true;
}

/*-----------------------------------------------------------------------------
	Cálculo de Dígito Verificador de Numero de Placa
-----------------------------------------------------------------------------*/
function calcularDVPlaca(numero) {
    if (numero.length != 11) {
        return false;
    }

    var DV = 0;
    var peso = 2;
    for (i = numero.length - 2; i >= 0; i--) {
        DV = parseInt(DV,10) + (parseInt(numero.charAt(i),10) * peso);
        (--peso == 0 ? peso = 2: "");
    }
    DV = DV % 10;

    if (parseInt(sRight(numero,1),10) != parseInt(DV,10)) {
        return false;
    }

    return true;
}

/*-----------------------------------------------------------------------------
	Cálculo de Dígito Verificador de Numero de Etiqueta e Dívida Ativa
-----------------------------------------------------------------------------*/
function validaDVEtiquetaDividaAtiva(numero) {
    if (numero.length != 9 && numero.length != 13) {
        return false;
    }

    if (numero.length == 9) { //Divida Ativa
        var pesos = [1,3,4,5,6,7,8,10];
        var soma = 0;
        for (i = 0; i < 8; i++) {
            soma = parseInt(soma,10) + (parseInt(numero.charAt(i),10) * pesos[i]);
        }
        var digito = soma % 11;
        if (digito == 10) digito = 0;

        return (parseInt(numero.charAt(8)) == digito);
    } else { //Etiqueta
        var soma = 0;
        for (i = 0; i < 12; i++) {
            soma = parseInt(soma,10) + (parseInt(numero.charAt(i),10) * (i+1));
        }
        var digito = soma % 11;
        if (digito == 10) digito = 0;

        return (parseInt(numero.charAt(12)) == digito);
    }
}

/*-----------------------------------------------------------------------------
	Cálculo de Dígito Verificador de Faixa de Ipva
-----------------------------------------------------------------------------*/
function validaDVFaixaIPVA(numero) {
    var peso = 2;
    var soma = 0;
    for (var i = numero.length - 2; i >= 0; i--) {
        soma = parseInt(soma,10) + (parseInt(numero.charAt(i),10) * peso);
        (--peso == 0 ? peso = 2: "");
    }
    var DV = soma % 10;
    return (parseInt(DV,10) == parseInt(sRight(numero,1),10));
}

/*-----------------------------------------------------------------------------
	Cálculo de Dígito Verificador de pelo módulo 11
		tipoValidacao = 1 (CPF, RENAVAM)
		tipoValidacao = 2 (CGC,CONTA,COD BARRAS, BLOQUETO)
-----------------------------------------------------------------------------*/
function sCalculaDigitoMod11Gare(sValor,iDigSaida,sTipoValidacao) {
        if (sTipoValidacao == 1) iCod = 12  // sTipoValidacao=1 - validacao digito verificador: cpf,renavam
        if (sTipoValidacao == 2) iCod = 9   // sTipoValidacao=2 - validacao digito verificador: cgc,conta,cod. barra bloqueto

        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);
}

function calculaDigitoVerificador(numero) {
	var pesos;     // Array que contém os pesos a serem multiplicados
	var soma = 0;  // Acumula a somatória da divisão dos pesos
	var resto = 0; // Resto da divisão

    if (numero.length == 6) {
        pesos = new Array(7);
        pesos = "7,6,5,4,3,2".split(",");
    } else if (numero.length == 8) {
        pesos = new Array(9);
        pesos = "9,8,7,6,5,4,3,2".split(",");
    }

    for (j = 0; j < numero.length; j++) {
        // soma = soma + (dígito do peso * dígito do número)
        soma += pesos[j] * sMid(numero, j + 1, 1);
    }

    // Digito é o algarismo mais a direita do resto
    resto = (soma % 11);
    if (resto >= 10)
        resto = sRight(resto.toString(), 1);

    return resto;
}

function calculaDigitoVerificadorDI(numero) {
	var pesos;     // Array que contém os pesos a serem multiplicados
	var soma = 0;  // Acumula a somatória da divisão dos pesos
	var resto = 0; // Resto da divisão

    if (numero.length == 10) {
        pesos = new Array(11);
        pesos = "3,2,9,8,7,6,5,4,3,2".split(",");
    }

    for (j = 0; j < numero.length; j++) {
        // soma = soma + (dígito do peso * dígito do número)
        soma += pesos[j] * sMid(numero, j + 1, 1);
    }

    // Digito é o algarismo mais a direita do resto
    resto = soma % 11;
    resto = parseInt(11 - resto);
    if (resto >= 10)
        resto = sRight(resto.toString(), 1);

    return Math.abs(resto);
}

function calculaDigitoParcelamento(numero) {
	var pesos = new Array(9); // Array que contém os pesos a serem multiplicados
	var soma = 0;           // Acumula a somatória da divisão dos pesos
	var resto = 0;          // Resto da divisão

    pesos = "8,7,6,5,4,3,2,10".split(",");
    for (j = 0; j < numero.length; j++) {
        // soma = soma + (dígito do peso * dígito do número)
        soma += pesos[j] * sMid(numero, j + 1, 1);
    }

    resto = soma % 11;
    resto = parseInt(11 - resto);
    if (resto == 10)
        resto = 0;

    return Math.abs(resto);
}

function calculaDigitoNotificacao(numero) {
	var pesos = new Array(9); // Array que contém os pesos a serem multiplicados
	var soma = 0;           // Acumula a somatória da divisão dos pesos
	var resto = 0;          // Resto da divisão

    pesos = "8,7,6,5,4,3,2,10".split(",");
    for (j = 0; j < numero.length; j++) {
        // soma = soma + (dígito do peso * dígito do número)
        soma += pesos[j] * sMid(numero, j + 1, 1);
    }

    resto = soma % 11;
    resto = parseInt(11 - resto);
    if (resto == 10)
        resto = 0;

    return Math.abs(resto);
}

function calculaDigitoGuia(numero) {
	var pesos = new Array(12); // Array que contém os pesos a serem multiplicados
	var soma = 0;              // Acumula a somatória da divisão dos pesos
	var resto = 0;             // Resto da divisão

    pesos = "3,2,10,9,8,7,6,5,4,3,2".split(",");
    for (j = 0; j < numero.length; j++) {
        // soma = soma + (dígito do peso * dígito do número)
        soma += pesos[j] * sMid(numero, j + 1, 1);
    }

    // Digito é o algarismo mais a direita do resto
    resto = (soma % 11);
    if (resto >= 10)
        resto = sRight(resto.toString(), 1);

    return Math.abs(resto);
}

function Trim( strDado ){
    return strDado.replace (/^\s+/,'').replace (/\s+$/,'');
}

/*-----------------------------------------------------------------------------
 Formata valores em formato SQL para o Brasileiro.
-----------------------------------------------------------------------------*/
function FormataValorBRA(pValor)
{
	var i;
	var j;
	var iDecimal;
	var iInteiro;
	var iNovoValor;

	iInteiro = pValor;
	iDecimal = '00';

	// Separa a parte Inteira da parte Decimal
	i = 0;
	for (i = 0; i < pValor.length; i++)
	{
		if (pValor.charAt(i) == ".")
		{
			iInteiro = pValor.substring(0,i);
			iDecimal = pValor.substring(i + 1,pValor.length);
		}
	}

	// Formata a parte decimal para duas casas no mínimo.
	if (iDecimal.length == 1)
	{
		iDecimal = iDecimal + "0";
	}

    // Formata a parte decimal para no máximo duas casas.
    if (iDecimal.length > 2) {
        iDecimal = sLeft(iDecimal, 2);
    }

	// Formata a parte Inteira.
	iNovoValor = '';
	j = 0;
	for (i = iInteiro.length; i > 0; i--)
	{
		j = j + 1;
		if (j == 4)
		{
			iNovoValor = iInteiro.substring(i,i-1) + '.' + iNovoValor;
			j = 1;
		}
		else
		{
			iNovoValor = iInteiro.substring(i,i-1) + iNovoValor;
		}
	}

	// Agrega a Parte decimal ao novo valor
	iNovoValor = iNovoValor + "," + iDecimal;

	return (iNovoValor);
}

/*-----------------------------------------------------------------*
 imprimir
 Descricao : Abre popup de impressão
 Parametros: caminho = nome da página
 *-----------------------------------------------------------------*/
function imprimir(caminho) {
	window.open(caminho,'mais','maximized=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,scrolling=yes,resizable=no,width=530,height=400,left=170,top=100');
}
function imprimir2(caminho) {
	window.open(caminho,'mais','maximized=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,scrolling=yes,resizable=no,width=600,height=400,left=170,top=100');
}

/*
 Nome........: FmtCpf
 Descricao...: Insere a máscara de CPF no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em 999.999.999-99, não permitindo 
               a digitação de caracteres alfa
*/

function FmtCpf(Dado)
  {
   	var Result = Dado;
   	var tam = Dado.length;
   	if(tam <= 3) {
   	    Result = Dado;
   	}
   	if(tam > 3 && tam <= 6) {
   	    Result = Dado.substring(0, 3) + "." + Dado.substring(3, tam);
   	}
   	if(tam > 6 && tam <= 9) {
   	    Result = Dado.substring(0, 3) + "." + Dado.substring(3, 6) + "." + Dado.substring(6, tam);
   	}
   	if(tam > 9 && tam <= 11) {
   	    Result = Dado.substring(0, 3) + "." + Dado.substring(3, 6) + "." + Dado.substring(6, 9) + "-" + Dado.substring(9, tam);
   	}
    return Result;
  }

/*-----------------------------------------------------------------*
 ConsisteCPF
 Descricao : verifica a consistencia do CPF.
 *-----------------------------------------------------------------*/

function ConsisteCPF(cpf) {
	var intNumeroCPF;
	var intDigitoCPF;

	//retira os caracteres '.','/' e '-' da string
	intNumeroCPF = cpf.replace(/\./g, "");
	intNumeroCPF = intNumeroCPF.replace(/-/g, "");
	
	//separa o dígito verificador
	intDigitoCPF = intNumeroCPF.substr(intNumeroCPF.length-2);
	//separa o número sem dígito verificador
	intNumeroCPF = intNumeroCPF.substring(0, intNumeroCPF.length-2);

	//calcula o dígito verificador e verifica se é igual ao recebido
	if ( CalculaDigitoMod11(intNumeroCPF, 2, 12) == intDigitoCPF ) {
		return true;
	} else {
		return false;
	}
}




/*--------------------------------------------------------------*
possuiLetrasNumeros()
Descricao: verifica se determinada string possui letras e números e retorna true se verdadeiro
Parametros: palavra - string que sera verificada
Retorno: true se a string possuir letras e numeros e false caso contrario 
*----------------------------------------------------------------*/
function possuiLetrasNumeros(palavra) {
	var strLetras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var temLetra = procuraCaractere(palavra, strLetras);
	var strNum = "01234567890";
	var temNum = procuraCaractere(palavra, strNum);
	return temLetra && temNum;
}


/*--------------------------------------------------------------*
procuraCaractere()
Descricao: verifica se determinada string possui um ou mais caracteres de um conjunto de caracteres informado
Parametros: palavra - string que sera verificada
                     str - conjunto de caracteres que serão verificados na string palavra
Retorno: true se a string possuir pelo menos um caractere de str em palavra e false caso contrario
*----------------------------------------------------------------*/
function procuraCaractere(palavra, str) {
	var retorno = false;
	for (i=0; i < palavra.length && !retorno; i++) {
		if (str.indexOf(palavra.charAt(i)) >= 0) {
			retorno = true;
		}
	}
	
	return retorno;
}

/*--------------------------------------------------------------*
saveAs()
Descricao: Funcao responsavel pelo salvamento das paginas de impressao (botao SALVAR)
*----------------------------------------------------------------*/
function saveAs() {
	document.frmImpressao.hdnSalvarImpr.value = "true";
	document.frmImpressao.submit();
}

/*--------------------------------------------------------------*
alteraTamJanela()
Descricao: Altera o tamanho da janela, tanto na horizontal quanto na vertical
Parametros: horizontal, vertical
*----------------------------------------------------------------*/
function alteraTamJanela(horiz, vert) {
	window.resizeBy(horiz, vert);
}

/*--------------------------------------------------------------*
movimentaJanela()
Descricao: Movimenta a janela na horizontal e vertical, caso os valores informados sejam maiores que zero
Parametros: horizontal, vertical
*----------------------------------------------------------------*/
function movimentaJanela(horiz, vert) {
	var moveHor = (horiz < 0) ? horiz*(-1) : 0;
	var moveVer = (vert < 0) ? vert*(-1) : 0;
	window.moveBy(moveHor, moveVer);
}

/*--------------------------------------------------------------*
alteraMoveJanela()
Descricao: Altera o tamanho da janela e a movimenta na horizontal e na vertical, chamando as funcoes alteraTamJanela() e movimentaJanela() acima
*----------------------------------------------------------------*/
function alteraMoveJanela() {

    return; // 10/11/2007 - retirado temporariamente devido ao problema com WinXP+IE6

	var horiz = Math.floor(Math.random() * 40) + 1;
	var vert = Math.floor(Math.random() * 40) + 1;
	if ((Math.floor(Math.random() * 10) + 1) > 5) {
		horiz *= (-1);
	}
	if ((Math.floor(Math.random() * 10) + 1) > 5) {
		vert *= (-1);
	}
	
	alteraTamJanela(horiz, vert);
	movimentaJanela(horiz, vert);
}

/*--------------------------------------------------------------*
moveMargem()
Descricao: Movimenta o "miolo central" das paginas do siwin, alterando a margem esquerda randomicamente.
                   Tambem decide randomicamente se a janela sera alinhada mais para a esquerda ou mais para a direita.
                   Observacao: o valor "-388" foi retirado do CSS, caso ocorra alterações no CSS, este valor também precisa ser alterado (e vice-versa).				   
*----------------------------------------------------------------*/
function moveMargem() {
	var randomico = Math.floor(Math.random() * 30) + 1;
	var novaMargem = 0;
	if ((Math.floor(Math.random() * 10) + 1) > 5) {
		novaMargem = -388 + randomico;
	} else {
		novaMargem = -388 - randomico;
	}
	var margem = "" + novaMargem + "px";
	document.getElementById("siwin_bkg").style.marginLeft = margem;
}