// Browser em execução
var navegador = navigator.userAgent.toLowerCase();

// Função que devolve uma nova requisição de leitura de XML - Ajax, tipo [1=text,2=XML]
var novoXML = function(url, funcao, metodo){
		
	var xmlhttp; xmlhttp = null;
	
	// Sintaxe para browsers padrão
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();	
		// Evitar que o Mozilla gere algum erro de tipo Mime
		if(xmlhttp.overrideMimeType){xmlhttp.overrideMimeType("text/xml");}
	}
	// Sintaxe para IE
	else if (window.ActiveXObject){xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
	if (xmlhttp!=null){		
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState==4){ // 4 = "carregado"				
				if (xmlhttp.status==200){// 200 = "Ok"					
					funcao(xmlhttp);
					
				}else{
					alert("Um erro ocorreu ao tentar carregar os dados do banco ("+xmlhttp.statusText+")");
				}
			} 
		}		 
		xmlhttp.open(metodo, url, true);
		xmlhttp.send(null);
	}else{
		alert("Este navegador não suporta requisições XML.");
	}
	

}

function $id(obj) {return document.getElementById(obj)};
function $tag(obj,i){return document.getElementsByTagName(obj)[i]};

// Função para retornar resposta do sistema (vocábulos) de acordo com a lingua (lin_ID)
function xml_gerar(url){
	// Para windows
    if(window.XMLHttpRequest){
        var xml = new XMLHttpRequest();
        xml.open("GET", url ,false);
        xml.send(null);
        return xml.responseXML;
	// Para os demais browsers
    }else if(window.ActiveXObject){
        var xml = new ActiveXObject("Msxml2.DOMDocument.3.0");
        xml.async = false;
        xml.load(url);
        return xml;
    }
}

// Função para retornar um vacábulo específico (voc_ID)
function form_respostas(voc_ID){
	var xml = xml_gerar("adm/xmls/vocabulos_"+lin_ID+".xml", voc_ID);
	return xml.getElementsByTagName("voc_ID"+voc_ID)[0].childNodes[0].nodeValue;
}

// Função para remover todas as opções de um campo select
function select_removeropc(obj){
	// reset select options
	for (var i=obj.length; i>0; i--){
		try {
			// Para FF, Chrome
			obj.remove(i);
		} catch(ex) {
			// Para IE
			obj.options[i] = null;			
		}		
	}	
}

// Função para inserir opções em um campo select [obj = campo do formulário do tipo select, array = array de valores]
function select_inseriropc(obj, array){
	for(var i=0; i<array.length; i++){
						
		var oOption 		= document.createElement("option");
		  oOption.value 	= array[i].id;
		  oOption.text 		= array[i].valor;

		try {
			// for Firefox
			var currentOption = obj.options[i+1];
			obj.add(oOption, currentOption);
		} catch(ex) {
			// for IE
			obj.add(oOption);	
		}
	}
}

// Abre uma url em um popup
function popup(url,larg,altu){

	larg = (larg=="") ? larg = screen.width  : larg = larg;
	altu = (altu=="") ? altu = screen.height : altu = altu;

	// Define o posicionamento da janela para o centro da tela
	var left = ( screen.width/2  ) - ( larg/2 );
	var top  = ( screen.height/2 ) - ( altu/2 );	

	novopopup = window.open(url,"janela","top="+top+",left="+left+",width="+larg+",height="+altu+",location=0,status=0,toolbar=0,resisable=0,scrollbars=yes");
	novopopup.focus();
	
	// Cria uma função que fechará o popup gerado caso ele saia de foco
	function fecharpopup(){
		if (novopopup != undefined ){
			novopopup.close();
		}else{
			document.onclick = null;		
		}
	}
	
	/* fecha popup quando clica fora */
	//document.onclick = fecharpopup;
}

