// Checa números na digitação em um campo de um formulário
function checaNumeros(evt) {
	var key_code = 	evt.keyCode  ? evt.keyCode  :
					evt.charCode ? evt.charCode :
					evt.which    ? evt.which    : void 0;

	// Habilita teclas <DEL>, <TAB>, <ENTER>, <ESC> e <BACKSPACE>
	if (key_code == 8  ||  key_code == 9  ||  key_code == 13  ||  key_code == 27  ||  key_code == 46) {
		return true;
	}
	
	// Habilita teclas <HOME>, <END>, mais as quatros setas de navegação (cima, baixo, direta, esquerda)
	else if ((key_code >= 35)  &&  (key_code <= 40)) {
		return true
	}
	
	// Habilita números de 0 a 9
	else if ((key_code >= 48)  &&  (key_code <= 57)) {
		return true
	}
	
	return false;
	
}

//Valida o Valor a ser pago
function Valida_Valor(objValor)
{
  if (objValor.value=='') 
   {
    alert('Por favor, digite o valor a ser pago.');
    objValor.focus();
    return false;
   }
   return true;
}

function ValidaControle(obj)
{
	if (obj.value=='')
	{
		alert('Por favor, digite o número de controle.');
		obj.focus();
		obj.select();
		return false;
	}
	obj2 = ""+obj.value
	obj.value = fnZeroAEsquerda(obj2,6);
	return true;
}

function ValidaInscricao(obj)
{
	if (obj.value=='')
	{
		alert('Por favor, digite o número da inscrição.');
		obj.focus();
		obj.select();
		return false;
	}
	obj2 = ""+obj.value
	obj.value = fnZeroAEsquerda(obj2,7);
	return true;
}

//Verifica se o campo número da OS foi preenchido
function Valida_Numero(objNumero)
{
	if (objNumero.value==''){
		alert('Por favor, digite o número da Ordem.');
		objNumero.focus();
		return false;
	}
	return true;
}

// Digita a barra do campo DATA
function formatadata(obj)
{
	vr = obj.value;
	if (vr.length == 2) obj.value = obj.value + '/';
	if (vr.length == 5) obj.value = obj.value + '/';
 };

// Digita a barra do campo DATA
function formatadata(obj)
{
	vr = obj.value;
	if (vr.length == 2) obj.value = obj.value + '/';
	if (vr.length == 5) obj.value = obj.value + '/';
 };

//Valida Nome
function Valida_Nome(objNome)
{
	if (objNome.value==''){
		alert('Por favor, digite o nome do responsável.');
		objNome.focus();
		return false;
	}
	return true;
}

//Valida Endereço
function Valida_Endereco(objEnd)
{
	if (objEnd.value=='')
	{
		alert('Por favor, digite o endereço do responsável.');
		objEnd.focus();
		return false;
	}
	return true;
}

//Valida a escolha do mês em list box
function Valida_Mes(obj_Mes)
{
	if(obj_Mes.selectedIndex ==0)
	{
		alert('Por favor, selecione um mês da lista.');
		obj_Mes.focus();
		return false;
	}
	return true;
}

//Valida a escolha do bairro em list box
function Valida_Bairro(obj_Bairro)
{
	if(obj_Bairro.selectedIndex ==0)
	{
		alert('Por favor, selecione um bairro da lista.');
		obj_Bairro.focus();
		return false;
	}
	return true;
}


//Valida area
function Valida_Area(obj_Area)
{
	if(obj_Area.value=='' || obj_Area.value<1)
	{
		alert('Por favor, digite a área do estabelecimento.');
		obj_Area.focus();
		return false;
	}
	return true;
}

//Valida a escolha da taxa em list box
function Valida_Taxa(obj_Taxa)
{
	if(obj_Taxa.selectedIndex ==0)
	{
		alert('Por favor, selecione o tipo da taxa.');
		obj_Taxa.focus();
		return false;
	}
	return true;
}

//Valida DAM Parcelado
function Valida_DAM_Parcelado(obj_Titulo, obj_Inscricao, obj_Parcela)
{
   if (obj_Titulo.value=='')
   {
    alert('Digite o número do Título.');
    obj_Titulo.focus();
    return false; 
   }
   if (obj_Inscricao.value=='')
   {
    alert('Digite a inscrição.');
    obj_Inscricao.focus();
    return false; 
   }
   if (obj_Parcela.value=='')
   {
    alert('Informe a parcela a ser paga.');
    obj_Parcela.focus();
    return false; 
   }
	return true;
}

