// ---------------------------------------------------------------------------
//                         funcoes.js
//
// Checar tamanho do textArea							checaTextArea
// Checar campos obrigatórios não preenchidos			checaVazio
// Checar se o email é válido							checaEmail
// Valida email usando expressao regular				validaEmailUsandoRegex
// Abrir uma nova janela e contabilizar acesso			novaJanela
// validar CPF											validarCPF
// Checar Tamanho mínimo e só Letra e/ou Numero			checaLetraNumero
// Limpar campos do formulário							limpaFormulario
// Checar nome e extensao de arquivo					verificaNomeExtensao
// Corrigir Nome										corrigenome
// Chamar página (principal, destino e parâmetro)		chamarPagina
// Chamar publicação (criando form e submetendo			chamarPublicacao
// Chamar diário oficial								chamarDiario
// Nova janela completa e tamanho variável				newWindow
// Checar existência de plica numa string				checaPlica
// validar data											validaData
// validar hora											validaHora
// Colocar barras nas datas quando em KeyPress			colocaBarras
// coloca dois no campo Hora quando em KeyPress			doisPontos
// checar se é número (inclusive ponto decimal)			somenteNumero
// Criar página/novo browser para ampliar foto			ampliaFoto
// Retirar barras do campo data quando em foco			retiraBarras
// Verifica se o campo é numerico (inteiro)				verificaNumerico
// Conta o número de caracteres em campo TEXTAREA       contaCharCampo 
// Checar se foi selecionado um valor numa lista		checaSelecao
// Valida valores do tipo Hora							ValidaHora
// Calcula a diferença em minutos						CalculaDiferencaHHMM
// Calcula a diferença em Segundos						CalculaDiferencaHHMMSS
// Formata campo moeda									formataMoeda
// Valida CNPJ                                          ValidaCNPJ
// Remove simbolos do CNPJ                              RemoveSimbolos
// Cria um cookie para a funcao de Acessibilidade		setCookie
// Captura os dados do cookie criado na função acima	getCookie		
// Remove o cookie										deleteCookie							
// ---------------------------------------------------------------------------

//Verifica o tamanho do campo TextArea
//------------------------------------
//pCampo = campo a ser verificado
//Nome = nome do campo a aparecer no alert

function checaTextArea(pCampo, Nome)
{	
	if (pCampo.value.length > 32767)
	{
		alert("O campo "+Nome+" não pode ter mais que 32.768 caracteres.");
		pCampo.select();
		pCampo.focus();
		return false;
	}
	return true;
}

//Verifica se o campo é numerico
//------------------------------
//pCampo = campo a ser verificado
//Nome = nome do campo a aparecer no alert

function verificaNumerico(pCampo, Nome)
{	
	i=0;
	while (i<pCampo.value.length)
	{
		if (("0123456789").indexOf(pCampo.value.charAt(i))==-1)
		{
			alert("O campo "+Nome+" não é númerico inteiro.");
			return false;
		}
		i++;
	}
	return true;
}

// Checar campos obrigatórios não preenchidos 
// ------------------------------------------
function checaVazio(pElemento, pNome)
	{
	 strBranco = ""; // as String
	 for (i = 1; i <= pElemento.value.length; i = i + 1)
	     {
	      strBranco = strBranco + " "
	     }  
	 if (pElemento.value.length < 1 || pElemento.value == strBranco)
	    {
		 alert("O Campo " + pNome + " não pode ser vazio.");
		 pElemento.focus();
		 pElemento.select();
		 return false;
		}
	 else
		{ 
		 return true;
		}
	}


// Checar se o email é válido
// --------------------------
function checaEmail(pElemento,pQuantidadeMaxima,pSeparador)
{
// inicio codigo antigo
/*
	if (pQuantidade == null)
	{	qtdePrmt = 1;}
	else
	{	qtdePrmt = pQuantidade;}
	if (pElemento.value.lastIndexOf("@") == -1)
	{
		alert("Formato ilegal de E-mail.");
		pElemento.focus();
		pElemento.select();
		return false;
	}
	else
	{
		Tamanho = pElemento.value.length; 
		Quantidade = 0;
		Posicao = 0;
		strLetra = pElemento.value;
		for (i=0; i<Tamanho; i++)
		{
			Letra = strLetra.charAt(i);
			if (Letra == "@") 
			{
				Quantidade = Quantidade + 1;
				Posicao = i;
			}
		}
		if ((Quantidade > qtdePrmt) || (Posicao == 0) || (Posicao > Tamanho -2))
		{
			alert ("Quantidade ou formato ilegal de E-mail.");
			pElemento.focus();
			pElemento.select();
			return false;
		}
		pElemento.value = strLetra;
		return true;
	}
*/ 
// fim codigo antigo



	var arrDestinatarios = pElemento.value.split(pSeparador);
	var qtdadeDestinatarios = arrDestinatarios.length; 	


	if((pQuantidadeMaxima != null) && (qtdadeDestinatarios > pQuantidadeMaxima) )
	{
		alert("Quantidade ilegal de E-mail.");
		pElemento.focus();
		pElemento.select();
		return false;
	}


	for(i = 0; i < qtdadeDestinatarios; i++)
	{		
		if (!validaEmailUsandoRegex(arrDestinatarios[i])) 
		{
			alert("Formato ilegal de E-mail.");
			pElemento.focus();
			pElemento.select();
			return false;
		}			
	}	
	

	return true;	
}