// Popup para ampliação de imagens
function ampliarimg(img_url){	
	
	var img 		= new Image();	
		img.src 	= img_url;

	w = img.width; h = img.height;	

	// to set window position center center
	var winLeft = (screen.width/2)  - (w/2);
	var winTop  = (screen.height/2) - (h/2);

	html = "<html><head><title>Image</title></head><body style='border:0; padding:0px; margin:0; overflow:none'>" 
	html +="<img src='" + img_url + "' border=0 onclick='self.close()' title='resposta(248)' style='cursor:pointer;'></body></html>";

	janelaimg = window.open("about:blank","image","top="+winTop+",left="+winLeft+",width="+w+",height="+h+", location=0, status=0, toolbar=0, resisable=0, scrollbars=0");	
	janelaimg.document.write(html);	
	janelaimg.document.close();	
	janelaimg.focus();
	
	function fecharjanelaimg(){
		if ( janelaimg != undefined ){
			janelaimg.close();
			document.onclick = null;
		}else{
			document.onclick = null;		
		}
	}
	
	document.onmouseup = fecharjanelaimg;	
}

// Função que faz disparar a animação de chamadas dos elementos do tipo Destaques [ele_id = elemento da página que deverão ser carregados os dados de chamada, t=tempo da transição]
var f_destaques = function(ele_ID,t){

	var d_ID 	= (destaques.length)-1;	// Resgata a última posição da array
	var cha_ID  = 0; // Inicia a posição primeira para a sequencia de chamadas
	var status	= true;
	var tempo;
	
	// Função que fará a transição das chamadas
	function iniciar(){	
					
		if(cha_ID<0) cha_ID = destaques[d_ID].length-2; // Se o numero da chamada corrente for menor que zero, então retorna a ultima chamada		
		if(cha_ID>(destaques[d_ID][cha_ID].length-2)) cha_ID = 0; // Se o numero da chamada corrente for igual a ultima, então retorna a primeira		
		
		// Coloca os valores de titulo e texto das chamadas na caixa de destaque, o titulo é um elemento do tipo "a", o texto é o "span" dentro de "a"
		document.getElementById(ele_ID).getElementsByTagName("a")[0].innerHTML = destaques[d_ID][cha_ID].cha_titulo+"<span>"+destaques[d_ID][cha_ID].cha_texto+"</span>";		
		document.getElementById(ele_ID).style.backgroundImage = "url(imagens/destaques/"+destaques[d_ID][cha_ID].cha_img+")";
		
		// Define a url do link
		var cha_url;
		
		if( destaques[d_ID][cha_ID].cha_url.indexOf("www")!="-1" ){cha_url = "http://"+destaques[d_ID][cha_ID].cha_url;}else{cha_url = destaques[d_ID][cha_ID].cha_url};		document.getElementById(ele_ID).getElementsByTagName("a")[0].setAttribute("href",cha_url);
		
		// Define a forma como será aberta a URL [N=Nova janela, P=Popup, A=Janela atual]
		if( destaques[d_ID][cha_ID].cha_local == "N" ){document.getElementById(ele_ID).getElementsByTagName("a")[0].setAttribute("target","_blank")}else if( destaques[d_ID][cha_ID].cha_local == "P" ){cha_url = "javascript:void(0); popup('"+cha_url+"',"+destaques[d_ID][cha_ID].cha_poplargura+","+destaques[d_ID][cha_ID].cha_popaltura+")"; document.getElementById(ele_ID).getElementsByTagName("a")[0].setAttribute("target","_self")}else if( destaques[d_ID][cha_ID].cha_local == "A" ){document.getElementById(ele_ID).getElementsByTagName("a")[0].setAttribute("target","_self")};document.getElementById(ele_ID).getElementsByTagName("a")[0].setAttribute("href",cha_url);
				
		cha_ID ++; // Define a posição da array para a próxima chamada		
		clearTimeout(tempo);
		
		// A transiçao acontecerá apenas se o status for verdadeiro
		if(status){			
			if(destaques[d_ID].length-1>1) {tempo = setTimeout(iniciar,(t*1000));} // Se houver mais que uma chamada, inicia-se as trasições	
		}
	};
	
	// Função para o botão rodar e parar
	function acao(){
		if(status){
			clearTimeout(tempo); // cancela o ultimo timeout
			status = false;				
			this.getElementsByTagName("img")[0].setAttribute("src","imagens/versoes/1/botao_rodar.png"); // Altera a imagem do botão para iniciado
		}else{			
			status = true;	
			tempo = setTimeout(iniciar,(t*1000));
			this.getElementsByTagName("img")[0].setAttribute("src","imagens/versoes/1/botao_parar.png"); //Altera a imagem do botão para parado
		}	
	}
	// Função para o botão voltar
	function voltar(){
		clearTimeout(tempo); // cancela o ultimo timeout
		cha_ID -= 2;		
		iniciar();
	}
	// Função para o botão avançar
	function avancar(){
		clearTimeout(tempo); // cancela o ultimo timeout
		iniciar();
	}
	
	var botoes = document.getElementById(ele_ID).getElementsByTagName("a");
	
	for( var i=0; i<botoes.length; i++ ){			
		if (botoes[i].className == "elementos_botoes_acao") 	botoes[i].onclick 	= acao;
		if (botoes[i].className == "elementos_botoes_voltar") 	botoes[i].onclick = voltar;
		if (botoes[i].className == "elementos_botoes_avancar") 	botoes[i].onclick= avancar;
	}

	iniciar(); // Dispara o processo
}