// Valida Formulario DAM_AVULSO
function Valida_DAM_AVULSO(obj_cpfcnpj, obj_nome, obj_endereco, obj_valor)
{
  if (obj_cpfcnpj.value=='')
   {
    alert('Digite o número de Controle.');
    obj_cpfcnpj.focus();
    return false; 
   }
  if (obj_nome.value=='') 
   {
    alert('Digite o nome do responsável.');
    obj_nome.focus();
    return false;
   }
  if (obj_endereco.value=='') 
   {
    alert('Digite o endereço do responsável.');
    obj_endereco.focus();
    return false;
   }
  if (obj_valor.value=='') 
   {
    alert('Digite o valor a ser pago.');
    obj_valor.focus();
    return false;
   }
    
    return true;
}


function Valida_Ano(obj_ano, obj_processo, nAno)
{
  if (obj_ano.value=='')
   {
    alert('Digite o ano do processo.');
    obj_ano.focus();
    return false; 
   }
  if (obj_processo.value=='') 
   {
    alert('Digite o número do processo.');
    obj_processo.focus();
    return false;
   }
  if (parseInt(obj_ano.value) < parseInt(nAno - 5)) 
   {
    alert('Processo de ano inválido.');
    obj_processo.focus();
    return false;
   }
    return true;
}

// Exibe ou Esconde objeto
// sAcao = "M" ==> exibe objeto
// sAcao = "E" ==> esconde objeto


function fnMostrarEsconder(sNomeObj,sAcao)
{

	//var oObj = eval(sNomeObj);	
	//var oImgObj = eval(oObj.id);
	
	if (sAcao=="M")
	{	
	   	//oObj.style.visibility = "visible";//vazio = block ou vazio = inline. Tal recurso compatibiliza o IE e o FF
   		document.getElementById(sNomeObj).style.visibility = "visible";
	}
	else
	{
		if(sAcao=="E")
		{
			
		   	//oObj.style.visibility = "hidden";
			document.getElementById(sNomeObj).style.visibility = "hidden";		   
		}
	}
}

// JavaScript Document

function CPF_CNPJ(rotulo, idObj1, maxTam, idObj2){
    var objeto1=document.getElementById(idObj1);
    var objeto2=document.getElementById(idObj2);

    objeto1.innerHTML = rotulo;
	objeto2.value = '';
	objeto2.size = maxTam+1;
	objeto2.maxLength = maxTam;
	objeto2.focus();
}

// Script Tab automatico para formularios
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
		//input.form[(getIndex(input)+1) % input.form.length].select();
	}
	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
		if(arr[index] == ele)
			found = true;
		else
			index++; 
		return found;
	}
	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
		if (input.form[i] == input)index = i;
		else i++;
		return index;
	}
		return true;
}


function tipoPagamento(){

	data = new Date();
	ano = data.getFullYear(); 
	
    var lista = document.formDados.anoExercicio;
    //if(lista.options[lista.selectedIndex].value == ano) {
	         document.all.EXERCatual.style.display = '';
			 document.all.parcelaESP.style.visibility = 'hidden';
			 //document.getElementById(pagamento).checked = 1;
			 
	//}
	//else {
	         //document.all.EXERCatual.style.display = 'none';
			 //document.all.parcelaESP.style.visibility = 'hidden';		 
			 //document.all.objExercicioEspecifico.innerText = lista.options[lista.selectedIndex].value;
			 //document.all.pagamento[3].checked = 1;
			 //document.getElementById(pagamento).checked = 1;
	//}
}

function typeTax(){
	/*
	Exibirá o campo de preenchimento da área e escolha de renovação
	de acordo com o tipo de taxa selecionado.	
	Tipos de taxa: E03, E04, E28, E29
	*/
	
	//taxas com área
	var taxa1 = "E03";
	var taxa2 = "E04";	
	
	var lista = document.formDados.tipoTaxa;	
	
	if(lista.options[lista.selectedIndex].value == taxa1 ||
	   lista.options[lista.selectedIndex].value == taxa2)
		{	//exibirá os campos		
			document.all.tArea.style.display = '';			
		}
	else{	//não exibirá os campos
			document.all.tArea.style.display = 'none';
		}
}

