			var Ajax = false;
			
			function AjaxRequest() {
		        Ajax = false;
		        if (window.XMLHttpRequest) { // Mozilla, Safari,...
		            Ajax = new XMLHttpRequest();
		        } else if (window.ActiveXObject) { // IE
		            try {
		                Ajax = new ActiveXObject("Msxml2.XMLHTTP");
		            } catch (e) {
		                try {
		                    Ajax = new ActiveXObject("Microsoft.XMLHTTP");
		                } catch (e) {}
		            }
		        }		
			}
			
					//FUNCAO PARA PEGAR OS ELEMENTOS DO FORM
				function BuscaElementosForm(idForm) {
					var elementosFormulario = document.getElementById(idForm).elements;
					var qtdElementos = elementosFormulario.length;
					var queryString = "";
					var elemento;
				
					//Cria uma funcao interna para concatenar os elementos do form
					this.ConcatenaElemento = function(nome,valor) {
												if (queryString.length>0) {
													queryString += "&";
												}
												queryString += encodeURIComponent(nome) + "=" + encodeURIComponent(valor);
											 };
				
					//Loop para percorrer todos os elementos
					for (var i=0; i<qtdElementos; i++) {
						//Pega o elemento
						elemento = elementosFormulario[i];
						if (!elemento.disabled) {
							//Trabalha com o elemento caso ele nao esteja desabilitado
							switch(elemento.type) {
								//Realiza a acao dependendo do tipo de elemento
								case "text": case "password": case "hidden": case "textarea":
									this.ConcatenaElemento(elemento.name,elemento.value);
									break;
								case "select-one":
									if (elemento.selectedIndex>=0) {
										this.ConcatenaElemento(elemento.name,elemento.options[elemento.selectedIndex].value);
									}
									break;
								case "select-multiple":
									 for (var j=0; j<elemento.options.length; j++) {
										if (elemento.options[j].selected) {
											this.ConcatenaElemento(elemento.name,elemento.options[j].value);
										}
									}
									break;
								case "checkbox": case "radio":
									if (elemento.checked) {
										this.ConcatenaElemento(elemento.name,elemento.value);
									}
									break;
							}
						}
					}
					return queryString;
				}
				
		
			function retorna(idForm,target,valida,target_valida) {
				
					var url = document.getElementById(idForm).action;
					var lista = BuscaElementosForm(idForm);
					
					
					
					if(valida!=""){
						var str = valida.split(",");
						for(var i = 0; i < str.length; i++) {
							if(document.getElementById(str[i]).value <= 0){
								if(target_valida!=""){
									document.getElementById(target_valida).innerHTML = "Campo "+str[i].toUpperCase()+" Obrigatorio";
								}else{
									alert("Campo "+str[i].toUpperCase()+" Obrigatorio");	
								}
									return;	
							}
						}
					}

					
					
				AjaxRequest();
				if(!Ajax) {
					document.getElementById(target).innerHTML ="[Erro]";
				
				}
        		Ajax.onreadystatechange = function () {
					
				if (Ajax.readyState != 4) {
				document.getElementById(target).innerHTML = 	"Carregando...!";	
				}
				if (Ajax.readyState == 4) {
            		if (Ajax.status == 200) {
							//texto=unescape(Ajax.responseText.replace(/\+/g," "));
            				//document.getElementById("status").innerHTML=texto;
							
							document.getElementById(target).innerHTML = Ajax.responseText;
							
            		} else {
                		document.getElementById(target).innerHTML = 	"[Erro]";
            		}
        		}
				
				}
				
				
				Ajax.open("POST",url,true);	
				//Send the proper header information along with the request
				Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				Ajax.setRequestHeader("Content-length", lista.length);
				Ajax.setRequestHeader("Connection", "close");


        		Ajax.send(lista);
    		}
