	var objDivUtilizando;
	var objDivUtilizada;	
	var objPai;
	function showList(busca,label){
		objDivUtilizando = busca+"Box"+label;
		objPai = busca+label;
		if(objDivUtilizada){
			if(objDivUtilizada == objDivUtilizando){
				if(document.getElementById(objDivUtilizando).style.display=="block"){
					document.getElementById(objDivUtilizando).style.display	= "none";
				}else{
					document.getElementById(objDivUtilizando).style.display	= "block";
				}
			}else{
				document.getElementById(objDivUtilizando).style.display="block";	
				document.getElementById(objDivUtilizada).style.display="none";
			}
		}else{
			document.getElementById(objDivUtilizando).style.display="block";
		}
		objDivUtilizada = objDivUtilizando;	
									
	}
	function selOption(option){
		novoId = document.getElementById(option).id;
		novoTxt = document.getElementById(option).title;
		document.getElementById(objPai).innerHTML=novoTxt;
		document.getElementById(objPai).title = novoTxt;
		document.getElementById(objDivUtilizando).style.display="none";
		
		//verifica se foi selecionada a opção de ordenação para os imóveis
		if(option=="orderMenorPreco" || option=="orderMaiorPreco" || option=="orderBairros"){
			if(option=="orderMenorPreco"){
				document.getElementById("ordem").value = 1;
			} else if(option=="orderMaiorPreco"){
				document.getElementById("ordem").value = 2;
			} else if(option=="orderBairros"){
				document.getElementById("ordem").value = 0;
			}
			
			//carrega a listagem
			buscar();
		}
		
	}
	
	
	var timeMnOut;
	function outdiv(id,obj){
		/*if(obj.nodeName.toUpperCase() != "DIV" && obj.nodeName.toUpperCase() != "UL" && obj.nodeName.toUpperCase() != "LI"){
			document.getElementById(id).style.display="none";
		}
		if(obj.id == "areaValor"){
			//alert(obj.id);
		}*/
		//timeMnOut = setTimeout(function (){clearTimeout(timeMnOut);document.getElementById(id).style.display="none"},2000);
		//document.getElementById(id).style.display="none";
	}
	
	var tipoImovelAnterior = "Residencial";
	function showImovel(tipo,valor){	
		if(valor == "3"|| valor == "4" || valor == "2"){
			//desabilita opções para grupo TERRENOS
			document.getElementById("item_dormitorios").style.display = "none";
			document.getElementById("item_suites").style.display = "none";
			if(valor != "2"){
				document.getElementById("item_vagas").style.display = "none";
			}else{
				document.getElementById("item_vagas").style.display = "";	
			}
		}else{
			if(document.getElementById("item_vagas") != null){
				document.getElementById("item_dormitorios").style.display = "";
				document.getElementById("item_suites").style.display = "";
				document.getElementById("item_vagas").style.display = "";	
			}
		}
		
		if(document.getElementById(objDivUtilizando) != null)
			document.getElementById(objDivUtilizando).style.display = "none";
		
		if(tipo != tipoImovelAnterior && tipoImovelAnterior){
			document.getElementById("bt"+tipoImovelAnterior).className = "";
			document.getElementById("seta"+tipoImovelAnterior).style.display = "none";	
		}
		document.getElementById("bt"+tipo).className = "ahover";
		document.getElementById("seta"+tipo).style.display = "block";
		tipoImovelAnterior = tipo;
		
		document.getElementById("grupo").value = valor;
		
		//atualiza / carrega campo Tipo
		//carregaTipos(valor);
	}
	
	function carregaTipos(valor) {
	  showImoveisDestaque(document.getElementById("finalidade").value);
	  carregaBannersDestaque(valor);
		
	  document.getElementById("ul_Subtipo").innerHTML = "";
	  document.getElementById("buscaAvancadaSubtipo").title = "Selecione o Tipo";
	  document.getElementById("buscaAvancadaSubtipo").innerHTML = "Selecione";
	  primeira_opcao_selecionada = "";
	  str_opcoes = "";
	  document.getElementById("tipo_cd").value = "";
	  
	  //remove a lista de subtipos
	  var objTipos = document.getElementById("ul_tipo");
	  objTipos.innerHTML = "";
	  
	  idOpcaoTipo = document.getElementById("buscaSimplesTipo");
	  
	  ajax5 = InicializaAjax();
	  //se tiver suporte ajax
	  if(ajax5) {
		 ajax5.open("POST", "../_includes/lista_tipos.php", true);
		 ajax5.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajax5.onreadystatechange = function() {
			//enquanto estiver processando...emite a msg de carregando
			if(ajax5.readyState == 1) {
			   idOpcaoTipo.innerHTML = "Carregando...";   
			}
			//após ser processado - mostra os tipos disponíveis
			if(ajax5.readyState == 4 ) {
			   idOpcaoTipo.innerHTML = "Selecione";
			   objTipos.innerHTML = ajax5.responseText;
			}
		 }
		 var params = "grupo="+valor;
		 ajax5.send(params);
	  }
	}
	
			
	function showTipoImovel(tipo){
		document.getElementById("bt"+tipo).className = "bt"+tipo;
		if(tipo == "Venda"){
			document.getElementById("btLocacao").className = "btLocacaohover";
			document.getElementById("finalidade").value = "2";
			
			//mostra valores de venda
			//document.getElementById("listaValorVenda").style.display="";
			
			//esconde os valores de locação
			//document.getElementById("listaValorLocacao").style.display="none";
			
		}
		if(tipo == "Locacao"){
			document.getElementById("btVenda").className = "btVendahover";
			document.getElementById("finalidade").value = "1";
			
			//mostra valores de locação
			//document.getElementById("listaValorLocacao").style.display="";
			
			//esconde os valores de venda
			//document.getElementById("listaValorVenda").style.display="none";
		}
	}
	
	function showHideLogos(objDiv){
		var div = "divInfo"+objDiv;
		if(document.getElementById(div).style.display=="block"){
			document.getElementById(div).style.display="none";
		}else{
			document.getElementById(div).style.display="block";
		}
	}