///////////// VALIDA PARCELA /////////////

function ValidaParcela(obj)
{
 if (obj.value=='')
 {
   alert("Informe a parcela em atraso.");
   obj.focus();
   return false;
  }
}

/////////////////////////////////////////

//Função para validar o CPF
function ValidaCPF(obj)
{
	if(obj.value=='')
	{
        alert('Digite o CPF.');
		obj.focus();
		obj.select();
		return false;
	}
	else
	{
	
		if (obj.value=='00000000000' || obj.value=='11111111111' ||
		    obj.value=='22222222222' || obj.value=='33333333333' ||
		    obj.value=='44444444444' || obj.value=='55555555555' ||
		    obj.value=='66666666666' || obj.value=='77777777777' ||
		    obj.value=='88888888888' || obj.value=='99999999999')
		{
			alert('CPF inválido.');
			obj.focus();
			obj.select();
			return false;
		}
		else
		{  
			obj2 = ""+obj.value
			obj.value = fnZeroAEsquerda(obj2,11);
			return pfValidaCPF_CGC(obj, 'CPF inválido.');
		}
	
	}
	
}

//Function Valida CNPJ
function ValidaCNPJ(obj)
{
	if(obj.value=='')
	{
        alert('Digite o CNPJ.');
		obj.focus();
		obj.select();
		return false;
	}
	else
	{

		if (obj.value=='00000000000000' || obj.value=='11111111111111' ||
			obj.value=='22222222222222' || obj.value=='33333333333333' ||
			obj.value=='44444444444444' || obj.value=='55555555555555' ||
			obj.value=='66666666666666' || obj.value=='77777777777777' ||
			obj.value=='88888888888888' || obj.value=='99999999999999')
		{
			alert('CNPJ inválido.');
			obj.focus();
			obj.select();
			return false;
		}
		else
		{  
			obj2 = ""+obj.value
			obj.value = fnZeroAEsquerda(obj2,14);
			return pfValidaCPF_CGC(obj, 'CNPJ inválido.'); 
		}	
		
	}
}

//função para validar CNPJ-CGC ou CPF de acordo com a Opção passada.
function ValidaCPFCNPJ(obj,tp)
{
	if(tp[0].checked) tp2 = 'F';
	else tp2 = 'J';
	if(obj.value=='')
	{
		if(tp2 == 'F') alert('Digite o CPF.');
		else alert('Digite o CNPJ.');
		obj.focus();
		obj.select();
		return false;
	}
	else
	{
		if(tp2 == 'F') 
		{
			if (obj.value=='00000000000' || obj.value=='11111111111' ||
			    obj.value=='22222222222' || obj.value=='33333333333' ||
			    obj.value=='44444444444' || obj.value=='55555555555' ||
			    obj.value=='66666666666' || obj.value=='77777777777' ||
			    obj.value=='88888888888' || obj.value=='99999999999')
			{
				alert('CPF inválido.');
				obj.focus();
				obj.select();
				return false;
			}
			else
			{  
				obj2 = ""+obj.value
				obj.value = fnZeroAEsquerda(obj2,11);
				return pfValidaCPF_CGC(obj, 'CPF inválido.');
			}
		}	
		else 
		{
			if (obj.value=='00000000000000' || obj.value=='11111111111111' ||
			    obj.value=='22222222222222' || obj.value=='33333333333333' ||
			    obj.value=='44444444444444' || obj.value=='55555555555555' ||
			    obj.value=='66666666666666' || obj.value=='77777777777777' ||
			    obj.value=='88888888888888' || obj.value=='99999999999999')
			{
				alert('CNPJ inválido.');
				obj.focus();
				obj.select();
				return false;
			}
			else
			{  
				obj2 = ""+obj.value
				obj.value = fnZeroAEsquerda(obj2,14);
				return pfValidaCPF_CGC(obj, 'CNPJ inválido.'); 
			}	
		}	
	}
				
}
				
function pfValidaCPF_CGC(msCPF_CGC, msMSG)
{
	if (!(checa(msCPF_CGC.value, msMSG)))
	{
		msCPF_CGC.focus();
		msCPF_CGC.select();
		return false;
	}
	else
	{ 
		return true; 
	}
}