//////////////Gera combo

   function GeraCombo(valor,pagina,campo,id) {
	  //se tiver suporte ajax
	  AjaxRequest();
	  if(Ajax) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 document.getElementById(campo).options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
		 
	     Ajax.open("POST",pagina,true);
		 Ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 Ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(Ajax.readyState == 1) {
			   idOpcao.innerHTML = "Carregando...!";   
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(Ajax.readyState == 4 ) {
			   if(Ajax.responseXML) {
				  idOpcao.innerHTML = "Selecione!";
			      processXML(Ajax.responseXML,campo,id);
			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				 document.getElementById("valida").innerHTML = Ajax.responseText;
				  alert( Ajax.responseXML);
			   }
            }
         }
		//passa o código do estado escolhido
	     var params = "intId="+valor;
         Ajax.send(params);
      }
   }
   
   function processXML(obj,campo,id){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("dados");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length ; i++) {
            var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			
	        //idOpcao.innerHTML = "--Selecione--";
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = descricao;
				//finalmente adiciona o novo elemento
				document.getElementById(campo).options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "--Primeiro selecione o campo acima--";
	  }	  
   }
   
     function extraiScript(texto){
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf("<script", ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf(">", ini) + 1;
            // procura o final do script
            var fim = texto.indexOf("</script>", ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            eval(codigo);
        }
    }
}

function Aleatorio(){ aleat = Math.random() * 5000; aleat = Math.round(aleat); return aleat;}

///////////////////////////

			function retorna_excluir(url,target,elem) {
				
		        if(confirm("Deseja excluir: "+elem+"")){
					
				
				AjaxRequest();
				if(!Ajax) {
					document.getElementById(target).innerHTML ="[Erro]";
					return;
				}
        		Ajax.onreadystatechange = function () {
					
				if (Ajax.readyState != 4) {
				document.getElementById(target).innerHTML = 	"Carregando...!";	
				}
				if (Ajax.readyState == 4) {
            		if (Ajax.status == 200) {
							// coloca o valor no objeto requisitado
							texto=unescape(Ajax.responseText.replace(/\+/g," "));
							document.getElementById(target).innerHTML=texto;
							// executa scripts
							extraiScript(texto);
							
            		} else {
                		document.getElementById(target).innerHTML = 	Ajax.responseText;
            		}
        		}
				
				}
					;
				
				if(url.indexOf("?")== -1)
					var operador = "?";
				else
					var operador = "&";
					
        		Ajax.open("GET",url+operador+"rand="+Aleatorio(),true);
        		Ajax.send(null);
				
				}else{
					return;
								
			}
    }

			function retorna_menu(url,target) {
				
		
				AjaxRequest();
				if(!Ajax) {
					document.getElementById(target).innerHTML ="[Erro]";
					return;
				}
        		Ajax.onreadystatechange = function () {
					
				if (Ajax.readyState != 4) {
				document.getElementById(target).innerHTML = 	"Carregando...!";	
				}
				if (Ajax.readyState == 4) {
            		if (Ajax.status == 200) {
							// coloca o valor no objeto requisitado
							texto=unescape(Ajax.responseText.replace(/\+/g," "));
							document.getElementById(target).innerHTML=texto;
							// executa scripts
							extraiScript(texto);
							
            		} else {
                		document.getElementById(target).innerHTML = 	"[Erro]";
            		}
        		}
				
				}
					;
				
				if(url.indexOf("?")== -1)
					var operador = "?";
				else
					var operador = "&";
					
        		Ajax.open("GET",url+operador+"rand="+Aleatorio(),true);
        		Ajax.send(null);
    		}

//MÁSCARA DE VALORES
function moeda(z){  
    v = z.value;
    v=v.replace(/\D/g,"")  //permite digitar apenas números
    v=v.replace(/[0-9]{12}/,"inválido")   //limita pra máximo 999.999.999,99
    v=v.replace(/(\d{1})(\d{8})$/,"$1.$2")  //coloca ponto antes dos últimos 8 digitos
    v=v.replace(/(\d{1})(\d{5})$/,"$1.$2")  //coloca ponto antes dos últimos 5 digitos
    v=v.replace(/(\d{1})(\d{1,2})$/,"$1,$2")    //coloca virgula antes dos últimos 2 digitos
        z.value = v;
}		

function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); }
      else { // qualquer caracter...
        return true;
      }
    }
    else {
      return true;
    }
  }