function validaEmailUsandoRegex(pEmail)
{
	// regra em expressao regular
	// antes do @: valem os caracteres a-Z,0-9,.,-,_
	// depois do @: valem os caracteres a-Z,0-9,.,-,_ seguido de "." (ponto)
	// depois do ".": valem os caracteres a-Z (de 2 a 6 sequencias) ou dos numeros 0-9 (de 1 a 3 sequencias)
	var regraExpRegular = /^[A-Za-z0-9\.\-\_]+@[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,6}|[0-9]{1,3})$/;
	var objExpRegular = new RegExp(regraExpRegular)
	if(objExpRegular.exec(pEmail) != null)
	{
		return true;
	}
	else
	{ 
		return false;
	}

}


// Abrir uma nova janela
// ---------------------
function novaJanela(pURL, pFormato, pId) {
	if (pId != null) {
		if (location.href.indexOf(".des.") > 0)
			sLocal = ".des"
		else if (location.href.indexOf(".dchm.") > 0)
			sLocal = ".dchm"
		else
			sLocal = "";
		URLDestino = "http://admin"+sLocal+".es.gov.br/scripts/adm000.asp?id=" + pId + "&to=" + pURL;
	}
	else {
		URLDestino = pURL;
	}
	
 	if (pFormato == null || pFormato == 0)	// janela completa (pq margem em volta)
		var jan1 = window.open(URLDestino,null,"fullscreen=no,channelmode=no,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=700,height=500,top=30,left=50")
	else if (pFormato == 1)	// menor que a completa e sem location
		var jan1 = window.open(URLDestino,null,"fullscreen=no,channelmode=no,toolbar=yes,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=600,height=350,top=50,left=100")
	else if (pFormato == 2)	// somente com barra de rolagem...
		var jan1 = window.open(URLDestino,null,"fullscreen=no,channelmode=no,toolbar=no,location=no,directories=no,status=nos,menubar=no,scrollbars=yes,resizable=no,width=600,height=450,top=50,left=100")
	else if (pFormato == 3)	// somente área para texto...
		var jan1 = window.open(URLDestino,null,"fullscreen=no,channelmode=no,toolbar=no,location=no,directories=no,status=nos,menubar=no,scrollbars=no,resizable=no,width=600,height=450,top=50,left=100")
	else if (pFormato == 4)	// ampliação de foto 550x383 px no formato paisagem 
		var jan1 = window.open(URLDestino,null,"fullscreen=no,channelmode=no,toolbar=no,location=no,directories=no,status=nos,menubar=no,scrollbars=no,resizable=no,width=600,height=450,top=50,left=100")
	else if (pFormato == 5)	// somente com barra de rolagem...
		var jan1 = window.open(URLDestino,null,"fullscreen=no,channelmode=no,toolbar=no,location=no,directories=no,status=nos,menubar=no,scrollbars=yes,resizable=no,width=650,height=450,top=50,left=100")
	else if (pFormato == 6)	// somente com barra de rolagem...
		var jan1 = window.open(URLDestino,null,"fullscreen=no,channelmode=no,toolbar=no,location=no,directories=no,status=nos,menubar=no,scrollbars=yes,resizable=no,width=300,height=250,top=50,left=100");
	return false;
}


// validar CPF
// -----------
function validarCPF(pCampo)
{	
	if (!checaLetraNumero(pCampo,"CPF",11,"N"))
		return false;
		
	var s = pCampo.value;
	soma=0; 
	for ( i=0; i<9; i++ ) 
	{	soma += (10-i) * ( eval(s.charAt(i)) ); 
	}  
	digito_verificador = 11-(soma % 11); 
	if ( (soma % 11) < 2 ) digito_verificador = 0; 
	if ( eval(s.charAt(9)) != digito_verificador ) 
	{	alert("CPF inválido.");
		pCampo.focus(); 
		pCampo.select();
		return false; 
	}  
	soma=0; 
	for ( i=0; i<9; i++ ) 
	{	soma += (11-i) * ( eval(s.charAt(i)) ); 
	} 
	soma += 2 * ( eval(s.charAt(9)) ); 
	digito_verificador = 11-(soma % 11); 
	if ( (soma % 11) < 2 ) digito_verificador = 0; 
	if ( eval(s.charAt(10)) != digito_verificador ) 
	{	alert("CPF inválido.");
		pCampo.focus();
		pCampo.select();
		return false; 
   }  
	return true; 
} 
//
// Função: Abre uma nova janela auxiliar
// -------------------------------------
function newWindow(pURL,pWidth,pHeight) 
{
	x="fullscreen=no,channelmode=no,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=" + pWidth + ",height=" + pHeight + ",top=0,left=0"
    var win = window.open(pURL,null,x);
    return false;
}


// Função: checa se há somente letra/número/tamanho mínimo
// -------------------------------------------------------
// pCampo : nome do campo a ser testado
// pNome	 : nome pra sair no alert
// pLen   : tamanho mínimo (opcional)
// pTipo  : "N" se numérico, senão Número ou Letra