// equema para fazer a animacao do botao de adicionar a lista de mais imoveis

	function addImovelLista(id){
		var obj = document.getElementById("cod"+id);
		if(obj.className == 'btFavoritos'){
			obj.className = 'btFavoritosHover';
			obj.innerHTML = "Im&oacute;vel Adicionado";
		}else{
			obj.className = 'btFavoritos';
			obj.innerHTML = "<span class='destaque'>+</span> Meus im&oacute;veis";
		}
		
	}
	
//FUNCOES AJAX
	var ajax = null;
	var ajax1 = null;
	var ajax2 = null;
	var ajax3 = null;
	var ajax4 = null;
	var ajax5 = null;
	var idOpcaoTipo = null;
	var idOpcaoBairro = null;
	var idOpcaoSubTipo = null;
	function InicializaAjax(){
	  //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;
				}
			 }
		  }
	  return ajax;
	}
	
	
	function carregaBairros() {
	  primeira_opcao_selecionada = "";
	  str_opcoes = "";
	  document.getElementById("campos_bairro").innerHTML = "";
	  
	  //remove a lista de bairros
	  var objBairro = document.getElementById("ul_bairro")
	  objBairro.innerHTML = "";
	  
	  idOpcaoBairro = document.getElementById("buscaSimplesBairro");
	  
	  ajax1 = InicializaAjax();
	  //se tiver suporte ajax
	  if(ajax1) {
		 ajax1.open("POST", "../_includes/xml_bairro.php", true);
		 ajax1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajax1.onreadystatechange = function() {
			//enquanto estiver processando...emite a msg de carregando
			if(ajax1.readyState == 1) {
			   idOpcaoBairro.innerHTML = "Carregando...";   
			}
			//após ser processado - chama função processXMLBairros que vai varrer os dados
			if(ajax1.readyState == 4 ) {
			   if(ajax1.responseXML) {
				  processXMLBairros(ajax1.responseXML, objBairro);
			   }else{
				   //caso não seja um arquivo XML emite a mensagem abaixo
				   idOpcaoBairro.innerHTML = "";
			   }
			}
		 }
		 var params = "cidade="+novoId;
		 ajax1.send(params);
	  }
	}
	
	function processXMLBairros(objResponseXML, objBairro){
	  //pega a tag bairro
	  var dataArray   = objResponseXML.getElementsByTagName("bairro");
	  
	  //total de elementos contidos na tag bairro
	  if(dataArray.length > 0) {
		 //percorre o arquivo XML para extrair os dados
		 for(var i = 0 ; i < dataArray.length ; i++) {
			var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var nome    =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
			var nodeId    =  item.getElementsByTagName("nodeId")[0].firstChild.nodeValue;
			
			idOpcaoBairro.innerHTML = "Selecione";
			addNodes(objBairro,nome,"bairro",nodeId);
		 }
		 idOpcaoBairro.innerHTML = "Selecione";
		 idOpcaoBairro.title = "Selecione";
	  }else{
		//caso o XML volte vazio, printa a mensagem abaixo
		 idOpcaoBairro.innerHTML = "";
		 idOpcaoBairro.title = "Não há bairros cadastrados para a cidade selecionada";
		 
	  }	  
	}
	
	//funcao adiciona LI's no UL passado por parametro
	//Concebida inicialmente para carregar o menu com os bairro ou o menu com os subtipos 
	function addNodes(objUL,nome,preNodeId,nodeId){
		var objLI = document.createElement("li");
		var objCheckbox = createCheckboxField(preNodeId+nodeId, nome);
		var objHREF = createHREF(nome,preNodeId,nodeId)
		var objLabel = createLabel();
		objLabel.appendChild(objCheckbox)
		objLabel.innerHTML += " " + nome;
		objHREF.appendChild(objLabel);
		objLI.appendChild(objHREF);
		objUL.appendChild(objLI);
	}
	
	function createCheckboxField(nome,valor){
		var newInputCheckbox = document.createElement("input");
		newInputCheckbox.setAttribute("type", "checkbox");
		newInputCheckbox.setAttribute("name", nome);
		newInputCheckbox.setAttribute("id", nome);
		newInputCheckbox.setAttribute("value", valor);
		return newInputCheckbox;
	}
	
	function createHREF(nome,preNodeId,nodeId){
		var newHREF = document.createElement("a");
		newHREF.setAttribute("href", "#");
		newHREF.setAttribute("style", "cursor:text");
		var param_codigo = codigo;
		newHREF.onclick = function(){ carregaOpcaoSelecionada(preNodeId+nodeId,nome,preNodeId,param_codigo); };
		newHREF.setAttribute("id", nodeId);
		newHREF.setAttribute("title", nome);
		return newHREF;
	}
	
	function doSomething() {
		this.style.backgroundColor = '#cc0000';
	}

	
	function createLabel(){
		var newLabel = document.createElement("label");
		newLabel.setAttribute("style", "cursor:pointer");
		return newLabel;
	}
	
	function carregaHiddenBusca(campo,valor){
		if(campo == "cidade"){
			document.getElementById("localidade_cd").value = valor;
		}else if(campo == "tipo"){
			document.getElementById("tipo_cd").value = valor;
		}else if(campo == "valor"){
			document.getElementById("maximo").value = valor;
		}else if(campo == "dormitorios"){
			document.getElementById("dormitorios").value = valor;
		}else if(campo == "suites"){
			document.getElementById("suites").value = valor;
		}else if(campo == "vagas"){
			document.getElementById("vagas").value = valor;
		}else if(campo == "CNPJ"){
			document.getElementById("CNPJ").value = valor;
		}
		
	}
	
	var str_opcoes = "";
	//funcao que cria um hidden para cada bairro selecionado formando um array bairro_cd[]
	function carregaOpcaoSelecionada(nome,valor,preNodeId,param_codigo){
	
		var objDivCampos = document.getElementById("campos_"+preNodeId);
		var objCheck = document.getElementById(nome);
		var objHidden = document.getElementById("hdd_"+nome);
		
		if(objCheck.checked){
			if(objHidden == null){
				objDivCampos.appendChild(createHiddenField(nome,valor,preNodeId,param_codigo));
			}
		}else{
			if(objHidden != null){
				objHidden.parentNode.removeChild(objHidden);
			}
		}
		
		str_opcoes = pegaStringOpcoesSelecionadas(preNodeId,0);
		//carrega tooltip das opcoes selecionadas
		if(str_opcoes == ""){
			document.getElementById(objPai).title = "Selecione";
			document.getElementById(objPai).innerHTML = "Selecione";	
		}else{
			document.getElementById(objPai).title = str_opcoes;
			if(primeira_opcao_selecionada.length > 9){
				primeira_opcao_selecionada = primeira_opcao_selecionada.substring(0, 9);
			}
			if(str_opcoes.length > 9) primeira_opcao_selecionada += "...";
			document.getElementById(objPai).innerHTML = primeira_opcao_selecionada;	
		}
	}
	
	function createHiddenField(nome,valor,preNodeId,param_codigo){
		var newInputHidden = document.createElement("input");
		newInputHidden.setAttribute("type", "hidden");
		newInputHidden.setAttribute("name", preNodeId+"_cd[]");
		newInputHidden.setAttribute("id", "hdd_"+nome);
		newInputHidden.setAttribute("codigo", param_codigo);
		newInputHidden.setAttribute("value", valor);
		return newInputHidden;
	}
	
	function buscaCodigo(){
		if(document.formBusca.codigo.value==""){
			alert("Preencha o código do Imóvel");
			return false;
		} else {
			document.formBusca.action = "../imoveis/detalhe_imovel.php?codigo=" + document.formBusca.codigo.value;
			//document.formBusca.submit();
		}
	}
	
	function buscar(){
		if(objDivUtilizando) document.getElementById(objDivUtilizando).style.display	= "none";
		if(objDivUtilizada) document.getElementById(objDivUtilizada).style.display	= "none";
		
		if(document.getElementById("codImovel").value == ""){
		
			if(document.getElementById("localidade_cd").value == ""){
				alert("Selecione a cidade!");	
				return false;
			}
			if(document.getElementById("tipo_cd").value == ""){
				alert("Selecione o tipo de imóvel!");	
				return false;
			}
			
		}
		
		//document.formBusca.submit();
		carregaResultadoBusca();
	}
	
	var primeira_opcao_selecionada = "";
	function pegaStringOpcoesSelecionadas(preNodeId,flag_codigo){
		str_opcoes = "";
		var objDiv = document.getElementById("campos_"+preNodeId);
		
		if(flag_codigo){
			codigo_pega_valor = "objDiv.childNodes[i].getAttribute('codigo') + ','";
		}else{
			codigo_pega_valor = "objDiv.childNodes[i].value + ','";
		}
		
		for(var i=0; i<objDiv.childNodes.length; i++){
			str_opcoes += eval(codigo_pega_valor);
			if(i==0){
				primeira_opcao_selecionada = objDiv.childNodes[i].value;
				if(objDiv.childNodes.length > 1) primeira_opcao_selecionada;
			}
		}
		if(str_opcoes != ""){
			str_opcoes = str_opcoes.substring(0, str_opcoes.length-1);
		}
		return str_opcoes;
	}
	
	var objDivRetorno = null;
	var params = "";
	function carregaResultadoBusca(){
		openCloseBusca('contentBuscaSimples');
		var objDivRetorno = document.getElementById("contentMiolo");
		ajax2 = InicializaAjax();
	  	//se tiver suporte ajax
	  	if(ajax2) {
			var url="../imoveis/_imoveis_lista_busca.php";
			ajax2.open("POST", url, true);
		 	ajax2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 	ajax2.onreadystatechange = function() {
				//enquanto estiver processando...emite a msg de carregando
				if(ajax2.readyState == 1) {
					objDivRetorno.innerHTML = "<img src='../../imagens/icones/ajax-loader.gif' />&nbsp;&nbsp;<h5>Carregando, por favor aguarde...</h5>";   
				}
				//após ser processado
				if(ajax2.readyState == 4 ) {
					if (ajax2.status == 200){
						if(objDivRetorno != null){
							if(ajax2.responseText == 1) window.location.href = "../../pt/home/anuncie-seu-imovel.php?solicitado=0&"+params;
							else{ 
								objDivRetorno.innerHTML = ajax2.responseText;
								selOption('CNPJ0');
								carregaHiddenBusca('CNPJ','');
							}
						}
					}else{
						if(objDivRetorno != null){
							objDivRetorno.innerHTML = "Ocorreu um erro no resultado da busca:<br>"+ajax2.statusText;
							objDivRetorno.innerHTML += "<br/>Por favor, tente novamente.";
						}
					}
				}
			}
			
			params = "localidade_cd=" + document.getElementById("localidade_cd").value + "&";
			params += "tipo_cd=" + document.getElementById("tipo_cd").value + "&";
			params += "maximo=" + document.getElementById("maximo").value.replace(/\./g,"").replace(".","").replace(",",".") + "&";
			params += "finalidade=" + document.getElementById("finalidade").value + "&";
			params += "grupo=" + document.getElementById("grupo").value + "&";
			params += "dormitorios=" + document.getElementById("dormitorios").value + "&";
			params += "suites=" + document.getElementById("suites").value + "&";
			params += "vagas=" + document.getElementById("vagas").value + "&";
			params += "CNPJ=" + document.getElementById("CNPJ").value + "&";
			params += "ordem=" + document.getElementById("ordem").value + "&";
			//params += "codigo=" + document.getElementById("codImovel").value + "&";
			
			str_bairros = pegaStringOpcoesSelecionadas("bairro",0);
			params += "bairro_cd=" + escape(str_bairros) + "&";
			
			str_subtipo = pegaStringOpcoesSelecionadas("subtipo",1);
			params += "sub_tipo_cd=" + escape(str_subtipo) + "&";
			
			params = params.substring(0, params.length-1);
			//alert("params: "+params);
			
			ajax2.send(params);
		}
	}
	
	function carregaSubTipos(tipo_cd) {
	  primeira_opcao_selecionada = "";
	  str_opcoes = "";
	  document.getElementById("campos_subtipo").innerHTML = "";
	  
	  //remove a lista de subtipos
	  var objSubTipos = document.getElementById("ul_Subtipo");
	  objSubTipos.innerHTML = "";
	  
	  idOpcaoSubTipo = document.getElementById("buscaAvancadaSubtipo");
	  
	  ajax3 = InicializaAjax();
	  //se tiver suporte ajax
	  if(ajax3) {
		 ajax3.open("POST", "../_includes/xml_subtipos.php", true);
		 ajax3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajax3.onreadystatechange = function() {
			//enquanto estiver processando...emite a msg de carregando
			if(ajax3.readyState == 1) {
			   idOpcaoSubTipo.innerHTML = "Carregando...";   
			}
			//após ser processado - chama função processXMLSubTipo que vai varrer os dados
			if(ajax3.readyState == 4 ) {
			   if(ajax3.responseXML) {
				  processXMLSubTipo(ajax3.responseXML, objSubTipos);
			   }else{
				   //caso não seja um arquivo XML emite a mensagem abaixo
				   idOpcaoSubTipo.innerHTML = "";
			   }
			}
		 }
		 var params = "tipo_cd="+tipo_cd;
		 ajax3.send(params);
	  }
	}
	
	var codigo = "";
	function processXMLSubTipo(objResponseXML, objSubTipos){
	  //pega a tag subtipo
	  var dataArray   = objResponseXML.getElementsByTagName("subtipo");
	  
	  //total de elementos contidos na tag subtipo
	  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 nome    =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
			var nodeId    =  item.getElementsByTagName("nodeId")[0].firstChild.nodeValue;
			idOpcaoSubTipo.innerHTML = "Selecione";
			codigo = nodeId;
			//alert("1: " + codigo);
			addNodes(objSubTipos,nome,"subtipo",nodeId);
		 }
		 idOpcaoSubTipo.innerHTML = "Selecione";
		 idOpcaoSubTipo.title = "Selecione";
	  }else{
		//caso o XML volte vazio, printa a mensagem abaixo
		 idOpcaoSubTipo.innerHTML = "";
		 idOpcaoSubTipo.title = "Não há subtipos cadastrados para o tipo selecionado";
	  }	  
	}
	