// Função que fará a leitura das mensagens de mural por mural [mur_ID] e mensagem [murmsg_ID]
var f_muralmsg_ler = function(obj,mur_ID,murmsg_ID,msg){
	
	document.getElementById(mur_ID).innerHTML = msg;
	
	function xmlfuncao(xml){	
	
		function preencher(valor,carac){
			if (valor.length>0) return valor+carac; else return "";
		}
		var resposta= xml.responseText.split(",");
		
		document.getElementById(mur_ID).innerHTML = '<span class="msg-titulo"><span class="msg-data">'+resposta[2]+'</span>'+preencher(resposta[0],", ")+'</span><br /><span class="msg-texto">'+resposta[1]+'</span><span class="msg-cliente">, '+resposta[3] +' '+ preencher(resposta[4],",")+' '+ preencher(resposta[6]," - ") + preencher(resposta[5],"") +'</span>'
		
		//obj.className += " msgbotaonum-ativo";
	}
	
	novoXML("adm/ajax/muralmensagens_listar.asp?murmsg_ID="+murmsg_ID,xmlfuncao,"get");
}

// Função que verifica a validade de um CNPJ
function validar_cnpj(s){
	var i; s = limpa_string(s); var c = s.substr(0,12); var dv = s.substr(12,2); var d1 = 0; 
	for (i = 0; i < 12; i++)	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
    
	if (d1 == 0) return false; d1 = 11 - (d1 % 11);	if (d1 > 9) d1 = 0;	if (dv.charAt(0) != d1) return false; d1 *= 2;
	
	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	
	d1 = 11 - (d1 % 11); if (d1 > 9) d1 = 0; if (dv.charAt(1) != d1) return false; return true;
}

// Função que verifica a validade de um e-mail
function validar_email(email) {
	var dot=false; var arr=false; var char=false;
	
	for(var i=0; i<email.length; i++) {
		if (email.charAt(i)=="@") arr=true;
        else if (email.charAt(i) == ".") dot = true;
        else if (email.charAt(i) != " ") char= true;
     }
	 
	 return (dot & arr & char);
}