function checaLetraNumero(pCampo,pNome,pLen,pTipo)
{
   tam = pCampo.value.length;
   
   if (!isNaN(pLen))
   {	if (tam < pLen)
		{	alert(pNome + " deve conter no mínimo " + pLen + " caracteres");
			pCampo.select();
			pCampo.focus();
			return false;
		}
	}
	tam--;
	for(i=0;i<=tam;i++)
	{	nrAsc = pCampo.value.charCodeAt(i);
		if (pTipo == "N") 
		{	if (nrAsc < 48 || nrAsc > 57)
			{	alert("Digite apenas números no campo " + pNome);
				pCampo.select();
				pCampo.focus();
				return(false);
			}
		}
		else if ((nrAsc < 48 || nrAsc > 57) && (nrAsc < 65 || nrAsc > 90) && (nrAsc < 97 || nrAsc > 122))
		{	alert("Digite apenas letras ou números no campo " + pNome);
			pCampo.select();
			pCampo.focus();
			return(false);
		}
	}
	return(true);
}
/* Limpar campos do formulário */
function limpaFormulario(pForm)
{
	for (i=0; i < pForm.elements.length; i++)
		{
		if (pForm.elements[i].type=="hidden" || pForm.elements[i].type=="text" || pForm.elements[i].type=="textarea" || pForm.elements[i].type=="select-one" || pForm.elements[i].type=="password")
			{
			eval('document.' + pForm.name + '.elements[' + i + '].value=""');
			}
		}
	//pForm.elements[0].focus();
	return false;
}
function verificaNomeExtensao(pCampo,pNome,pExtensao)
{  
   tam = pCampo.value.length;  
   if ((tam>100) || (tam<5))
   {
		alert("Nome de " + pNome + " deve conter no mínimo 5 caracteres e no máximo 100");
		pCampo.select();
		pCampo.focus();
		return (false);
   } 	
	tam=tam-5;//posicao antes do ponto	
	for(i=0;i<=tam;i++)
	{		
		nrAsc = pCampo.value.charCodeAt(i);				
		if (((nrAsc < 48 || nrAsc > 57) && (nrAsc < 65 || nrAsc > 90) && (nrAsc < 97 || nrAsc > 122)) && (nrAsc != 95))
		{	alert("Digite apenas letras, números ou '_' no nome de " + pNome);
			pCampo.select();
			pCampo.focus();
			return(false);
		}											
	}
	tam=tam+1;	
	//verificar se o ponto esta no lugar certo
	nrAsc = pCampo.value.charCodeAt(tam);	
	if (nrAsc != 46)
	 	{
	 		alert("Formato inválido de nome de " + pNome);
			pCampo.select();
			pCampo.focus();
	 		return(false);
	 	}
	else //verifica se a extensao esta correta
	{	
		if (pExtensao!=null)//se a extensao é definida pelo usuario, verificar caracteres
		{											
			if (pCampo.value.substring(tam+1,tam+4)!=pExtensao)
	 		{
	 			alert("Formato inválido de extensão de " + pNome);
				pCampo.select();
				pCampo.focus();
	 			return(false);
	 		}
		}		
		else		
		{
			s=pCampo.value.substring(tam+1,tam+4);
			if (s != "htm" && s != "doc" && s != "pdf" && s != "zip" && s != "xls" && s != "gif" && s !="jpg" && s !="txt")
	 		{
	 			alert("Formato inválido de extensão de " + pNome);
				pCampo.select();
				pCampo.focus();
	 			return(false);
	 		}
		}
	}
	return(true);
}

//Função para Corrigir Nome 