function checa(msCPF_CGC, msMSG){
	if ((msCPF_CGC.length != 14) && (msCPF_CGC.length !=11)){
		alert(msMSG);
		return false;
	}
				  
	if ((!(modulo(msCPF_CGC.substring(0,msCPF_CGC.length - 2)).toString()+modulo(msCPF_CGC.substring(0,msCPF_CGC.length - 1)).toString() == msCPF_CGC.substring(msCPF_CGC.length - 2,msCPF_CGC.length))) && (modulo_cic(msCPF_CGC.substring(0,msCPF_CGC.length - 2)) + "" + modulo_cic(msCPF_CGC.substring(0,msCPF_CGC.length - 1)) != msCPF_CGC.substring(msCPF_CGC.length - 2,msCPF_CGC.length))){
		alert(msMSG);
		return false;
	}
	return true;
}

function modulo(msCPF_CGC){
	soma=0;
	ind=2;
					
	for(pos=msCPF_CGC.length-1;pos>-1;pos=pos-1){
		soma = soma + (parseInt(msCPF_CGC.charAt(pos)) * ind);
		ind++;
				      
		if(msCPF_CGC.length>11){ 
			if(ind>9) ind=2; 
        }
	}
					
	resto = soma - (Math.floor(soma / 11) * 11);
						 
	if(resto < 2){ 
		return 0; 
	}
	else{ 
		return (11 - resto); 
	}
}

function modulo_cic(msCPF_CGC){
   	soma=0;
	ind=2;

	for(pos=msCPF_CGC.length-1;pos>-1;pos=pos-1){
		 soma = soma + (parseInt(msCPF_CGC.charAt(pos)) * ind);
		 ind++;
						 
		 if(msCPF_CGC.length>11){	
		    if(ind>9) ind=2; 
		 }
	}				
					
	resto = soma - (Math.floor(soma / 11) * 11);
						  
	if(resto < 2){	
		return 0; 
	}
	else{ 
		return 11 - resto;
	}
}

function fnZeroAEsquerda(str,n) 
{	
	s = ""+str;
	gera = "";
	if(s.length < n)
	{ 
		for(i=0;i<n-s.length;i++)
		{ 
			gera = gera + "0";
		}
		gera = gera + s;
	}
	else 
	{
		gera = s;
	} 
	return gera;
}

function ValidaIPTU(obj)
{
	if (obj.value=='')
	{
		alert('Digite a Inscrição do IPTU.');
		obj.focus();
		obj.select();
		return false;
	}
	obj2 = ""+obj.value;
	obj.value = fnZeroAEsquerda(obj2,7);
	return true;
	
	/*
	if (obj2.length < 7)
	{
		alert('Inscrição do IPTU deve ter 7 digitos!');
		obj.focus();
		obj.select();
		return false;
	}
	else
	{
		return true;
	}
	*/
}

//--------------------------------------------------------------------------