function excluir_imagem(url,target,obj) {
				
		
				AjaxRequest();
				if(!Ajax) {
					document.getElementById(target).innerHTML ="[Erro]";
					return;
				}
        		Ajax.onreadystatechange = function () {
					
				if (Ajax.readyState != 4) {
				document.getElementById(target).innerHTML = 	"Carregando...!";	
				}
				if (Ajax.readyState == 4) {
            		if (Ajax.status == 200) {
						    
							
							document.getElementById(target).innerHTML="";
							document.getElementById(obj).value = "";
							var nr = parseInt(document.getElementById("nr").innerHTML) - 1;
							document.getElementById("nr").innerHTML = nr;
							var cont = document.getElementById("cont").innerHTML;
							
							if (document.getElementById("nr").innerHTML < document.getElementById("cont").innerHTML){
								document.getElementById("image").disabled = false;
								document.getElementById("submit").disabled = false;
							}
							
            		} else {
                		document.getElementById(target).innerHTML = 	 Ajax.responseText;
            		}
        		}
				
				}
					;
				
				
				if(url.indexOf("?")== -1)
					var operador = "?";
				else
					var operador = "&";
					
        		Ajax.open("GET",url+operador+"rand="+Aleatorio(),true);
        		Ajax.send(null);
}
function conta_imagem(){
	
  if (document.getElementById("nr").innerHTML == document.getElementById("cont").innerHTML){
		document.getElementById("image").disabled = true;
		document.getElementById("submit").disabled = true;
	} 
}

function startCallback() {
            // make something useful before submit (onStart)
            return true;
        }

        function completeCallback(response) {
            // make something useful after (onComplete)
			var nr = parseInt(document.getElementById('nr').innerHTML);
            
			var cont = document.getElementById('cont').innerHTML;
			
			
            for(var i=1;i<=cont;i++){
				if (document.getElementById('imagem'+i).value == '' ) {
					var quebra=response.split('/');
					document.getElementById('imagem'+i).value = quebra[1];
					document.getElementById('nr').innerHTML =nr+1;
					var bt_excluir = "<a href=\"javascript:excluir_imagem('x_excluir_imagem.php?pasta="+quebra[0]+"&imagem="+quebra[1]+"','exibe_imagem"+i+"','imagem"+i+"')\"> Excluir</a>";
					document.getElementById('exibe_imagem'+i).innerHTML="<img src='../arquivos/"+response+"' width='100'/>"+bt_excluir;
					if (document.getElementById('nr').innerHTML == document.getElementById('cont').innerHTML){
						document.getElementById('image').disabled = true;
						document.getElementById('submit').disabled = true;
					}	
					return;
				}
				
				}
        }


AIM = {

    frame : function(c) {

        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');


d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }

        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },

    submit : function(f, c) {
        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart();
        } else {
            return true;
        }
    },

    loaded : function(id) {
        var i = document.getElementById(id);
        if (i.contentDocument) {
            var d = i.contentDocument;
        } else if (i.contentWindow) {
            var d = i.contentWindow.document;
        } else {
            var d = window.frames[id].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }

        if (typeof(i.onComplete) == 'function') {
            i.onComplete(d.body.innerHTML);
        }
    }

}