//open e close busca avancada
function openCloseBusca(id){
	if(id == 'contentBuscaAvancada'){
		document.getElementById(id).style.display="block";	
		document.getElementById('btBuscaAvancada').style.display="none";
		document.getElementById('btBuscaSimples').style.display="block";
		//document.getElementById('boxBuscaCodigo').style.marginTop="61px";
		//document.getElementById('boxBuscaCodigo').style.marginLeft="300px";
	}else{
		document.getElementById('contentBuscaAvancada').style.display="none";	
		document.getElementById('btBuscaAvancada').style.display="block";
		document.getElementById('btBuscaSimples').style.display="none";	
		document.getElementById('boxBuscaCodigo').style.marginTop="-31px";
		document.getElementById('boxBuscaCodigo').style.marginLeft="272px";
	}
}
	
//Mostra os imóveis em destaque de acordo com os parâmetros: Venda / Locação
function showImoveisDestaque(tipoImovel){
	carregaImoveisDestaque(tipoImovel);
}

var objDivRetorno = null;
function carregaImoveisDestaque(tipoImovel){
	var objDivRetorno = document.getElementById("boxImoveisDestaque");
	if(objDivRetorno != null){
		ajax4 = InicializaAjax();
		//se tiver suporte ajax
		if(ajax4) {
			var url="../home/_imoveis_destaque.php";
			ajax4.open("POST", url, true);
			ajax4.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
			ajax4.onreadystatechange = function() {
				//enquanto estiver processando...emite a msg de carregando
				if(ajax4.readyState == 1) {
					objDivRetorno.innerHTML = "<img src='../../imagens/icones/ajax-loader.gif' />&nbsp;&nbsp;<h5>Carregando, por favor aguarde...</h5>";   
				}
				//após ser processado
				if(ajax4.readyState == 4 ) {
					if (ajax4.status == 200){
						if(objDivRetorno != null) objDivRetorno.innerHTML = ajax4.responseText;
					}else{
						if(objDivRetorno != null){
							objDivRetorno.innerHTML = "Ocorreu um erro no resultado da busca:<br>"+ajax4.statusText;
							objDivRetorno.innerHTML += "<br/>Por favor, tente novamente.";
						}
					}
				}
			}
			
			var params = "finalidade=" + tipoImovel + "&";	
			params += "grupo=" + document.getElementById("grupo").value;
			ajax4.send(params);
		}
	}
}

function carregaBannersDestaque(tipoImovel){
	if(document.getElementById("boxBannerDestaque") != null){
		var flash = insertFlash({src:"../../imagens/bannerDestaque/bannerDestaque.swf",
				id:"bannerSWF",
				width:210, height:235,
				wmode:"transparent",
				flashVars:"path=../../imagens/bannerDestaque/&xml=banners.php?cat="+tipoImovel,
				flashVersion:"9,0,0,0"}, true);
		//alert(document.getElementById("boxBannerDestaque").childNodes[1]);
		document.getElementById("boxBannerDestaque").innerHTML = flash;
	}
}