// Função que verifica todos os campo de um formulário para validação a efeito de envio de dados para o banco
function validar_form(obj,tipo){	
	
	var i    	= 0; 		// Valor inicial
	var pos		= true;
	
	if(tipo != 3 ){
		// Laço entre todos os campos do formulário
		while ((i < obj.elements.length)){
			if( obj.elements[i].getAttribute("obrigatorio")=="sim" ){
				if(obj.elements[i].value.length==0){
					
					// Recupera o valor do nó do elemento cujo campo esteja inserido
					var msg = (obj.elements[i].parentNode.firstChild.nodeValue == null) ? "" : 
						form_respostas(5) + " " + obj.elements[i].parentNode.firstChild.nodeValue +"."; /* Rsposta de obrigatoriedade */					
						
					// Se exisir um elemento próprio para recebimento de mensagem
					if(document.getElementById("resposta") != undefined){						
						document.getElementById("resposta").innerHTML = msg;	
					}else{
						alert(msg);
					}
					
					obj.elements[i].focus();
					var pos	= false;
					break;				
				}else{
					var pos	= true;
				}
			}
			
			// Verifica todos os campos cujo formato seja igual a email
			if( (obj.elements[i].getAttribute("formato") == "email") && (obj.elements[i].value.length > 0) ){
				if(!validar_email(obj.elements[i].value)){
					
					// Recupera o valor do nó do elemento cujo campo esteja inserido
					var msg = (obj.elements[i].parentNode.firstChild.nodeValue == null) ? "" : 
						form_respostas(6) + " " + obj.elements[i].parentNode.firstChild.nodeValue +"."; /* Resposta de obrigatoriedade */				
						
					// Se exisir um elemento próprio para recebimento de mensagem
					if(document.getElementById("resposta") != undefined){						
						document.getElementById("resposta").innerHTML = msg;	
					}else{
						alert(msg);
					}
					
					obj.elements[i].focus();
					var pos	= false;
					break;
					return pos;
				}
				
			}
			
			i++;
		}
	}
	if(pos){
		// Se exisir um elemento próprio para recebimento de mensagem
		if(document.getElementById("resposta") != undefined){						
			document.getElementById("resposta").innerHTML = form_respostas(4);	
		}					
		
		// Tipo de procedimento, 1=cadastrar, 2=alterar, 3=apagar, 0=nulo
		// Condição apenas para a opção 3, evita o preenchimento obrigatório dos campos para o submit
		if(tipo == "3"){			
			// Confirmação da exclusão
			if(confirm("Confirma excluir este registro?")){
				pos = true;
			}else{
				pos = false;
				// Remove a resposta do campo
				if(document.getElementById("resposta") != undefined){						
					document.getElementById("resposta").innerHTML = "";	
				}
			}
		}
	}

	return pos;
}


/*	Função que ativa o foco do campo de um formulário e valida os botões submit segundo as opções de procedimento
	1 = Inserir, 2 = Alterar, 3 = Excluir
*/
function ativar_form(){	
	
	// Laço entre todos os formulários da página
	for( var i=0; i<document.forms.length; i++ ){
		
		// Laço entre todos os campos do formulário corrente
		for(var ii=0; ii<document.forms[i].elements.length; ii++){

			// Atribui funções para todos os campos diferente de submit, checkbox, radio
			if	(
				 (document.forms[i].elements[ii].getAttribute("type") != "submit") 	 &&
				 (document.forms[i].elements[ii].getAttribute("type") != "button") 	 &&
				 (document.forms[i].elements[ii].getAttribute("type") != "checkbox") &&
				 (document.forms[i].elements[ii].getAttribute("type") != "radio")
				){
				
				if ( document.forms[i].elements[ii].getAttribute("ati_status") == "0" ){
				}else{
					if ( document.forms[i].elements[ii].tagName.toLowerCase() != "fieldset" ){
						var classeatual = document.forms[i].elements[ii].className;
						document.forms[i].elements[ii].onfocus = function(){this.className = "input-ativo"};
						document.forms[i].elements[ii].onblur  = function(){this.className = ""};
					}
				}
				
				// Acrescenta o símbolo * para campos de preenchimento obrigatório
				if(document.forms[i].elements[ii].getAttribute("obrigatorio") == "sim"){
					document.forms[i].elements[ii].parentNode.firstChild.nodeValue = "** "+document.forms[i].elements[ii].parentNode.firstChild.nodeValue;
				}
				
				// Máscara para campos tipo data
				if(document.forms[i].elements[ii].getAttribute("formato") == "data"){
					document.forms[i].elements[ii].onkeyup = function(){ mascara(this,'99/99/9999',1,this) }
					document.forms[i].elements[ii].onblur  = function(){ mascara(this,'99/99/9999',1,this); this.className = "" }
				}
				
				// Máscara para campos tipo CEP
				if(document.forms[i].elements[ii].getAttribute("formato") == "cep"){
					document.forms[i].elements[ii].onkeyup = function(){ mascara(this,'99999999',1,this) }
					document.forms[i].elements[ii].onblur  = function(){ mascara(this,'99999999',1,this); this.className = "" }
				}
			}
			
			var form  = document.forms[i];
			var field = document.forms[i].elements[ii];
			
			// Ativa as funções de cada tipo de botão submit [1,2,3]
			// 1
			if((field.getAttribute("type") == "submit") && field.getAttribute("formato") == "inserir"){				
				field.onclick = function(){
					form.tipo.value = 1;					
				}
			}
			
			// 2
			if((field.getAttribute("type") == "submit") && field.getAttribute("formato") == "alterar"){				
				field.onclick = function(){
					form.tipo.value = 2;					
				}
			}
			
			// 3
			if((field.getAttribute("type") == "submit") && field.getAttribute("formato") == "excluir"){				
				field.onclick = function(){
					form.tipo.value = 3;					
				}
			}
			
			// 4
			if((field.getAttribute("type") == "submit") && field.getAttribute("formato") == "busca"){				
				field.onclick = function(){
					if(form.pagina_atual != undefined) form.pagina_atual.value = 0; // Limpa o campo ponteiro da busca					
				}
			}
			
			// Ativa a verificação de campos do formulário
			document.forms[i].onsubmit = function(){
				var tipo = (this.tipo != undefined) ? this.tipo.value : 0;				
				return validar_form(this,tipo);
			}
		}		

		// Posiciona o ponteiro do mouse (foco) no primeiro campo ativo do formulário
		if(document.forms[0] != undefined){
			if((document.forms[0].elements[0] != undefined) && (document.forms[0].elements[0].getAttribute("type") != "hidden" )){
				document.forms[0].elements[0].focus();
			}
		}
	}
}