function VerificaSoCPF(pForm, pCampo)
{
   var wVr, wTam, wSoma, wSoma2, i, j, wDig1, wDig2,
   wVETOR_CC = new Array(9),
   wVETOR_PESO = new Array(9);

   for (i=0; i < pForm.elements.lenght; i++)
   {
      if (pForm.elements[i].name == pCampo)
      {
          pCampo = i;
          i = pForm.elements.lenght;
      }
   }
   wVr = pForm[pCampo].value;
   wVr = wVr.replace( ".", "" );
   wVr = wVr.replace( ".", "" );
   wVr = wVr.replace( "-", "" );
   wTam = wVr.length + 1;

   if (wVr == '')
   {
      return false;
   }
   if (wTam < 11)
   {
      alert("Atenção: Nº de dígitos do CPF menor que o normal.");
      pForm[pCampo].value = "";
      pForm[pCampo].focus();
      return false;
   }

   for (i = 0; i < wVr.length; i++)
   {
      if (isNaN(parseInt(wVr.charAt(i))) )
      {
         alert("Atenção: O CPF contém dígitos inválidos.");
         pForm[pCampo].value = "";
         pForm[pCampo].focus();
         return false;
      }
   }

   if (wVr == '00000000000' || wVr == '11111111111' || wVr == '22222222222' || wVr == '33333333333' || wVr == '44444444444' || wVr == '55555555555' ||
       wVr == '66666666666' || wVr == '77777777777' || wVr == '88888888888' || wVr == '99999999999')
   {
      alert("Atenção: Este Tipo de CPF é inválido");
      pForm[pCampo].value = "";
      pForm[pCampo].focus();
      return false;
   }
   wSoma = 0;
   wSoma2 = 0;
   j = 2;
   for (i = 0; i < 11; i++)
   {
      wVETOR_CC[i] = wVr.charAt(i);
      wVETOR_PESO[i] = j;
      j++;
   }
   i = 0;
   while (i < 9)
   {
     i++;
     if (i < 10)
     {
        wSoma += wVETOR_CC[9 - i] * wVETOR_PESO[i - 1];
     }
        wSoma2 += wVETOR_CC[10 - i] * wVETOR_PESO[i - 1];
   }
   wDig1 = (wSoma * 10) % 11;
   wDig2 = (wSoma2 * 10) % 11;
   if (wDig1 == 10)
   {
      wDig1 = 0;
   }
   if (wDig2 == 10)
   {
      wDig2 = 0;
   }
   if (parseInt(wVr.charAt(9)) != wDig1 || parseInt(wVr.charAt(10)) != wDig2)
   {
      alert("Atenção: CPF com Dígito verificador é inválido.");
      pForm[pCampo].value = "";
      pForm[pCampo].focus();
      return false;
   }
    return true;
}function VerificaEmail(pform, pcampo)
{
   for (i=0; i < pform.elements.lenght; i++)
   {
      if (pform.elements[i].name == pcampo)
      {
          pcampo = i;
          i = pform.elements.lenght;
      }
   }

   parametro = pform[pcampo].value;
   teste_parametro = "false";
   tamanho_parametro = parametro.length;
   aposicao = 0; //posicao @
   pposicao = 0; //poiscao ponto
   narrobas = 0; // numero de @
   for (i = 0; i < tamanho_parametro; i++)
   {
      if (parametro.charAt(i) == "@")
      {
         narrobas = narrobas + 1
	 aposicao = i;
      }
      if (parametro.charAt(i) == ".")
      {
	 pposicao = i;
      }
   }
   if (aposicao > 0 && aposicao+1 < pposicao && narrobas<2)
   {
      teste_parametro = "true";
   }

   for (i = 0; i < tamanho_parametro; i++)
   {
      if (parametro.charAt(i) == " ")
      {
         teste_parametro = "false";
      }
   }

   if (tamanho_parametro < 5)
   {
       teste_parametro = "false"; /*tamanho minimo*/
   }


   if (parametro.charAt(0) == " " || parametro.charAt(1) == " ")
   {
      teste_parametro = "false";
   }

   if (teste_parametro == "false" && tamanho_parametro != 0 )
   {
       alert("Atenção: E-mail inválido!");
       pform[pcampo].focus();
       return false;
   }
   else
   {
       return true;
   }
}function FormataDadoCPF(pForm,pCampo,pTamMax,pPos1,pPos2,pPosTraco,pTeclaPres)
{
   var wTecla, wVr, wTam;

   wTecla = pTeclaPres.keyCode;
   for (i=0; i < pForm.elements.lenght; i++)
   {
      if (pForm.elements[i].name == pCampo)
      {
         pCampo = i;
         i = pForm.elements.lenght;
      }
   }
   wVr = pForm[pCampo].value;
   wVr = wVr.replace( "-", "" );
   wVr = wVr.replace( ".", "" );
   wVr = wVr.replace( ".", "" );
   wVr = wVr.replace( "/", "" );
   wTam = wVr.length ;
   if (wTam < pTamMax && wTecla != 8)
   {
      wTam = wVr.length + 1 ;
   }

   if (wTecla == 8 )
   {
      wTam = wTam - 1 ;
   }

   if ( wTecla == 8 || wTecla == 88 || wTecla >= 48 && wTecla <= 57 || wTecla >= 96 && wTecla <= 105 )
   {
      if ( wTam <= 2 )
      {
         pForm[pCampo].value = wVr ;
      }
      if (wTam > pPosTraco && wTam <= pTamMax)
      {
         wVr = wVr.substr(0, wTam - pPosTraco) + '-' + wVr.substr(wTam - pPosTraco, wTam);
      }
      if ( wTam == pTamMax)
      {
         wVr = wVr.substr( 0, wTam - pPos1 ) + '.' + wVr.substr(wTam - pPos1, 3) + '.' + wVr.substr(wTam - pPos2, wTam);
      }
      pForm[pCampo].value = wVr;

   }

}
function somente_numero(campo){  
var digits="0123456789"   
var campo_temp   
     for (var i=0;i<campo.value.length;i++){  
         campo_temp=campo.value.substring(i,i+1)   
         if (digits.indexOf(campo_temp)==-1){  
             campo.value = campo.value.substring(0,i);  
         }  
     }  
}  


