// JavaScript Document

<!-- remover acentos -->
function retira_acentos(palavra) {
com_acento = 'áaaâäéeeëíiîióooôöúuuüçÁAAÂÄÉEEËÍIÎIÓOOÖÔÚUUÜÇ';
sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
nova='';
for(i=0;i<palavra.length;i++) {
if (com_acento.search(palavra.substr(i,1))>=0) {
nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);
}
else {
nova+=palavra.substr(i,1);
}
}
return nova;
}
<!--/ remover acentos -->

<!-- tratar url -->
function tratar_url(url){
var out = "", flag = 0;
url = url.replace(/&/g, "" );
url = url.replace(/'/g, "" );
//utilizo a funcao pra remover acentos
url=retira_acentos(url);
	for (i = 0; i < url.length; i++) {
		if (url.charAt(i) != " ") {
		out += url.charAt(i);
		flag = 0;
		}
		else {
			if(flag == 0) {
			out += "-";
			flag = 1;
        	}
   		}
   }
 out=out.toLowerCase(out);
 out='http://www.dominio.com.br/'+out+'.php';
 return out;
}
<!-- / tratar url -->

<!-- redirecionar pagina -->
function redireciona(pagina){
	var url;
	url = tratar_url(pagina)
	document.location.href=url;
};
<!-- / redirecionar pagina -->
<!-- EXIBIR -->
function exibe(mostrar){
    if(document.getElementById(mostrar).style.display == "none" ) {
       document.getElementById(mostrar).style.display = "block";
    }else{
        document.getElementById(mostrar).style.display = "block";
    }
};
<!-- /EXIBIR -->
<!-- OCULTAR -->
function oculta(ocultar){
    if(document.getElementById(ocultar).style.display == "block" ) {
       document.getElementById(ocultar).style.display = "none";
    }else{
        document.getElementById(ocultar).style.display = "none";
    }
};
<!-- /OCULTAR -->
<!-- MOSTRAR ORÇAMENTO -->
function mostrar_ocultar(nomeDiv) {
    if( document.getElementById(nomeDiv).style.display == "none" ) {
        document.getElementById(nomeDiv).style.display = "block";
    } else {
        document.getElementById(nomeDiv).style.display = "none";
    }
}
<!-- /MOSTRAR ORÇAMENTO -->

// colocar no evento onKeyUp passando o objeto como parametro
function FormataData(val)
{
   	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;				
 				  continue;			
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
				 	var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;			
				}
		
				if	((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
   		  }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>10)
		val.value = val.value.substring(0, 10);
	 	return true;
}//fim da função de formatação de data

//Função de validação de data

function validaData(str) { 

	dia = (str.value.substring(0,2)); 
    mes = (str.value.substring(3,5)); 
	ano = (str.value.substring(6,10)); 

	cons = true; 
	
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
		alert("Preencha a data somente com números."); 
		str.value = "";
		str.focus(); 
		return false;
	}
		
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31) { 
    	cons = false; 
	} 

	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
    
	if (cons == false) { 
		alert("A data inserida não é válida: " + str.value); 
		str.value = "";
		str.focus(); 
		return false;
	} 
}//fim da função de validação de data

//função para exibir e ocultar div

function mostrar(nomeDiv) {
    if( document.getElementById(nomeDiv).style.display == "none" ) {
        document.getElementById(nomeDiv).style.display = "block";
    } else {
        document.getElementById(nomeDiv).style.display = "none";
    }
}// fim da função que exibe e oculta div

function ocultar(nomeDiv) {
 document.getElementById(nomeDiv).style.display = "none";
   
}// fim da função que exibe e oculta div


//FUNÇÃO PARA CRIAR MASCARA
function mascara(src, mask) 
{
  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);
  }
}

// FIM DA FUNÇÃO DE MASCARA


//FUNÇÃO AJAX PARA VERIFICAR SE O NAVEGADOR TEM SUPORTE
// Função responsável de conectar a uma página externa e retornar os resultados
function ajax(url){
req = null;
// Procura por um objeto nativo (Mozilla/Safari)
if (window.XMLHttpRequest){
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET",url,true);
req.send(null);
}
// Procura por uma versão ActiveX (IE)
else if (window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req){
req.onreadystatechange = processReqChange;
req.open("GET",url,true);
req.send();
}
}
}
// FECHA FUNÇÃO DE VERIFICAÇÃO AJAX