function corrigenome(pNome)
{
	Tamanho = pNome.value.length; 
	Quantidade = 0;
	strLetra = pNome.value.substring(0,1).toUpperCase();
	strLetra1 = pNome.value.substring(1,Tamanho);
	if (strLetra == " ")
	{
		alert("O primeiro caracter não pode ser um espaço em branco")
		return false;
	}
	else
	{
		for (i=0; i<Tamanho; i++)
		{
			Letra = strLetra1.charAt(i);
			if (Letra == " ") 
			{	
				if (strLetra1.charAt(i + 1) == " ")
				{
					alert ("Não pode ter mais de um espaço entre cada palavra");
					return false;
				}
				else
				{
					Letra = strLetra1.charAt(i + 1);
					strLetra = strLetra + " " + Letra.toUpperCase();
					Quantidade = Quantidade + 1;
					i++;
				}
			}
			else
			{
				strLetra = strLetra + Letra.toLowerCase();
			}
		}
	}
	pNome.value = strLetra;
	return false;
}
//Função para checar se existe apóstrofo simples.
function checaPlica(pCampo, pNome)
{	
    for (i=0; i < pCampo.value.length; i++)
        {
         if (pCampo.value.charAt(i) == "'")
            {
             alert ("O campo " + pNome + " não aceita aspas simples.");
			 pCampo.focus();
			 pCampo.select();
			 return false;
            }
        }
	return true;
}
//
//Função para chamar nova Página que não consta do menu
//
function chamarPagina(pPagina,pDestino,pParametro)
{	
	document.frmGeral.ItemMenu.value=pPagina;
	if (pDestino!=null)
	{	document.frmGeral.PaginaDestino.value=pDestino;
	}
	if (pParametro!=null)
	{	document.frmGeral.Parametro.value=pParametro;
	}
	document.frmGeral.submit();
	return false;
}
//
//Função para chamar uma publicação qualquer
//
function chamarPublicacao(pPublicacao)
{	
	document.frmGeral.ItemMenu.value="adm005.asp";
	document.frmGeral.PaginaDestino.value="adm005_1.asp";
	document.frmGeral.hidCdPublicacao.value=pPublicacao;
	document.frmGeral.submit();
	return false;
}
//
//Função para chamar um diário oficial qualquer
//
function chamarDiario(pCdDiario)
{	
	document.frmGeral.ItemMenu.value="adm345.asp";
	document.frmGeral.PaginaDestino.value="adm345_1.asp";
	document.frmGeral.Parametro.value=pCdDiario;
	document.frmGeral.submit();
	return false;
}
//
//
/* Função que critica data */
//
//
function validaData(pDataI)
{
	pData=pDataI.value;
    if ((pData.length == 10) &&
        (pData.substring(2,3) == "/") &&
        (pData.substring(5,6) == "/"))
    {
        pData = pData.substring(0,2) +
                      pData.substring(3,5) +
                      pData.substring(6,10);
    }
    //alert(pData);
    var pDia = pData.substring(0,2);
    var pMes = pData.substring(2,4);
    var pAno = pData.substring(4,8);
    var numDias = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    
    if (pAno % 4 == 0) 
    {   numDias[01] = 29;
    }

    if (pData.length != 0)
    {  
       if ((pData.length != 8) ||
          (isNaN(pData)) || 
          (pAno < 1900) || 
          (pDia == 0) ||
          (pMes == 0) ||
          (pMes > 12) || 
          (pDia > numDias[pMes-1]))
       {
          alert("Data inválida. Utilize formato DD/MM/AAAA.");
          pDataI.focus(); 
          pDataI.select();
          return false;
       }
       else
       {
          pDataI.value = pDia + "/" + pMes + "/" + pAno;
          return true;
       }
    }
}
//
//
/* Função que critica hora */
//
//
function validaHora(pHora)
{
    if ((pHora.value.length == 5) && (pHora.value.substring(2,3) == ":"))
    {
        pHora.value = pHora.value.substring(0,2) + pHora.value.substring(3,5);
    }
    //alert(pHora.value);
    var pH = pHora.value.substring(0,2);
    var pMinutos = pHora.value.substring(2,4);
    if (pHora.value.length != 0)
    {  
       if ((pHora.value.length != 4) || (isNaN(pHora.value)) || (pH > 24) || (pMinutos >60))
       {
          alert("Hora inválida. Utilize formato HH:MM.");
          pHora.focus(); 
          pHora.select();
          return false;
       }
       else
       {
          pHora.value = pH + ":" + pMinutos;
          return true;
       }
    }
}
//
//
/* Função que coloca as barras do campo data quando em KeyPress */
//
//02/03/2003
function colocaBarras(pData)
{
	if (pData.value.length == 2)
		pData.value = pData.value + "/";
	else if (pData.value.length == 5)
		pData.value = pData.value + "/";
	return true;
}
//
//
/* Função que coloca dois no campo Hora quando em KeyPress */
//
//02/03/2003
function doisPontos(pHora)
{
	if (pHora.value.length == 2)
		pHora.value = pHora.value + ":";
	return true;
}
//
//
/*Função para permitir somente numeros*/
//
//
function somenteNumero(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;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}


// Ampliar foto em novo browser (modal) 
// ------------------------------------
function ampliaFoto(pFoto,pAltura,pLargura)
{
	newWindow = window.open("","","fullscreen=no,channelmode=no,toolbar=no,location=no,directories=no,status=nos,menubar=no,scrollbars=no,resizable=no,height="+pAltura+",width="+pLargura+",top=20,left=100");
	newWindow.focus();
	newContent = "<HTML><BODY bottommargin=0 leftmargin=0 topmargin=0 rightmargin=0 onBlur=focus()><IMG src=images/"+pFoto+"></BODY></HTML>";
	newWindow.document.write(newContent);	 
	newWindow.document.close();
	return false;
} 

/* Função que retira as barras do campo data quando em foco */
/* -------------------------------------------------------- */
function retiraBarras(pData)
{
   if ((pData.value.length == 10) && (pData.value.substring(2,3) == "/") && (pData.value.substring(5,6) == "/"))
   {
      pData.value = pData.value.substring(0,2) + 
                    pData.value.substring(3,5) + 
                    pData.value.substring(6,10);
   }
   pData.select();
}

/* Conta o número de caracteres em campo TEXTAREA usando onkeyup */
/* ------------------------------------------------------------- */
function contaCharCampo(mCampo, mLenCampo, mNomeCampo)
{
if (mCampo.value.length > mLenCampo)
	{
	alert("Atençao. No " + mNomeCampo + " são permitidos digitar no máximo " + mLenCampo + " caracteres.");
	mCampo.value = mCampo.value.substr(0,mLenCampo);
	}
}

// Checar se foi selecionado um valor numa lista
// ---------------------------------------------
function checaSelecao(pCampo, pNome)
{
if (pCampo.selectedIndex == 0)
	{	alert("Escolha uma das opções do campo "+pNome);
		pCampo.focus();
		return false;
	}
return true;
}
// Calcula a diferença em MINUTOS entre dois valores do tipo Hora no formato HH:MM
//--------------------------------------------------------------------------------
function CalculaDiferencaHHMM(hr1,hr2) {
	if (hr1.length==5) 
		hr1=hr1+":00";
	if (hr2.length==5) 
		hr2=hr2+":00";
	
	qtdMinutos=CalculaDiferencaHHMMSS(hr1,hr2)/60;
	
	return qtdMinutos;
};
// Calcula a diferença em Segundos entre valores do tipo Hora no formato HH:MM:SS
//-------------------------------------------------------------------------------
function CalculaDiferencaHHMMSS(hr1,hr2) {
		hh1=hr1.substr(0,2);
		mm1=hr1.substr(3,4);
		ss1=hr1.substr(6,7);
		n1=hh1*3600+mm1*60+ss1;
		
		hh2=hr2.substr(0,2);
		mm2=hr2.substr(3,4);
		ss2=hr2.substr(6,7);
		n2=hh2*3600+mm2*60+ss2;
	
		qtdSegundos=n2-n1;
		return qtdSegundos;
};
// Valida Hora no formato (=0) HH:MM ou (=1) HH:MM:SS
//---------------------------------------------------
function ValidaHora(hora,formato) {
	if (formato==0)
		return ValidaHoraHHMM(hora)
	else
		return ValidaHoraHHMMSS(hora);
};