function mascara(campo, formato, conteudo, event){

 valor = campo.value;

 var i, j;
 var caracs = [ '.', '/', '-', ':', '(', ')', ',' ];
 var auxPonto = formato;
 var auxBarra = formato;
 var auxHifen = formato;
 var auxDblPonto = formato;
 var auxAbrePar = formato;
 var auxFechaPar = formato;
 var auxVirgula = formato;
 var tamanho = formato.length;
 var posPonto = new Array(tamanho);
 var posBarra = new Array(tamanho);
 var posHifen = new Array(tamanho);
 var posDblPonto = new Array(tamanho);
 var posAbrePar = new Array(tamanho);
 var posFechaPar = new Array(tamanho);
 var posVirgula = new Array(tamanho);
 var keyPress = event;

 campo.maxLength = tamanho;

 if (event.keyCode != 17) {
  switch (conteudo) {
  case 1: // Verifica se soh podem ser entrados valores numericos
   if (!(event.keyCode >= 48 && (event.keyCode <= 57)))
    event.keyCode = 0;
   break;
  case 2: // Somente Letras
   if (!((event.keyCode >= 97 && event.keyCode <= 122)
     || event.keyCode >= 65
     && event.keyCode <= 90))
    event.keyCode = 0;
   break;
  case 3: // Letras e numeros
   if (!((event.keyCode >= 48 && event.keyCode <= 57)
     || (event.keyCode >= 97 && event.keyCode <= 122)
     || (event.keyCode >= 65 && event.keyCode <= 90)))
    event.keyCode = 0;
   break;
  }
 }

 // ----------------------------- PEGA A FORMATACAO DA MASCARA
 // ------------------
 for (i = 0; i < tamanho; i++) {

  posPonto[i] = auxPonto.indexOf('.');
  posBarra[i] = auxBarra.indexOf('/');
  posHifen[i] = auxHifen.indexOf('-');
  posDblPonto[i] = auxDblPonto.indexOf(':');
  posAbrePar[i] = auxAbrePar.indexOf('(');
  posFechaPar[i] = auxFechaPar.indexOf(')');
  posVirgula[i] = auxVirgula.indexOf(',');

  auxPonto = auxPonto.substring(posPonto[i] + 1, tamanho);
  auxBarra = auxBarra.substring(posBarra[i] + 1, tamanho);
  auxHifen = auxHifen.substring(posHifen[i] + 1, tamanho);
  auxDblPonto = auxDblPonto.substring(posDblPonto[i] + 1, tamanho);
  auxAbrePar = auxAbrePar.substring(posAbrePar[i] + 1, tamanho);
  auxFechaPar = auxFechaPar.substring(posFechaPar[i] + 1, tamanho);
  auxVirgula = auxVirgula.substring(posVirgula[i] + 1, tamanho);

  if (i > 0) {
   posPonto[i] = posPonto[i] + posPonto[i - 1];
   posBarra[i] = posBarra[i] + posBarra[i - 1];
   posHifen[i] = posHifen[i] + posHifen[i - 1];
   posDblPonto[i] = posDblPonto[i] + posDblPonto[i - 1];
   posAbrePar[i] = posAbrePar[i] + posAbrePar[i - 1];
   posFechaPar[i] = posFechaPar[i] + posFechaPar[i - 1];
   posVirgula[i] = posVirgula[i] + posVirgula[i - 1];
   posPonto[i] = posPonto[i] + 1;
   posBarra[i] = posBarra[i] + 1;
   posHifen[i] = posHifen[i] + 1;
   posDblPonto[i] = posDblPonto[i] + 1;
   posAbrePar[i] = posAbrePar[i] + 1;
   posFechaPar[i] = posFechaPar[i] + 1;
   posVirgula[i] = posVirgula[i] + 1;
  }
 }

 // Retirando a máscara
 for (i = 0; i < campo.value.length; i++) {
  valor = valor.replace('-', '');
  valor = valor.replace('(', '');
  valor = valor.replace(')', '');
  valor = valor.replace(':', '');
  valor = valor.replace('/', '');
  valor = valor.replace('.', '');
  valor = valor.replace(',', '');
 }

 // Faz a validação se for apenas número
 // utilizado para fazer a validação de Ctrl+V
 if (conteudo == 1) {
  if (isNaN(valor)) {
   if (isNaN(valor.charAt(valor.length - 2)))
    valor = "";
   else
    valor = valor.substring(0, valor.length - 1);
  }
 }

 indicePonto = 0;
 indiceBarra = 0;
 indiceHifen = 0;
 indiceDblPonto = 0;
 indiceVirgula = 0;
 indiceAbrePar = 0;
 indiceFechaPar = 0;

 // Varre o campo aplicando a máscara
 for (i = 0; i < valor.length; i++) {
  if (i == posPonto[indicePonto]) {
   if (valor.charAt(i) != '.') {
    if (i == 0) {
     valor = '.' + valor;
    } else if (i == valor.length) {
     valor = valor + '.';
    } else {
     valor = valor.substring(0, i) + '.' + valor.substring(i);
    }
    indicePonto++;
   }
  }
  if (i == posBarra[indiceBarra]) {
   if (valor.charAt(i) != '/') {
    if (i == 0) {
     valor = '/' + valor;
    } else if (i == valor.length) {
     valor = valor + '/';
    } else {
     valor = valor.substring(0, i) + '/' + valor.substring(i);
    }
    indiceBarra++;
   }
  }

  if (i == posHifen[indiceHifen]) {
   if (valor.charAt(i) != '-') {
    if (i == 0) {
     valor = '-' + valor;
    } else if (i == valor.length) {
     valor = valor + '-';
    } else {
     valor = valor.substring(0, i) + '-' + valor.substring(i);
    }
    indiceHifen++;
   }
  }

  if (i == posDblPonto[indiceDblPonto]) {
   if (valor.charAt(i) != ':') {
    if (i == 0) {
     valor = ':' + valor;
    } else if (i == valor.length) {
     valor = valor + ':';
    } else {
     valor = valor.substring(0, i) + ':' + valor.substring(i);
    }
    indiceDblPonto++;
   }
  }

  if (i == posAbrePar[indiceAbrePar]) {
   if (valor.charAt(i) != '(') {
    if (i == 0) {
     valor = '(' + valor;
    } else if (i == valor.length) {
     valor = valor + '(';
    } else {
     valor = valor.substring(0, i) + '(' + valor.substring(i);
    }
    indiceAbrePar++;
   }
  }

  if (i == posFechaPar[indiceFechaPar]) {
   if (valor.charAt(i) != ')') {
    if (i == 0) {
     valor = ')' + valor;
    } else if (i == valor.length) {
     valor = valor + ')';
    } else {
     valor = valor.substring(0, i) + ')' + valor.substring(i);
    }
    indiceFechaPar++;
   }
  }

  if (i == posVirgula[indiceVirgula]) {
   if (valor.charAt(i) != ',') {
    if (i == 0) {
     valor = ',' + valor;
    } else if (i == valor.length) {
     valor = valor + ',';
    } else {
     valor = valor.substring(0, i) + ',' + valor.substring(i);
    }
    indiceVirgula++;
   }
  }
 }

 if (campo.value.length > tamanho) {
  campo.value = campo.value.substring(0, tamanho);
 }

 campo.value = valor;
}