$(document).ready(function(){
	//Sidebar Accordion Menu:
		
		$("#navegacaoPrincipal li ul").hide(); // Hide all sub menus
		$("#navegacaoPrincipal li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
		
		$("#navegacaoPrincipal li a.nav-top-item").click( // When a top menu item is clicked...
			function () {
				$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
				$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
				return false;
			}
		);
		
		$("#navegacaoPrincipal li a.no-submenu").click( // When a menu item with no sub menu is clicked...
			function () {
				window.location.href=(this.href); // Just open the link instead of a sub menu
				return false;
			}
		); 


    //Minimize Content Box
		
		$(".closed-box .content-box-content").hide(); // Hide the content of the header if it has the class "closed"
		$(".closed-box .content-box-tabs").hide(); // Hide the tabs in the header if it has the class "closed"
		
		$(".content-box-header h3").click( // When the h3 is clicked...
			function () {
			  $(this).parent().next().toggle(); // Toggle the Content Box
			  $(this).parent().parent().toggleClass("closed-box"); // Give the Content Box Header a special class for styling and hiding
			  $(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs
			}
		);

    //Close button:
		
		$(".fechar").click(
			function () {
				$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
					$(this).slideUp(600);
				});
				return false;
			}
		);




    // Alternating table rows:
		
		$('tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows

    // Check all checkboxes when the one in a table head is checked:
		
		$('.check-all').click(
			function(){
				$(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));   
			}
		)
});

var tempo = new Date();
inicio = tempo.getTime();	 
dec = 0;
function removeMensagemRetorno(){
   	var ntempo = new Date();
    var agora = ntempo.getTime();
   	var decorrido = (agora - inicio) / 1000 ;	
//    document.getElementById('msg').innerHTML = dec;
	var interv = setTimeout('removeMensagemRetorno()',500);
	if(dec > 5){
		clearTimeout(interv);
		document.getElementById('mensagem').innerHTML = '';
		document.getElementById('mensagem').className = '';
	}else{
		dec++;
	}
}

// JavaScript Document
function DadosCEP(valor) {	
//	alert("TEste "+ valor);
	//verifica se o browser tem suporte a ajax
	try {
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch(e) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(ex) {
			try {
				ajax = new XMLHttpRequest();
			}
			catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				ajax = null;
			}
		}
	}
	
	//se tiver suporte ajax
	if(ajax) {
		//deixa apenas o elemento 1 no option, os outros são excluídos
		//document.forms[0].listCidades.options.length = 1;
		
		carregando  = document.getElementById("aguarde");
		//carregando.innerHTML = "<img src='img/progress.gif'>";
		
		ajax.open("POST", "buscaCep.php", 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) {
				carregando.innerHTML = "<img src='imagens/carregando.gif'>";
			}
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
				if(ajax.responseXML) {
					processXML(ajax.responseXML);
				}
			}
         }
		 //passa o código do estado escolhido
		 var params = "cep="+valor;
//		 alert("TESTE: "+params);
		 ajax.send(params);
	}
}
   
   function processXML(obj){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("dadoscep");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
		 if(dataArray.length > 0){
        	 for(var i = 0 ; i < dataArray.length ; i++) {
    	        var item = dataArray[i];
				//contéudo dos campos no arquivo XML			
				var tipo_logradouro	=  item.getElementsByTagName("tipo_logradouro")[0].firstChild.nodeValue;
				var logradouro 		=  item.getElementsByTagName("logradouro")[0].firstChild.nodeValue;
				var bairro 			=  item.getElementsByTagName("bairro")[0].firstChild.nodeValue;
				var cidade 			=  item.getElementsByTagName("cidade")[0].firstChild.nodeValue;
				var uf 				=  item.getElementsByTagName("uf")[0].firstChild.nodeValue;
		 	}
			carregando.innerHTML = "";
			document.getElementById("endereco").value = tipo_logradouro+" "+logradouro;
			document.getElementById("numero").focus();
			document.getElementById("bairro").value = bairro;
			document.getElementById("cidade").value = cidade;
			document.getElementById("estado").value = uf;
		 }
	}else{
		carregando.innerHTML = "Informe os Dados Manualmente.";
	}	  
}