function limita_numerico(e,virgula_ponto)
{
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;

    if (tecla > 47 && tecla < 58)  // numeros de 0 a 9
		return true;
	else
	{
	   if (virgula_ponto)
	   {
          if  ((tecla == 44) || (tecla == 46))
	         return true;
	   }

       if (tecla != 8) // backspace
       {
		//  event.keyCode = 0;
		  return false;
       }
	  else
		  return true;
	}
}function MM_formtCep(e,src,mask) {
    if(window.event) { _TXT = e.keyCode; }
    else if(e.which) { _TXT = e.which; }
    if(_TXT > 47 && _TXT < 58) {
 var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
 if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); }
    return true; } else { if (_TXT != 8) { return false; }
 else { return true; }
    }
} 
function dvCGC(pForm, pCampo)
{
   var Numero = pForm[pCampo].value.substr(0, 15);
   var Digito = pForm[pCampo].value.substr(16, 2);
   var CNPJ = pForm[pCampo].value

   for (i=0; i < pForm.elements.lenght; i++)
   {
      if (pForm.elements[i].name == pCampo)
      {
         pCampo = i;
         i = pForm.elements.lenght;
      }
   }

   Numero = Numero.replace(".","");
   Numero = Numero.replace(".","");
   Numero = Numero.replace("/","");
   Numero = Numero.replace("-","");

   CNPJ = CNPJ.replace(".","");
   CNPJ = CNPJ.replace(".","");
   CNPJ = CNPJ.replace("/","");
   CNPJ = CNPJ.replace("-","");

   var CGC = Numero;
   var peso1 = '543298765432';
   var peso2 = '654329876543';
   var soma1 = 0;
   var soma2 = 0;
   var digito1 = 0;
   var digito2 = 0;

   if (CNPJ == '00000000000000')
   {
      alert("CNPJ Inválido. Redigite!");
      pForm[pCampo].value = "";
      pForm[pCampo].focus();
      return false;
   }

   if ((Numero.length + Digito.length + 1 > 1) && (Numero.length + Digito.length + 1 < 15))
   {
      alert("Nº de dígitos do CNPJ menor que o normal. Redigite !!!");
      pForm[pCampo].value = "";
      pForm[pCampo].focus();
      return false;
   }

   if (Numero.length + Digito.length + 1 > 1)
   {
      for (i = 1; i < 12 - Numero.length + 1; i++)
      {
         CGC = eval("'" + 0 + CGC + "'")
      }

      for (i = 1; i < CGC.length+1; i++)
      {
         soma1 += CGC.substring(i, i-1) * peso1.substring(i, i-1);
      }

      soma1 %= 11;

      if (soma1  < 2)
      {
         digito1 = 0;
      }
      else
      {
         digito1 = 11 - soma1;
      }

      for (i = 1; i < CGC.length+1; i++)
      {
         soma2 += CGC.substring(i, i-1) * peso2.substring(i, i-1);
      }

      soma2 += digito1 * 2
      soma2 %= 11;

      if (soma2  < 2)
      {
         digito2 = 0;
      }
      else
      {
         digito2 = 11 - soma2;
      }

      if (eval("'" + digito1 + digito2 + "'") != Digito)
      {
          alert("CNPJ inválido. Redigite !!!");
	  pForm[pCampo].value = "";
	  pForm[pCampo].focus();
	  return false;
      }
      else
      {
	  return true;
      }
   }
}//////////////////////////
function FormataDadoCGC(pForm,pCampo,pTeclaPres)
{
   var wTecla, wVr, wTam;

   wTecla = pTeclaPres.keyCode;
   
    if (pTeclaPres.keyCode < 45 || pTeclaPres.keyCode > 57) return true;
	
   for (i=0; i < pForm.elements.lenght; i++)
   {
      if (pForm.elements[i].name == pCampo)
      {
         pCampo = i;
         i = pForm.elements.lenght;
      }
   }
   wVr = pForm[pCampo].value;
   wVr = wVr.replace( "-", "" );
   wVr = wVr.replace( ".", "" );
   wVr = wVr.replace( ".", "" );
   wVr = wVr.replace( "/", "" );
   wTam = wVr.length ;

   if (wTam < 14 && wTecla != 8)
   {
      wTam = wVr.length + 1 ;
   }

   if (wTecla == 8 )
   {
      wTam = wTam - 1 ;
   }

   if ( wTecla == 8 || wTecla == 88 || wTecla >= 48 && wTecla <= 57 || wTecla >= 96 && wTecla <= 105 )
   {
      if ( wTam <= 2 )
      {
         pForm[pCampo].value = wVr ;
      }
      if (wTam > 2 && wTam <= 14)
      {
         wVr = wVr.substr(0, wTam - 2) + '-' + wVr.substr(wTam - 2, wTam);
      }

      if ( wTam == 14)
      {
         wVr = wVr.substr( 0, wTam - 12 ) + '.' + wVr.substr(wTam - 12, 3) + '.' + wVr.substr(wTam - 9, 3) + "/" + wVr.substr(wTam - 6, wTam);
      }
      pForm[pCampo].value = wVr;

   }
}
function horizontal() {
 
   var navItems = document.getElementById("menu_dropdown").getElementsByTagName("li");
    
   for (var i=0; i< navItems.length; i++) {
      if(navItems[i].className == "submenu")
      {
         if(navItems[i].getElementsByTagName("ul")[0] != null)
         {
            navItems[i].onmouseover=function() {this.getElementsByTagName("ul")[0].style.display="block";this.style.backgroundColor = "#f9f9f9";}
            navItems[i].onmouseout=function() {this.getElementsByTagName("ul")[0].style.display="none";this.style.backgroundColor = "#FFFFFF";}
         }
      }
   }
 
}