//FUNÇÃO QUE FAZ A REQUISIÇÃO  E FUNÇÃO DE PESQUISA
function processReqChange(){
// apenas quando o estado for "completado"
if (req.readyState == 4)
{
// apenas se o servidor retornar "OK"
if (req.status ==200)
{
// procura pela div id="pagina" e insere o conteudo
// retornado nela, como texto HTML
document.getElementById('pagina').innerHTML = req.responseText;
}
else
{
alert("Houve um problema ao obter os dados:n" + req.statusText);
}
}
}
//FECHA FUNÇÃO DE REQUISIÇÃO
//ABRE FUNÇÃO DE PESQUISA
function pesquisa(valor)
{
//Função que monta a URL e chama a função AJAX
url="busca_nome.php?valor="+valor;
ajax(url);
}
//FECHA FUNÇÃO DE PESQUISA
//ABRE FUNÇÃO DE PESQUISA
function checa_duplicidade(valor){
//Função que monta a URL e chama a função AJAX
url="checar_duplicidade.php?valor="+valor;
ajax(url);
}
//FECHA FUNÇÃO DE PESQUISA

//FECHA FUNÇÃO QUE FAZ A PESQUISA

//FUNÇÃO USAR ENTER COMO TAB

function passaCampo(e){
	if (e.keyCode == 13){
    e.keyCode=9
    //proximoCampo.focus()
    }
}		
//FIM FUNÇÃO ENTER
//FUNÇÃO PARA MUDAR DE CAMPO QUANDO ATINGIR UM NUMERO X DE DIGITOS
// FUNÇÃO MUDACAMPO
function mudaCampo(campo,tamanho,proximo){
if(campo.value.length==tamanho){
	proximo.focus();
}
}
// FIM FUNÇÃO MUDACAMPO
//INICIO FUNÇÃO MOEDA
function moeda(z){
	v = z.value;
	var tamanho;
	var pontuacao;
	
	tamanho = v.length;
	pontuacao= v.charAt(tamanho - 3);
	
	//verifica se o 3 caracter é um . ou ,
	if(pontuacao!= "," && pontuacao !="." ){
         
		 v=z.value+",00";
		 
		 z.value = v ;
		} else {
			if(pontuacao=="."){
				v=v.replace(".",",");
				z.value = v ;
				}else{
				z.value = v ;
				}
		
		}
		
    }
//FIM DA FUNÇÃO MOEDA
// INICIO FUNÇÃO DE MASCARA MAIUSCULA
function maiuscula(z){
        v = z.value.toUpperCase();
        z.value = v;
    }
//FIM DA FUNÇÃO MASCARA MAIUSCULA

// FUNÇÃO PARA DAR FOCO EM UM CAMPO //
function foco(campo){
	document.getElementById('campo').focus();
	}
//FIM FUNÇÃO FOCO //


//FUNÇÃO PARA PEGAR CEP
// Função única que fará a transação
function getEndereco() {
// Se o campo CEP não estiver vazio
if($.trim($("#cep").val()) != ""){
/* 
Para conectar no serviço e executar o json, precisamos usar a função
getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain,
os outros dataTypes não possibilitam esta interação entre domínios diferentes
Estou chamando a url do serviço passando o parâmetro "formato=javascript"
e o CEP digitado no formulário					http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val()
*/
	$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), 	function(){
	// o getScript dá um eval no script, então é só ler!
	//Se o resultado for igual a 1
	if(resultadoCEP["resultado"]){
	// troca o valor dos elementos
	$("#endereco").val(unescape(resultadoCEP["tipo_logradouro"])+" "+unescape(resultadoCEP["logradouro"]));
	$("#bairro").val(unescape(resultadoCEP["bairro"]));
	$("#cidade").val(unescape(resultadoCEP["cidade"]));
	$("#uf").val(unescape(resultadoCEP["uf"]));
	}else{
	//alert("Endereço não encontrado");
	$("#endereco").val("Endereço não encontrado");
	}
	});				
}			
}