function validarData(campo){
		
var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
var msgErro = 'Formato inválido de data.';

if ((campo.value.match(expReg)) && (campo.value!='')){
	var dia = campo.value.substring(0,2); //posição inicial e final do parâmetro
	var mes = campo.value.substring(3,5);
	var ano = campo.value.substring(6,10);

	//variáveis utilizadas para comparação
	var nData = new Date();
	var nAno = nData.getFullYear();
	var nMes = nData.getMonth() + 1;	
	
	if (ano!=nAno){
		alert("Ano incorreto. Por favor, entre com o ano corrente.");
		return false;
		}
	else if (mes!=nMes){
		alert("Mês incorreto. Por favor, entre com o mês corrente.");
		return false;
		}
	else{
		if((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30){
			alert("Dia incorreto. O mês especificado contém no máximo 30 dias.");
			return false;
			} 
		else{
			if(ano%4!=0 && mes==2 && dia>28){
					alert("Data incorreta. O mês especificado contém no máximo 28 dias.");
					return false;
					} 
			else{
				if(ano%4==0 && mes==2 && dia>29){
					alert("Data incorreta. O mês especificado contém no máximo 29 dias.");
					return false;} 
				else{ 
					//alert ("Data correta.");
					return true;}
				}
			}
		}
} 
else {
	alert(msgErro);
	campo.focus();
	return false;}
}

// Valida ISS---------------------------------------------------------------
function ValidaISS(obj)
{
	if (obj.value=='')
	{
		alert('Digite a Inscrição do ISS.');
		obj.focus();
		obj.select();
		return false;
	}
	obj2 = ""+obj.value
	obj.value = fnZeroAEsquerda(obj2,7);
	return true;
	

	/*
	if (obj2.length < 7)
	{
		alert('Inscrição do ISS deve ter 7 digitos!');
		obj.focus();
		obj.select();
		return false;
	}
	else
	{
		return true;
	}
	*/
}

//------------------------------------------------
// Funções para validar Inscrição Municipal de Fortaleza
// Por Rodrigo Petry
// 06/04/2009
//------------------------------------------------

function validaInscMunicipal(strInscMunicipal, options) {
	
	var strInscMunicipal, digitosIguais,algarismos,i,j,soma,mod11,digitoVerificador;
	
	strInscMunicipalValor = strInscMunicipal.value.replace(/[^0-9]/g, '');
	
	if(strInscMunicipalValor.length != 7) {
		
		alert('Inscrição do ISS deve ter 7 digitos.');
		strInscMunicipal.focus();
		strInscMunicipal.select();
		
		return false;
	}
	
	digitosIguais = strInscMunicipalValor.search(/0{7}|1{7}|2{7}|3{7}|4{7}|5{7}|6{7}|7{7}|8{7}|9{7}/g);
	
	if(digitosIguais != -1) {
		
		alert('Inscrição do ISS inválida.');
		strInscMunicipal.focus();
		strInscMunicipal.select();
		
		return false;
	}
	else {
		
		algarismos = strInscMunicipalValor.split('');
		
		j = 2;
		soma = 0;
		for(i=5; i >= 0 ; i--) {
			soma = soma + (parseInt(algarismos[i]) * j);
			j++;
		}
	
		mod11 = soma%11;
			
		if(mod11 < 2) {
		
			digitoVerificador = 0;
	
		}
		
		if(mod11 >= 2) {
		
			digitoVerificador = 11 - mod11;
		
		}
		
		if(algarismos[6] != digitoVerificador) {
			
			alert('Inscrição do ISS inválida.');
			strInscMunicipal.focus();
			strInscMunicipal.select();
			
			return false;
		}
		else {
			return true;
		}
	}
	
	return false;
	
}


// Mostra esconde layer (browsers versão 4)
function encontraObj(n, d) 
{
  var p,i,x;  
  if(!d) d=document; 
  if((p=n.indexOf("?"))>0&&parent.frames.length) 
  {
  	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

// Mostra esconde layer (browsers versão 6)
function mostraEscondeLayers() 
{
  var i,p,v,obj,args=mostraEscondeLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
 	if ((obj=encontraObj(args[i]))!=null) 
	{ 
		v=args[i+2];
  		if (obj.style) 
  		{ 
  			obj=obj.style; v=(v=='mostra')?'visible':(v=='esconde')?'hidden':v; 
  		}
  		obj.visibility=v; 
  	}
}

// Valida campos do formulário
function validaForm(obj,nome,tipo)
{
	if (tipo == "d")
	{
		if (!fnVerData(obj.value))
		{
			obj.focus();
			obj.select();
			return false;
		}
		else
			return true;
	}
	else if (tipo == "h")
	{
		if (!fnValidaHora(obj.value))
		{
			alert("Hora inválida. Formato: HH:MM:SS");
			obj.focus();
			obj.select();
			return false;
		}
		else
			return true;
	}
	else
	{
		if (obj.value == "")
		{	
			alert("Preencha o campo: " + nome + ".");
			obj.focus();
			return false;
		}
		else 
			return true;
	}		
}

// Função para formatar Data colocando as barras ao digitar
function ajustar_data(input)
{
	if ((event.keyCode<48)||(event.keyCode>57)){
		event.returnValue = false; 
		} else { 
		if ((input.value.length==2)||(input.value.length==5))
			input.value=input.value + "/" ;
	}
}

// Função para formatar Hora colocando os dois pontos ao digitar
function ajustar_hora(input)
{
	if ((event.keyCode<48)||(event.keyCode>57)){
		event.returnValue = false; 
		} else { 
		if ((input.value.length==2)||(input.value.length==5))
			input.value=input.value + ":" ;
	}
}

// Função para formatar hora
function FormataHora(campo,tammax, teclapres) 
{
	numHora = 24;
	var tecla = teclapres.keyCode;
	vr = campo;
	vr = vr.replace( ":", "" );
	tam = vr.length ;
	
	if (tecla == 8 ) 
	{
		tam = tam - 1 ;
	}

	alert(tam);

	if (tam == 2) 
	{
		campo.value = vr.substr( 0, 2 ) + ':' +  vr.substr( 2, tam );
	}
	
	if (vr.substr( 0, 2 ) > 24 ) 
	{ 
        alert('O limite de horas é 24.');
        campo.value = "";
        campo.focus();        
		
		if (vr.substr( 2, 4 ) > 60 ) 
		{ 
            alert('O limite de minutos é 60.');
	        campo.value = "";
            campo.focus();
		}
		if (vr.substr( 4, 6 ) > 60 ) 
		{ 
            alert('O limite de segundos é 60.');
	        campo.value = "";
            campo.focus();
		}
	}
}


// função para formatar moeda quando o usuário digita
function FmascTempoReal(ConteudoCampo)
{  //alert ("Key Press: " + event.keyCode);
if (ConteudoCampo.value.length < ConteudoCampo.maxLength) {
   if (((event.keyCode) > 47) && ((event.keyCode) < 58)) //abre if #1
   {
   NumDig = ConteudoCampo.value;
   //alert("NumDig = " + NumDig);
   TamDig = NumDig.length;
   //alert("TamDig = " + TamDig);
   Contador = 0;
   if (TamDig > 1) { //abre if #2
      numer = "";
      for (i = TamDig; (i >= 0); i--){
		  //alert("i = " + i);
		  //alert("NumDig.substr(i,1) = " + NumDig.substr(i,1));
		  //alert("parseInt(NumDig.substr(i,1)) = " + parseInt(NumDig.substr(i,1)));
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9)) //abre if #3
            {
             Contador++;
             //alert("Contador = " + Contador);
             if ((Contador == 2) && ((TamDig -i) < 4))
              {numer = ","+numer;
               Contador = 0;
               }
             else if (Contador == 3)
              {numer = "."+numer;
               Contador = 0;
              }
             numer = NumDig.substr(i, 1)+numer;
             //alert("numer = " + numer);
            } //fecha if #3
           } //fecha for
      ConteudoCampo.value = numer;
      //alert(ConteudoCampo.value);
      }; //fecha if #2
   return(true)
   } //fecha if #1
   else return(false)
}
}


function FtrataBackSpace(dado)
{
   NumDig = dado.value;
   TamDig = NumDig.length;
   TamDig--;
   Contador = 0;

   if ((TamDig >= 0) && (event.keyCode == 8))
    { numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
			 /*alert(NumDig.substr(i, 1) + " Contador " + Contador+ " numer "+ numer+ " TamDig " +TamDig + " i " + i );*/
             if ((Contador == 4) && ((TamDig -i) < 5))
              {numer = ","+numer;
               Contador = 0;
               }
             else if ((Contador == 3) && ((numer.length) > 4))  
              {numer = "."+numer;
               Contador = 0;
              }
			  
             numer = NumDig.substr(i, 1)+numer;
			
            }
			}
			if (numer == "001" || numer == "000" || numer == "002" || numer == "003" || numer == "004" || numer == "005" || numer == "006" || numer == "007" || numer == "008" || numer == "009") 
			    numer="";		
			if ((numer.length) == 3 )
			    numer= "0," + numer;

		dado.value = numer;
      };

}