function ValidaHoraHHMM(hora) {
	r=true;
	if (hora.length!=5)
		r=false
	else {
		hora=hora+":00";
		r=ValidaHoraHHMMSS(hora);
	};
	return r;
};

function ValidaHoraHHMMSS(hora) {
	r=true;
	if (hora.length!=8)
		r=false
	else {
		hh=parseInt(hora.substr(0,2));
		if (hh>=24)
			r=false
		else {
			mm=parseInt(hora.substr(3,4));
			if (mm>=60)
				r=false;
			else {
				ss=parseInt(hora.substr(6,7));
				if (ss>=60)
					r=false;
			}
		}
	}
	return r;
};

function validaTipoImagem(CampoNomeImg) {
// Verifica se o nome da imagem é valido, ou seja, se é do tipo
// GIF, JPG, BMP, TIF ou PNG
	r=true;
	if (CampoNomeImg.value.length > 0) {
		tam = CampoNomeImg.value.length - 4;
		ext = CampoNomeImg.value.substring(tam,tam+4);
		ext = ext.toLowerCase();
		if ((ext != ".gif") && (ext != ".jpg") && (ext != ".bmp") && (ext != ".tif") && (ext != ".png")) {	
			alert("Utilize arquivos do tipo GIF, JPG, BMP, TIF ou PNG para a Imagem ");
			r=false;
		}
	}
	return r;
};

// Formatar campo moeda (2 casas decimais)
//----------------------------------------
function formataMoeda(fld, milSep, decSep, e) { 
	/*
	Esta função é testada quando se está digitando, não permitindo valores irregulares.
	Exemplo de utilização:
	onKeyPress="return(formataMoeda(this,'.',',',event))"> 
	*/
	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 = fld.value.length; 
	for(i = 0; i < len; i++) 
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; 
	aux = ''; 
	for(; i < len; i++) 
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); 
	aux += key; 
	len = aux.length; 
	if (len == 0) fld.value = ''; 
	if (len == 1) fld.value = '0'+ decSep + '0' + aux; 
	if (len == 2) fld.value = '0'+ decSep + aux; 
	if (len > 2) { 
		aux2 = ''; 
		for (j = 0, i = len - 3; i >= 0; i--) { 
			if (j == 3) { 
				aux2 += milSep; 
				j = 0; 
			} 
			aux2 += aux.charAt(i); 
			j++; 
		} 
		fld.value = ''; 
		len2 = aux2.length; 
		for (i = len2 - 1; i >= 0; i--) 
			fld.value += aux2.charAt(i); 
		fld.value += decSep + aux.substr(len - 2, len); 
	} 
	return false; 
} 

function RemoveSimbolos(campo){
	
   var s = new String(campo.value);		
	// remove os pontos, barras e traços do cnpj
   if (isNaN(s)) {
       campo.value = s.substring(0,2) + s.substring(3,6) + s.substring(6,9)+ s.substring(9,13) + s.substring(13);
	}
}
	
function ValidaCNPJ(campo)
{
   if(campo.value!= ""){
   RemoveSimbolos(campo);
   CNPJ = campo.value;
   var cnpjCalc = CNPJ.substr(0,12);  
   var cnpjSoma = 0;
   var cnpjDigit = 0;  
   var digit = "";    
 
   for (i = 0;  i < 4;  i++) {
     cnpjSoma = cnpjSoma + parseInt(cnpjCalc.charAt(i)) * (5 - i);
    }     
  
   for (i = 0;  i < 8;  i++) {
     cnpjSoma = cnpjSoma + parseInt(cnpjCalc.charAt(i+4)) * (9 - i);            
    }    
 
   cnpjDigit = 11 - cnpjSoma%11;       

   if ((cnpjDigit == 10) || (cnpjDigit == 11)){     
     cnpjCalc = cnpjCalc + "0";        
    } 
   else {     
     digit = digit + cnpjDigit; 
     cnpjCalc = cnpjCalc + (digit.charAt(0));
    }
  
   cnpjSoma = 0;
  
   for (i = 0;  i < 5;  i++){
     cnpjSoma = cnpjSoma + parseInt(cnpjCalc.charAt(i)) * (6 - i);    
    }  
  
   for (i = 0;  i < 8;  i++) {
     cnpjSoma = cnpjSoma + parseInt(cnpjCalc.charAt(i+5)) * (9 - i);    
    }

   cnpjDigit = 11 - cnpjSoma%11;         
 
   if ((cnpjDigit == 10) || (cnpjDigit == 11)) {    
     cnpjCalc = cnpjCalc + "0";    
    } 
   else {     
     digit = "";
     digit = digit + cnpjDigit; 
     cnpjCalc = cnpjCalc + (digit.charAt(0))
    }
 
   if (CNPJ != cnpjCalc) { 
		//return false
	 	alert("CNPJ incorreto!");
	 	campo.focus();
		campo.select();
    }else{
		cnpjCorreto = CNPJ.substring(0,2) + "." + CNPJ.substring(2,5) + "." + CNPJ.substring(5,8)+ "/" + CNPJ.substring(8,12) + "-" + CNPJ.substring(12);
		campo.value = cnpjCorreto;
	}
   	
   //return true;
   }
  } 	
  
  //------ javascript da acessibilidade ----------------
  //criação de cookie para a utilização da acessibilidade
  
  