var Password = function() {
	this.pass = "";

	this.generate = function(chars) {
		for (var i= 0; i<chars; i++) {
			this.pass += this.getRandomChar();
		}
		return this.pass;
	}

	this.getRandomChar = function() {
		/* 
		*	matriz contendo em cada linha indices (inicial e final) da tabela ASCII para retornar alguns caracteres.
		*	[48, 57] = numeros;
		*	[64, 90] = "@" mais letras maiusculas;
		*	[97, 122] = letras minusculas;
		*/
		var ascii = [[48, 57],[64,90],[97,122]];
		var i = Math.floor(Math.random()*ascii.length);
		return String.fromCharCode(Math.floor(Math.random()*(ascii[i][1]-ascii[i][0]))+ascii[i][0]);
	}
}

function showPass(alvo, pass) {
	document.getElementById(alvo).value = pass;
}

function newPass() {
	var pwd = new Password();
	showPass("senha", pwd.generate(6));
}

var atual=1; //esta var guarda o valor que tá sendo exibido agora.
var timeloop; //guardará o setInterval

function muda(qual){
    /*** função que altera a div que é exibida ***/
    //divs que estão dentro do destaques colocadas num array
    var divs = document.getElementById("destaques").getElementsByTagName("div");
    //formatando o qual
    var qual_num = Number(qual);
    if (qual_num<1){ qual_num = divs.length;}
    else if (qual_num>divs.length) { qual_num = 1;}
    //colocando o zero antes se for necessário
    if (qual_num<10) {qual = "0" + qual_num} else { qual = qual_num };
    //voltando a classe de todas para o padrão que é vazio (resetando)
    for (var i=0;i<divs.length;i++){ divs[ i ].className = "";}
    //aplicando a classe exibe na que for pra exibir
    document.getElementById("dest_"+qual).className = "exibe";
    atual = qual_num; //setando o atual
}

function iniciaAutomatico(){
    timeloop = setInterval("muda(Number(atual)+1)",5000);
}

function altera_busca(opcao,on,off,url){
		
	document.getElementById('opcao_label').innerHTML = opcao;
	document.getElementById('opcao').value = opcao;
	document.getElementById(on).style.backgroundColor = '#0c83e3';
	document.getElementById(off).style.backgroundColor = '#192c91';
	document.getElementById('frmBusca').action = url;
		
	}