//FIM DA FUNÇÃO PEGAR CEP

//FUNÇÃO AJAX PARA VERIFICAR SE O NAVEGADOR TEM SUPORTE
// Função responsável de conectar a uma página externa e retornar os resultados
function ajax1(url,div){
req = null;
// Procura por um objeto nativo (Mozilla/Safari)
	if (window.XMLHttpRequest){
	req = new XMLHttpRequest();
	req.onreadystatechange = processaReqChange;
	req.open("GET",url,true);
	req.send(null);
	}
	// Procura por uma versão ActiveX (IE)
	else if (window.ActiveXObject){
	req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req){
		req.onreadystatechange = processaReqChange;
		req.open("GET",url,true);
		req.send();
		}
	}
}
// FECHA FUNÇÃO DE VERIFICAÇÃO AJAX
//FUNÇÃO QUE FAZ A REQUISIÇÃO  E FUNÇÃO DE PESQUISA
function processaReqChange(div){
	// apenas quando o estado for "completado"
	if (req.readyState == 4){
	// apenas se o servidor retornar "OK"
		if (req.status ==200){
			// procura pela div id="pagina" e insere o conteudo
			// retornado nela, como texto HTML
			document.getElementById('resultado-pesquisa').innerHTML = req.responseText;
		}
		else{
			alert("Houve um problema ao obter os dados:n" + req.statusText);
		}
	}
}
//FECHA FUNÇÃO DE REQUISIÇÃO
//ABRE FUNÇÃO DE PESQUISA
function pes_contatos(valor){
//Função que monta a URL e chama a função AJAX
url="pes_contatos.php?valor="+valor;
div="resultado-pesquisa";
ajax1(url,div);
}
//FECHA FUNÇÃO DE PESQUISA

//FUNÇÃO PARA RETIRAR ACENTOS ///
function retirarAcento(objResp) {
var varString = new String(objResp.value);
var stringAcentos = new String('àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ');
var stringSemAcento = new String('aaeouaoaeioucuAAEOUAOAEIOUCU');

var i = new Number();
var j = new Number();
var cString = new String();
var varRes = '';

for (i = 0; i < varString.length; i++) {
cString = varString.substring(i, i + 1);
for (j = 0; j < stringAcentos.length; j++) {
if (stringAcentos.substring(j, j + 1) == cString){
cString = stringSemAcento.substring(j, j + 1);
}
}
varRes += cString;
}
objResp.value = varRes;
}
/* esta função foi retirada de http://tedk.com.br/blog/index.php/category/javascript-ajax-dhtml/page/4/ s*/
//FIM FUNÇÃO RETIRAR ACENTOS ////

//FUNÇÃO PARA VERIFICAR SE O E-MAIL JÁ ESTÁ CADASTRADO
//EXTRAIDA DO ENDEREÇO
//http://www.oracle.com/technology/global/lad-pt/pub/articles/oracle_php_cookbook/ullman-ajax.html
function createRequestObject() {
    var ro;
    if (navigator.appName == "Microsoft Internet Explorer") {
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        ro = new XMLHttpRequest();
    }
    return ro;
}
var http = createRequestObject();

// Function that calls the PHP script:
// Função que chama o script PHP
// NOME ORIGINAL sendRequest
function ChecaEmail(email) {
	// Call the script.
	// Use the GET method.
	// Pass the email address in the URL.
	// Chama o script.
	// Use o método GET.
	// Passa o endereço de email na URL.
    http.open('get', 'checa-email.php?email=' + encodeURIComponent(email));
    http.onreadystatechange = handleResponse;
    http.send(null);
}

// Function handles the response from the PHP script.
//Função controla a resposta do script PHP
function handleResponse() {
	// If everything's okay:
	//Se está tudo bem
    if(http.readyState == 4){
    	// Assign the returned value to the document object.
		//Atribuir o valor retornado para o objeto de documento
        document.getElementById('email_label').innerHTML = http.responseText;
    }
}
//FIM FUNÇÃO CHECA EMAIL