function setCookie(name,value,days,path,domain,secure) {
  var expires, date;
  if (typeof days == "number") {
    date = new Date();
    date.setTime( date.getTime() + (days*24*60*60*1000) );
		expires = date.toGMTString();
  }
  document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie(name) {
  var nameq = name + "=";
  var c_ar = document.cookie.split(';');
  for (var i=0; i<c_ar.length; i++) {
    var c = c_ar[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameq) == 0) return unescape( c.substring(nameq.length, c.length) );
  }
  return null;
}

function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// Funcionalidade do Serviço de Acessibilidade 
  
 
var dw_fontSizerDX = {
    sizeUnit:       "px",
    defaultSize:    11,
    maxSize:        24,
    minSize:        9,
    queryName:      "dw_fsz",   // name to check query string for when passing size in URL
    queryNum:       true,       // check query string for number only (eg. index.html?18 )
    adjustList:     [],         // set method populates

    setDefaults: function(unit, dflt, mn, mx, sels) {
        this.sizeUnit = unit;       this.defaultSize = dflt;
        this.maxSize = mx;          this.minSize = mn;
        if (sels) this.set(dflt, mn, mx, sels);
    },

    set: function (dflt, mn, mx, sels) { 
        var ln = this.adjustList.length;        
        for (var i=0; sels[i]; i++) {
            this.adjustList[ln+i] = [];
            this.adjustList[ln+i]["sel"]  = sels[i];
            this.adjustList[ln+i]["dflt"] = dflt;
            this.adjustList[ln+i]["min"]   = mn || this.minSize;
            this.adjustList[ln+i]["max"]   = mx || this.maxSize;
            // hold ratio of this selector's default size to this.defaultSize for calcs in adjust fn 
            this.adjustList[ln+i]["ratio"] = this.adjustList[ln+i]["dflt"] / this.defaultSize;
        }
    },

    init: function() {
        if ( !document.getElementById || !document.getElementsByTagName ) return;
        var size, sizerEl, i;
        // check query string and cookie for fontSize
        // check size (in case default unit changed or size passed in url out of range)
        size = getValueFromQueryString( this.queryName, this.queryNum );
        if ( isNaN( parseFloat(size) ) || size > this.maxSize || size < this.minSize ) {
            size = getCookie("fontSize");
            if ( isNaN( parseFloat(size) ) || size > this.maxSize || size < this.minSize ) {
                size = this.defaultSize;
            }
        } 
        this.curSize = this.defaultSize;  // create curSize property to use in calculations 
        sizerEl = document.getElementById('sizer');
        if (sizerEl) sizerEl.style.display = "block";
        // if neither set nor setDefaults populates adjustList, apply sizes to body and td's
        if (this.adjustList.length == 0) {
            this.setDefaults( this.sizeUnit, this.defaultSize, this.minSize, this.maxSize, ['body', 'td'] );
        }
        if ( size != this.defaultSize ) this.adjust( size - this.defaultSize );
    },

    adjust: function(n) {
        if ( !this.curSize ) return; 
        var alist, size, list, i, j;
        // check against max/minSize
        if ( n > 0 ) {
            if ( this.curSize + n > this.maxSize ) n = this.maxSize - this.curSize;
        } else if ( n < 0 ) {
            if ( this.curSize + n < this.minSize ) n = this.minSize - this.curSize;
        }
        if ( n == 0 ) return;
        this.curSize += n;
        // loop through adjustList, calculating size, checking max/min
        alist = this.adjustList;
        for (i=0; alist[i]; i++) {
            size = this.curSize * alist[i]['ratio']; // maintain proportion 
            size = Math.max(alist[i]['min'], size); size = Math.min(alist[i]['max'], size);
            list = dw_getElementsBySelector( alist[i]['sel'] );
            for (j=0; list[j]; j++) { list[j].style.fontSize = size + this.sizeUnit; }
        }
        setCookie( "fontSize", this.curSize, 180, "/" );
    },

    reset: function() {
        if ( !this.curSize ) return; 
        var alist = this.adjustList, list, i, j;
        for (i=0; alist[i]; i++) {
            list = dw_getElementsBySelector( alist[i]['sel'] );
            for (j=0; list[j]; j++) { 
                // Reset adjustList elements to their default sizes
                //list[j].style.fontSize = alist[i]['dflt'] + this.sizeUnit;
                list[j].style.fontSize = '';  // restores original font size
            } 
        }
        this.curSize = this.defaultSize;
        deleteCookie("fontSize", "/");
    }

};