/*
---------------------------------------------------------------------------
FUNÇÃO:	fnValidaValor
ENTRADA: nValor= variável com o valor a ser validado.
SAÍDA:	true = se o valor passado é válido.
			false = se o valor passado é inválido.

OBS: O valor correto esta no formato: 99.999.999.999,99
---------------------------------------------------------------------------
*/

function fnValidaValor(nValor) 
{
	nTam = nValor.length;

	sModelo = '99.999.999.999,99';

	if (nValor.indexOf(',') > 0)
	{
		nCont = sModelo.length;
	}
	else
	{
		nCont = sModelo.length - 3;
	}

	bValNum = false  
 
	if (nTam > 0)
	{
		bValNum = true  ;
		nAux =  "";
 
		while (nTam > 0 && bValNum)
		{
			nDig = nValor.substr(nTam,1);
			if (sModelo.substr(nCont,1) == "9")
			{
				if (nDig == "." || nDig == "," )
				{
					bValNum = false;
				}
				else
				{
					nAux = nDig + nAux;
				}
			}
			else
			{
				if (sModelo.substr(nCont,1) != nValor.substr(nTam,1))
				{
					bValNum = false;
				}
			}

			nTam = nTam - 1;
			nCont = nCont - 1;
		}  //Fim do while
	}
    
	if (!bValNum) 
	{
		return false;
	}

	return true;
}