function dw_getElementsBySelector(selector) {
    if (!document.getElementsByTagName) return [];
    var nodeList = [document], tokens, bits, list, col, els, i, j, k;
    selector = selector.normalize();
    tokens = selector.split(' ');
    for (i=0; tokens[i]; i++) {
        if ( tokens[i].indexOf('#') != -1 ) {  // id
            bits = tokens[i].split('#'); 
            var el = document.getElementById( bits[1] );
            if (!el) return []; 
            if ( bits[0] ) {  // check tag
                if ( el.tagName.toLowerCase() != bits[0].toLowerCase() ) return [];
            }
            for (j=0; nodeList[j]; j++) {  // check containment
                if ( nodeList[j] == document || dw_contained(el, nodeList[j]) ) 
                    nodeList = [el];
                else return [];
            }
        } else if ( tokens[i].indexOf('.') != -1 ) {  // class
            bits = tokens[i].split('.'); col = [];
            for (j=0; nodeList[j]; j++) {
                els = dw_getElementsByClassName( bits[1], bits[0], nodeList[j] );
                for (k=0; els[k]; k++) { col[col.length] = els[k]; }
            }
            nodeList = [];
            for (j=0; col[j]; j++) { nodeList.push(col[j]); }
        } else {  // element 
            els = []; 
            for (j = 0; nodeList[j]; j++) {
                list = nodeList[j].getElementsByTagName(tokens[i]);
                for (k = 0; list[k]; k++) { els.push(list[k]); }
            }
            nodeList = els;
        }
    }
    return nodeList;
};

function dw_getElementsByClassName(sClass, sTag, oCont) {
    var result = [], list, i;
    var re = new RegExp("\\b" + sClass + "\\b", "i");
    oCont = oCont? oCont: document;
    if ( document.getElementsByTagName ) {
        if ( !sTag || sTag == "*" ) {
            list = oCont.all? oCont.all: oCont.getElementsByTagName("*");
        } else {
            list = oCont.getElementsByTagName(sTag);
        }
        for (i=0; list[i]; i++) 
            if ( re.test( list[i].className ) ) result.push( list[i] );
    }
    return result;
};

function getValueFromQueryString(varName, bReturn) {
    var val = "";
    if (window.location.search) {
        var qStr = window.location.search.slice(1);
        var ar = qStr.split("&");
        var get = [], ar2;
        // portion before = becomes index (like $_GET)
        for (var i=0; ar[i]; i++) {
            if ( ar[i].indexOf("=") != -1 ) {
                ar2 = ar[i].split("=");
                get[ ar2[0] ] = ar2[1];
            }
        }
        val = get[varName];
        // if varName is not passed to this function or not found, return entire query string ?      
        if ( !val && bReturn ) {
            val = qStr;
        }
    }
    return val;
};

// returns true of oNode is contained by oCont (container)
function dw_contained(oNode, oCont) {
    if (!oNode) return; // in case alt-tab away while hovering (prevent error)
    while ( oNode = oNode.parentNode ) if ( oNode == oCont ) return true;
    return false;
};

if (!Array.prototype.push) {  // ie5.0
	Array.prototype.push =  function() {
		for (var i=0; arguments[i]; i++) this[this.length] = arguments[i];
		return this[this.length-1]; // return last value appended
	}
};

String.prototype.normalize = function() {
	var re = /\s\s+/g;
	return this.trim().replace(re, " ");
};

String.prototype.trim = function() {
	var re = /^\s+|\s+$/g;
	return this.replace(re, "");
};

  
  //-------------------------------------------------------------------------------------------------------------------------------

  {
	//Valida a Placa do Carro.
	function validaPlaca()
	{
		if (document.frmDetg020.txtIdentificacao.value.length != 0)
		{
			if (document.frmDetg020.txtIdentificacao.value.length != 7)
			{
				alert("Placa inválida. Favor digitar no formato AAA9999.");
				document.frmDetg020.txtIdentificacao.focus();
				document.frmDetg020.txtIdentificacao.select();
				return false;
			}
			else
			{
				Erro = 0;
				strLetra = document.frmDetg020.txtIdentificacao.value.substring(0,3).toUpperCase();
				strNumero = document.frmDetg020.txtIdentificacao.value.substring(3,7);
				for (i=0; i<3; i++)
				{
					Letra = strLetra.charAt(i);
					if ((Letra < 'A') || (Letra > 'Z'))
					{
						alert("Placa com letra " + Letra + " inválida.");
						Erro = Erro + 1;
					}
				}
				for (i=0; i<4; i++)
				{
					Numero = strNumero.charAt(i);
					if ((Numero < '0') || (Numero > '9'))
					{
						alert("Placa com número " + Numero + " inválido.");
						Erro = Erro + 1;
					}
				}
				if (Erro != 0)
				{
					alert("Placa inválida. Favor digitar no formato AAA9999.");
					document.frmDetg020.txtIdentificacao.focus();
					document.frmDetg020.txtIdentificacao.select();
					return false;
				}
					document.frmDetg020.txtIdentificacao.value = strLetra + strNumero;
			}
		}
		return true;
	}

	//Função para validação dos campos do formulário.
	function validaFormulario()
	{
		if (!checaVazio(document.frmDetg020.txtIdentificacao, "Identificação"))
		{
			return false;
		}
		if ((document.frmDetg020.optConsulta[0].checked) || (document.frmDetg020.optConsulta[1].checked) || (document.frmDetg020.optConsulta[2].checked))
		{
			if (document.frmDetg020.optConsulta[0].checked)
			{
				if (!validaPlaca())
				{
					return false;
				}
				else
				{
					document.frmDetg020.submit();
				}
			}
			else
			{
				if (document.frmDetg020.optConsulta[1].checked)
				{
					if (document.frmDetg020.txtIdentificacao.value.length > 6)
					{
						alert("Registro deve conter apenas 6 dígitos numéricos.");
						document.frmDetg020.txtIdentificacao.focus();
						document.frmDetg020.txtIdentificacao.select();
						return false;
					}
					if ((document.frmDetg020.txtIdentificacao.value.length != 0) && (document.frmDetg020.txtIdentificacao.value.length < 6))
					{
						for (i=1; document.frmDetg020.txtIdentificacao.value.length < 6; i++)
						{
							document.frmDetg020.txtIdentificacao.value = 0 + document.frmDetg020.txtIdentificacao.value;
						}
					}
					if (!verificaNumerico(document.frmDetg020.txtIdentificacao, "Registro"))
					{
						return false;
					}
					else
					{
						document.frmDetg020.submit();
					}
				}
				else
				{
					document.frmDetg020.txtIdentificacao.value = document.frmDetg020.txtIdentificacao.value.toUpperCase();
					document.frmDetg020.submit();
				}
			}
		}
		else
		{
			alert("Você deve escolher uma opção de consulta.");
			return false;
		}
	}
}
//
// prepara variáveis de orientação através de imagens
img_placa = new Image();
img_registro = new Image();
img_proprietario = new Image();
img_placa.src = "../images/"
img_proprietario.src = "../images/detg020_proprietario.gif";
img_registro.src = "../images/detg020_registro.gif";
img_placa.src = "../images/detg020_placa.gif";
//
function placa() {
	//x=PosImg();
	//document.images[x].src = img_placa.src
        var txt = "XXX9999";
        document.getElementById('info').textContent = txt;
	}