// Verifica se somente números foram digitados no campo
function fnValidaNumero(campo) 
{
	//var er = "\d{2,1},\d{1}";
	str = campo.value;
	var nRet = true;
	var strValidNumber="1234567890,";
	for (nCount=0; nCount < str.length; nCount++) 
	{
		strTempChar=str.substring(nCount,nCount+1);
		if ( (strValidNumber.indexOf(strTempChar,0)==-1) || (strTempChar == ".") ) 
		{
			return false;
		}
	} 
	
	//return er.test(campo.value);
	
	return(nRet);
} 



function Valida_Ano_GR(obj_ano, obj_processo, nAno)
{
  if (obj_ano.value=='')
   {
    alert('Digite o ano da guia.');
    obj_ano.focus();
    return false; 
   }
  if (obj_processo.value=='') 
   {
    alert('Digite o número da guia.');
    obj_processo.focus();
    return false;
   }
    return true;
}

function Valida_Ano_Amidf(obj_ano, obj_processo, nAno)
{
  if (obj_ano.value=='')
   {
    alert('Digite o ano da Autorização.');
    obj_ano.focus();
    return false; 
   }
  if (obj_processo.value=='') 
   {
    alert('Digite o número da autorização.');
    obj_processo.focus();
    return false;
   }
  if (parseInt(obj_ano.value) < parseInt(nAno - 5)) 
   {
    alert('Autorização de ano inválido. ');
    obj_processo.focus();
    return false;
   }
    return true;
}

// Valida E-MAIL
function Valida_EMAIL(mail){
    var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
    var check=/@[\w\-]+\./;
    var checkend=/\.[a-zA-Z]{2,3}$/;
	
    if(typeof(mail) == "string") {
        varmail = mail;
	}
    else if(typeof(mail) == "object") {
		varmail = mail.value;
	}
	
	if(((varmail.search(exclude) != -1)||(varmail.search(check)) == -1)||(varmail.search(checkend) == -1)){
		return false;
    }
    else {
		return true;
    }
}


// Valida Formulario FALE CONOSCO
function Valida_FALE_CONOSCO(obj_nome, obj_email, obj_assunto, obj_mensagem) {
	
	if (obj_nome.value=='') {
		alert('Digite seu nome.');
		obj_nome.focus();
		return false; 
	}
	if (obj_email.value=='') {
		alert('Digite seu e-mail.');
		obj_email.focus();
		return false;
	}
	if (Valida_EMAIL(obj_email.value)==false) {
		alert('E-mail inválido.');
		obj_email.focus();
		return false;
	}
	if (obj_assunto.value=='') {
		alert('Escolha o assunto.');
		obj_assunto.focus();
		return false;
	}
	if (obj_mensagem.value=='') {
		alert('Digite a mensagem.');
		obj_mensagem.focus();
		return false;
	}
	
	return true;
}


//------------------------------------------------
// Função para validar CPF por Ajax (Spry)
// Por Germano Guerra
//------------------------------------------------

var ajaxValidaCPF = function(strCPF, options) {

	var numeros, digitos, soma, i, resultado, digitos_iguais;
	
	strCPF = strCPF.replace(".", "");
	strCPF = strCPF.replace(".", "");	
	strCPF = strCPF.replace("-", "");

	digitos_iguais = 1;
	
	if (strCPF.length != 11) {
		flagCPFValid = false;
		return false;
	}

	for (i = 0; i < strCPF.length - 1; i++)
		if (strCPF.charAt(i) != strCPF.charAt(i + 1)) {
			  digitos_iguais = 0;
			  break;
		}
		
	if (!digitos_iguais) {
		numeros = strCPF.substring(0,9);
		digitos = strCPF.substring(9);
		soma = 0;
		for (i = 10; i > 1; i--)
			  soma += numeros.charAt(10 - i) * i;
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0)) {
			flagCPFValid = false;
			return false;
		}
		numeros = strCPF.substring(0,10);
		soma = 0;
		for (i = 11; i > 1; i--)
			  soma += numeros.charAt(11 - i) * i;
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1)) {
			flagCPFValid = false;
			return false;
		}
		flagCPFValid = true;
		return true;
		}
	else {
	flagCPFValid = false;
	return false;
	}

}