function registro() {
	//x=PosImg();
	//document.images[x].src = img_registro.src
        var txt = "9999/99";
        document.getElementById('info').textContent = txt;
	}
function proprietario() {
	//x=PosImg();
	//document.images[x].src = img_proprietario.src
        var txt = "Digite o nome completo ou parte do nome.";
        document.getElementById('info').textContent = txt;
	}
function PosImg()
{
// vamos verificar quantos elementos foram apresentados na página
for (i=0; i<=document.images.length; i++)
	{
	y=0;
	x=document.images[i].src;
	if (x.indexOf("detg020_proprietario.gif")!=-1){y=i;break;};
	if (x.indexOf("detg020_registro.gif")!=-1){y=i;break;};
	if (x.indexOf("detg020_placa.gif")!=-1){y=i;break;};
	}
return y;
}

function validaForm()
{
	if (document.AcessoRapido.renavam.value.length == 0)
	{
		alert("O campo Renavam não pode ser vazio.")
		document.AcessoRapido.renavam.focus();
		return false;
	}
	if (document.AcessoRapido.renavam.value.length != 9)
	{
		alert("Renavam incorreto.")
		document.AcessoRapido.renavam.focus();
		return false;
	}
	i=0;
	while (i<document.AcessoRapido.renavam.value.length)
	{
		if (("0123456789").indexOf(document.AcessoRapido.renavam.value.charAt(i))==-1)
		{
			alert("O campo Renavam só aceita números.");
			document.AcessoRapido.renavam.focus();
			return false;
		}
		i++;
	}
	/*if (document.AcessoRapido.CPF.value.length == 0)
	{
		alert("O campo CPF não pode ser vazio.")
		document.AcessoRapido.CPF.focus();
		return false;
	}
	if (document.AcessoRapido.CPF.value.length != 11)
	{
		alert("CPF incorreto.")
		document.AcessoRapido.CPF.focus();
		return false;
	}
	i=0;
	while (i<document.AcessoRapido.CPF.value.length)
	{
		if (("0123456789").indexOf(document.AcessoRapido.CPF.value.charAt(i))==-1)
		{
			alert("O campo CPF só aceita números.");
			document.AcessoRapido.CPF.focus();
			return false;
		}
		i++;
	}
	if (!validarCPF(document.AcessoRapido.CPF))
	{
		return false;
	}*/

	//document.AcessoRapido.placa.value = document.AcessoRapido.placa1.value;
	//document.AcessoRapido.renavam.value = document.AcessoRapido.renavam1.value;
	//document.AcessoRapido.placa1.value = "";
	//document.AcessoRapido.renavam1.value = "";
	return true;
}
//Valida a Placa do Carro.

function validaPlaca()
{
	if (document.AcessoRapido.placa.value.length != 0)
	{
		if (document.AcessoRapido.placa.value.length != 7)
		{
			alert("Placa inválida. Favor digitar no formato AAA9999.");
			document.AcessoRapido.placa.focus();
			document.AcessoRapido.placa.select();
			return false;
		}
		else
		{
			Erro = 0;
			strLetra = document.AcessoRapido.placa.value.substring(0,3).toUpperCase();
			strNumero = document.AcessoRapido.placa.value.substring(3,7);
			for (i=0; i<3; i++)
			{
				Letra = strLetra.charAt(i);
				if ((Letra < 'A') || (Letra > 'Z'))
				{
					alert("Placa com letra " + Letra + " inválida.");
					Erro = Erro + 1;
				}
			}
			for (i=0; i<4; i++)
			{
				Numero = strNumero.charAt(i);
				if ((Numero < '0') || (Numero > '9'))
				{
					alert("Placa com número " + Numero + " inválido.");
					Erro = Erro + 1;
				}
			}
			if (Erro != 0)
			{
				alert("Placa inválida. Favor digitar no formato AAA9999.");
				document.AcessoRapido.placa.focus();
				document.AcessoRapido.placa.select();
				return false;
			}
				document.AcessoRapido.placa.value = strLetra + strNumero;
		}
	}
	return true;
} // fim função validaPlaca