//------------------------------------------------
// Função para validar CNPJ por Ajax (Spry)
// Por Germano Guerra
//------------------------------------------------

var ajaxValidaCNPJ = function(strCNPJ, options) {
	
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	
	strCNPJ = strCNPJ.replace(".", "");
	strCNPJ = strCNPJ.replace(".", "");	
	strCNPJ = strCNPJ.replace("/", "");		
	strCNPJ = strCNPJ.replace("-", "");
	
	digitos_iguais = 1;
	
	if (strCNPJ.length != 14)  {
		flagCNPJValid = false;
		return false;
	}
	
	for (i = 0; i < strCNPJ.length - 1; i++)
		if (strCNPJ.charAt(i) != strCNPJ.charAt(i + 1)) {
			  digitos_iguais = 0;
			  break;
		}
		
	if (!digitos_iguais) {
		tamanho = strCNPJ.length - 2
		numeros = strCNPJ.substring(0,tamanho);
		digitos = strCNPJ.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--) {
			  soma += numeros.charAt(tamanho - i) * pos--;
			  if (pos < 2)
					pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0)) {
			flagCNPJValid = false;
			return false;
		}
		tamanho = tamanho + 1;
		numeros = strCNPJ.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--) {
			  soma += numeros.charAt(tamanho - i) * pos--;
			  if (pos < 2)
					pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1)){
			flagCNPJValid = false;
			return false;
		}
		flagCNPJValid = true;;
		return true;
		}
	else {
		flagCNPJValid = false;
		return false;
	}
} 

//------------------------------------------------
// Funções para validar CEP
// Por Germano Guerra
//------------------------------------------------
var intervalo = 0;

var ajaxValidaCEP = function(strCEP, options) {
	
	if (dsEndereco.getDataWasLoaded() && dsEndereco.getData()[0]["intCodErro"]) {
		return false;
	} 
	else {
		var intervalo = setInterval(verificaDadosCarregados, 1000)
	}
}

function verificaDadosCarregados() {
	if (dsEndereco.getDataWasLoaded() && dsEndereco.getData()[0]["intCodErro"]) {
		clearInterval(intervalo);
		return false;
	} 
	if (dsEndereco.getDataWasLoaded() && !dsEndereco.getData()[0]["intCodErro"]) {
		clearInterval(intervalo);
		return true;
	} 
}

//------------------------------------------------
// Funções para validar Inscrição Municipal de Fortaleza
// Por Rodrigo Petry
// 06/04/2009
//------------------------------------------------

function validaInscMunicipal(strInscMunicipal, options) {
	
	var strInscMunicipal, digitosIguais,algarismos,i,j,soma,mod11,digitoVerificador;
	
	strInscMunicipal = strInscMunicipal.replace(/[^0-9]/g, '');
	
	if(strInscMunicipal.length != 7) {
		return false;
	}
	
	digitosIguais = strInscMunicipal.search(/0{7}|1{7}|2{7}|3{7}|4{7}|5{7}|6{7}|7{7}|8{7}|9{7}/g);
	
	if(digitosIguais != -1) {
		return false;
	}
	else {
		
		algarismos = strInscMunicipal.split('');
		
		j = 2;
		soma = 0;
		for(i=5; i >= 0 ; i--) {
			soma = soma + (parseInt(algarismos[i]) * j);
			j++;
		}
	
		mod11 = soma%11;
			
		if(mod11 < 2) {
		
			digitoVerificador = 0;
	
		}
		
		if(mod11 >= 2) {
		
			digitoVerificador = 11 - mod11;
		
		}
		
		if(algarismos[6] != digitoVerificador) {
			return false;
		}
		else {
			return true;
		}
	}
	
	return false;
	
}
