var Map;
var Marker;
$(function() {
	$(document).keypress(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if (code == 27) { CloseInfoImovel(); }
	});
	$("#Busca input[type=checkbox]").attr('checked', false);
	
	$( "#slider-quartos" ).slider({
		range: true,
		min: 0,
		max: 6,
		animate: true,
		values: [ 0, 6 ],
		slide: function( event, ui ) {
			if (ui.values[ 0 ] == ui.values[ 1 ]) { $( "#amountQuartos" ).html( ui.values[ 0 ] ); }
			else { $( "#amountQuartos" ).html( ui.values[ 0 ] + " a " + ui.values[ 1 ] ); }
		},
		stop: function() { UpdateResults(false); }
	});
	
	$( "#slider-garagem" ).slider({
		range: true,
		min: 0,
		max: 2,
		animate: true,
		values: [ 0, 2 ],
		slide: function( event, ui ) {
			if (ui.values[ 0 ] == ui.values[ 1 ]) { $( "#amountGaragem" ).html( ui.values[ 0 ] ); }
			else { $( "#amountGaragem" ).html( ui.values[ 0 ] + " a " + ui.values[ 1 ] ); }
		},
		stop: function() { UpdateResults(false); }
	});
	
	$( "#slider-valor" ).slider({
		range: true,
		min: 0,
		max: 2,
		animate: true,
		values: [ 0, 2 ],
		slide: function( event, ui ) {
			if (ui.values[ 0 ] == ui.values[ 1 ]) { $( "#amountValor" ).html( 'R$ ' + formatCurrency(ui.values[ 0 ]) ); }
			else { $( "#amountValor" ).html( 'R$ ' + formatCurrency(ui.values[ 0 ]) + " - R$ " + formatCurrency(ui.values[ 1 ]) ); }
		},
		stop: function() { UpdateResults(false); }
	});

	$( "#slider-banheiros" ).slider({
		range: true,
		min: 0,
		max: 2,
		animate: true,
		values: [ 0, 2 ],
		slide: function( event, ui ) {
			if (ui.values[ 0 ] == ui.values[ 1 ]) { $( "#amountBanheiros" ).html( ui.values[ 0 ] ); }
			else { $( "#amountBanheiros" ).html( ui.values[ 0 ] + " a " + ui.values[ 1 ] ); }
		},
		stop: function() { UpdateResults(false); }
	});		
	
	$('#Imoveis > div.Imovel').live('mouseover', function() {
		$(this).stop(true, false).animate({ backgroundColor: '#444444' });
	});
	$('#Imoveis > div.Imovel').live('mouseout', function() {
		$(this).stop(true, false).animate({ backgroundColor: '#212121' });
	});
	
	//Imobiliario = Imb.Venda;
	//InfoImovel(6);
});

function UpdateCheckbox() {
	$("#BuscaImoveis label").each(function() {
		if ($("input#" + $(this).attr('for')).is(":checked")) {
			$(this).addClass("checked");
		} else { $(this).removeClass("checked"); }
	});
}
		
		var OldFinalidades = null;
		function UpdateTipo() {
			var Tipos = Array();
			var Finalidades = Array();
			var FinalidadesCheck = Array();
			$('input[name=TipoImovel]:checked').each(function() { Tipos[Tipos.length] = $(this).val(); });
			$('input[name=Finalidades]:checked').each(function() { FinalidadesCheck[FinalidadesCheck.length] = $(this).val(); });
			UpdateCheckbox();
			
			var Html = '';
			for (var i in Imobiliario.imoveis) {
				if (inArray(Imobiliario.imoveis[i].tipo, Tipos)) {
					for (var k in Imobiliario.imoveis[i].finalidades) {
						Finalidades[Imobiliario.imoveis[i].finalidades[k]] = Imobiliario.imoveis[i].finalidades[k];
					}
				}
			}
			var Finalidades = Array();
			for (var i in Tipos) {
				for (var k in ImobiliarioAtual.Tipos[Tipos[i]]) {
					if (!inArray(ImobiliarioAtual.Tipos[Tipos[i]][k], Finalidades)) {
						Finalidades[Finalidades.length] = ImobiliarioAtual.Tipos[Tipos[i]][k];
					}
				}
			}
			for (var i in Finalidades) {
				Html += '<div style="padding: 3px 0px;"><input type="checkbox" name="Finalidades" ' + (inArray(Finalidades[i], FinalidadesCheck) ? 'checked="checked"' : '' ) + ' id="f' + Finalidades[i].replace('/', '').replace(' ', '').replace(' ', '') + '" value="' + Finalidades[i] + '" onchange="UpdateFinalidade()" onclick="UpdateFinalidade()" /><label ' + (inArray(Finalidades[i], FinalidadesCheck) ? 'class="checked"' : '' ) + 'for="f' + Finalidades[i].replace('/', '').replace(' ', '').replace(' ', '') + '">' + Finalidades[i] + '</label></div>';
			}
			//Html = '<div style="height: 1px; background: #EEE; margin: 10px 0px 10px 0px;"></div>' + Html;
			if (Finalidades.length > 0) {
				if (!$("#Finalidades").is(":visible")) { $("#Finalidades").html(Html).slideDown(); }
				else if (OldFinalidades != Html) { $("#Finalidades").slideUp(200, function() { $(this).html(Html).slideDown(200); }); }
				OldFinalidades = Html;
			} else { $("#Finalidades").slideUp(); }
			UpdateResults(true);
		}
		
		function UpdateFinalidade() {
			UpdateCheckbox();
			UpdateResults(true);
		}
		
		
		function formatCurrency(value) {
			if (value == null) { return '0,00'; }
			var a = value.toString().split('.');
			if (a[0].length > 3) {
				var x = a[0];
				var n = '';
				while (x.length > 0) {
					if (x.length > 3) { n = x.substr(x.length - 3) + (n != '' ? '.' : '') + n; }
					else { n = x + '.' + n; }
					x = x.substr(0, x.length - 3);
				}				
				n += ',' + (a.length > 1 ? a[1] : '00');
				return n;
				//return a[0].substr(0, a[0].length - 3) + '.' + a[0].substr(a[0].length - 3) + ',' + (a.length > 1 ? a[1] : '00');
			} else {
				return a[0] + ',' + (a.length > 1 ? a[1] : '00');
			}
		}
		
		var Filtros = false;
		var ResultsCheck = null;
		var ImoveisMapa = null;
		function UpdateResults(UpdateFilters) {
			if (typeof(StartBanner) != 'undefined') { StopBanner(); }
			var OldRC = ResultsCheck;
			ResultsCheck = '';

			if (UpdateFilters) { Filtros = false; }
			var Tipos = Array();
			var Finalidades = Array();
			$('input[name=TipoImovel]:checked').each(function() { Tipos[Tipos.length] = $(this).val(); });
			$('input[name=Finalidades]:checked').each(function() { Finalidades[Finalidades.length] = $(this).val(); });
			if (!(inArray('Terreno', Tipos) || inArray('Box', Tipos))) {
				if (!(Tipos.length > 0 && Finalidades.length > 0)) {
					if ($("#SearchResults").is(':visible')) {
						$("#SearchResults").slideUp(function() {
							$("#ImovelContent").hide();
							$("#Content").slideDown();		
							$(this).css('display', 'none');
						});
					} else {
						$("#SearchResults").hide(function() { $(this).css('display', 'none'); });
						$("#ImovelContent").hide();
						$("#Content").show();
					}

					return;
				}
			}
			
			var Html = '';
			var Resultados = 0;
			var ResultadosReais = 0;
			var Valores = { Min: 1000 * 1000, Max: 0 };
			var Dormitorios = { Min: 1000 * 1000, Max: 0 };
			var Garagens = { Min: 1000 * 1000, Max: 0 };
			var Banheiros = { Min: 1000 * 1000, Max: 0 };
			var Comodidades = Array();
			
			if (!ImoveisMapa) { ImoveisMapa = new google.maps.MVCArray(); }
			ImoveisMapa.clear();
			for (var i in ImobiliarioAtual.Imoveis) {
				var Imovel = Imobiliario.Imoveis[ImobiliarioAtual.Imoveis[i]];
				if (inArray(Imovel.tipo, Tipos)) {
					if (!((inArray('Terreno', Tipos) || inArray('Box', Tipos)) && !Imovel.subtipo)) {
						if (!inArray(Imovel.subtipo, Finalidades)) { continue; }
					}
				
					
						if (BuscaTipo == 0) { var Valor = parseFloat(Imovel.valor_venda); }
						else { var Valor = parseFloat(Imovel.valor_locacao); }
					
						if (Valor < Valores.Min) { Valores.Min = parseInt(Valor); }
						if (Valor > Valores.Max) { Valores.Max = parseInt(Valor); }
					
						if (Imovel.dormitorios < Dormitorios.Min) { Dormitorios.Min = Imovel.dormitorios; }
						if (Imovel.dormitorios > Dormitorios.Max) { Dormitorios.Max = Imovel.dormitorios; }
					
						if (Imovel.garagens < Garagens.Min) { Garagens.Min = Imovel.garagens; }
						if (Imovel.garagens > Garagens.Max) { Garagens.Max = Imovel.garagens; }
						
						if (Imovel.banheiros < Banheiros.Min) { Banheiros.Min = Imovel.banheiros; }
						if (Imovel.banheiros > Banheiros.Max) { Banheiros.Max = Imovel.banheiros; }					
					
						for (var cc in Imovel.comodidades) {
							Comodidades[Imovel.comodidades[cc]] = Imobiliario.Comodidades[Imovel.comodidades[cc]];
						}					
					
						if (Filtros) {
							if (Valor < $('#slider-valor').slider("values", 0) || Valor > $('#slider-valor').slider("values", 1)) { continue; }
							if (Imovel.dormitorios < $('#slider-quartos').slider("values", 0) || Imovel.dormitorios > $('#slider-quartos').slider("values", 1)) { continue; }
							if (Imovel.garagens < $('#slider-garagem').slider("values", 0) || Imovel.garagens > $('#slider-garagem').slider("values", 1)) { continue; }
							if (Imovel.banheiros < $('#slider-banheiros').slider("values", 0) || Imovel.banheiros > $('#slider-banheiros').slider("values", 1)) { continue; }
						}
						
						if (UsarFiltrosExtras) {
							if ($("#mobiliado").attr('checked') && !Imovel.mobiliado) { Resultados++; continue; }
							var C = false;
							$("#Comodidades input:checked").each(function() {
								if (!inArray($(this).val(), Imovel.comodidades)) { C = true; }
							});
							if (C) { Resultados++; continue; }
						}
					
						var ImovelId = Imovel.sid;
						var Pos = { sid: ImovelId, pos: new google.maps.LatLng(Imovel.geoposicionamento.lat, Imovel.geoposicionamento.lng) };
						ImoveisMapa.push(Pos);					
					
						Html += HtmlResultado(Imovel, i);
						ResultsCheck += Imovel.sid;
						Resultados++;
						ResultadosReais++;
					
				}
			}
			
			Html = '<div style="background: #ffc8cb; color: #000; padding: 5px 10px 5px 10px; margin-bottom: 5px; margin-top: 5px; font-size: 11px;"><span style="float: right;"><a style="color: #000;" href="javascript:cancelarBusca()">Voltar</a></span>' + (ResultadosReais == 0 ? 'Nenhum imóvel encontrado' : (ResultadosReais == 1 ? 'Um imóvel encontrado' : '<b>' + ResultadosReais + '</b> imóveis encontrados' )) + '. ' + (ResultadosReais > 0 ? 'Clique no imóvel para ver mais informações' : '<a href="solicite/">Clique aqui</a> para solicitar o seu imóvel') + '.</div>' + Html;
			if (UpdateFilters) {
				$("#slider-valor").slider("option", { min: Valores.Min, max: Valores.Max, values: [ parseInt(Valores.Min), parseInt(Valores.Max) ] });
				$( "#amountValor" ).html( 'R$ ' + formatCurrency(Valores.Min) + " a R$ " + formatCurrency(Valores.Max) );
				$("#slider-quartos").slider("option", { min: parseInt(Dormitorios.Min), max: parseInt(Dormitorios.Max), values: [ parseInt(Dormitorios.Min), parseInt(Dormitorios.Max) ] });
				$( "#amountQuartos" ).html( (Dormitorios.Min == Dormitorios.Max ? Dormitorios.Min : Dormitorios.Min + " a " + Dormitorios.Max) );
				$("#slider-banheiros").slider("option", { min: parseInt(Banheiros.Min), max: parseInt(Banheiros.Max), values: [ parseInt(Banheiros.Min), parseInt(Banheiros.Max) ] });
				$( "#amountBanheiros" ).html( (Banheiros.Min == Banheiros.Max ? Banheiros.Min : Banheiros.Min + " a " + Banheiros.Max) );
            
				$("#slider-garagem").slider("option", { min: parseInt(Garagens.Min), max: parseInt(Garagens.Max), values: [ parseInt(Garagens.Min), parseInt(Garagens.Max) ] });
				$( "#amountGaragem" ).html( (Garagens.Min == Garagens.Max ? Garagens.Min : Garagens.Min + " a " + Garagens.Max) );
            
				$("#gText").css({ color: (Garagens.Min == Garagens.Max ? "#888" : "#FFF") });
				$("#slider-garagem").slider("disabled", (Garagens.Min == Garagens.Max));
            
				$("#dText").css({ color: (Dormitorios.Min == Dormitorios.Max ? "#888" : "#FFF") });
				$("#slider-quartos").slider("disabled", (Dormitorios.Min == Dormitorios.Max));
            
				$("#bText").css({ color: (Banheiros.Min == Banheiros.Max ? "#888" : "#FFF") });
				$("#slider-banheiros").slider("disabled", (Banheiros.Min == Banheiros.Max));
				
				var ComodidadesCheck = Array();
				$("#Comodidades input:checked").each(function() { ComodidadesCheck[ComodidadesCheck.length] = $(this).val();  });
				
				var HtmlComodidades = '';
				for (var cc in Comodidades) {
					HtmlComodidades += '<div class="inblock" style="width: 235px;"><input ' + (inArray(cc, ComodidadesCheck) ? 'checked="checked"' : '') + ' type="checkbox" value="' + cc + '" name="co' + cc + '" id="co' + cc + '" onclick="UpdateResults(false);" onchange="UpdateResults(false);" style="vertical-align: middle;" /> <label style="vertical-align: middle;" ' + (inArray(cc, ComodidadesCheck) ? 'class="checked"' : '') + ' onclick="UpdateResults(false);" for="co' + cc + '">' + Comodidades[cc] + '</label></div>';
				}
				$("#Comodidades").html(HtmlComodidades);
				if (Comodidades.length == 0) { $("#ComodidadesContainer").hide(); }
				else { $("#ComodidadesContainer").show(); }
			}

			
			
			
			if (OldRC != ResultsCheck) {
				//$("#Content").slideUp(100);
				//$("#Imoveis").html(Html).slideUp(100, function() { $(this).slideDown(function() { $(this).show(); }); });
				//$("#SearchResults").show().css('display', 'block');
				//$(".Imovel [title]").tooltip({ position: "bottom center", opacity: 0.5 });
				
				$("#Content").slideUp(100);
				$("#ImovelContent").show();
				$("#ImovelInfo").hide();
				setTimeout(function() {
					$("#SearchResults").slideDown(100, function() { $(this).css('display', 'block'); });
					$("#Imoveis").slideUp(100, function() {
						$("#Imoveis").html(Html);
						$(".Imovel [title]").tooltip({ position: "bottom center", opacity: 0.9 });
						if (MapType == 0) { $("#Imoveis").slideDown(100, function() { $(this).css('display', 'block'); });  }
					});
				}, 100);

				//$("#Content").slideUp(function() {
				//	$("#Imoveis").slideUp(100, function() {
				//		$("#Imoveis").html(Html);
				//		$(".Imovel [title]").tooltip({ position: "bottom center", opacity: 0.5 });
				//		$("#SearchResults").slideDown(function() {
				//			$("#Imoveis").slideDown(100); 
				//			$(this).css('display', 'block');
				//		});
				//	});
				//});
				
				if (MapType == 1) { UpdateMapa(); }
			}
			if (UpdateFilters && Resultados <= 1) {
				$("#Filtros").hide();
			} else { $("#Filtros").show(); }
			Filtros = true;
		}
		
		function HtmlResultado(Imovel, id) {
			var Garagem = '', Dormitorios = '', Banheiros = '';
			for (var i = 0;i < Imovel.garagens;i++) { Garagem += '<img style="margin-right: 5px;" src="imagens/garagem.png" />'; }
			for (var i = 0;i < Imovel.banheiros;i++) { Banheiros += '<img style="margin-right: 5px;" src="imagens/banheiro.png" />'; }
			for (var i = 0;i < Imovel.dormitorios;i++) {
				if (((Imovel.dormitorios - (i+1)) - Imovel.suites) >= 0) { Dormitorios += '<img style="margin-right: 5px;" src="imagens/dormitorio.png" />'; }
				else { Dormitorios += '<img style="margin-right: 5px;" src="imagens/suite.png" />'; }
			}
			var TitleDormitorios = ((Imovel.dormitorios - Imovel.suites) > 0 ? ((Imovel.dormitorios - Imovel.suites) == 1 ? (Imovel.dormitorios - Imovel.suites) + ' dormitório' : (Imovel.dormitorios - Imovel.suites) + ' dormitórios') : '') + (Imovel.suites > 0 ? (Imovel.suites == 1 ? ((Imovel.dormitorios - Imovel.suites) > 0 ? ' e ' : '' ) + 'suíte' : ((Imovel.dormitorios - Imovel.suites) > 0 ? ' e ' : '' ) + Imovel.suites + ' suítes') : '');
			var TitleBanheiros = Imovel.banheiros + (Imovel.banheiros == 1 ? ' banheiros' : ' banheiros');
			var TitleGaragens = Imovel.garagens + (Imovel.garagens == 1 ? ' garagem' : ' garagens');
			return '\
				<div class="Imovel" style="height: 110px; padding: 10px; color: #FFF;" onclick="InfoImovel(\'' + Imovel.sid + '\')">\
					<div style="float: left;"><img style="background: #fff; padding: 5px;" src="' + Imovel.imagem_capa + '" /></div>'
					+ (BuscaTipo == 0 ?
						'<div style="float: right; text-align: right; padding: 10px 0px 10px 10px; cursor: default;" class="Preco">\
							' + (Imovel.valor_venda > 0 ? '<div style="color: #888 !important; font-size: 12px; font-weight: bold;" title="Valor de venda">R$ ' + formatCurrency(Imovel.valor_venda) + '</div>' : '' ) + '\
							' + (Imovel.valor_locacao > 0 ? '<div style="display: inline-block; color: #AAA !important; font-size: 11px; font-weight: bold;" title="Valor de aluguel">R$ ' + formatCurrency(Imovel.valor_locacao) + '</div>' : '') + '\
						</div>'
						:
						(BuscaTipo == -1 ?
							(Imovel.valor_venda > 0 ?
								'<div style="float: right; text-align: right; padding: 10px; cursor: default;" class="Preco">\
									' + (Imovel.valor_venda > 0 ? '<div style="color: #888 !important; font-size: 12px; font-weight: bold;" title="Valor de venda">R$ ' + formatCurrency(Imovel.valor_venda) + '</div>' : '' ) + '\
									' + (Imovel.valor_locacao > 0 ? '<div style="display: inline-block; color: #AAA !important; font-size: 11px; font-weight: bold;" title="Valor de aluguel">R$ ' + formatCurrency(Imovel.valor_locacao) + '</div>' : '') + '\
								</div>'
								:
								'<div style="float: right; text-align: right; padding: 10px; cursor: default;" class="Preco">\
									' + (Imovel.valor_locacao > 0 ? '<div style="color: #888 !important; font-size: 12px; font-weight: bold;" title="Valor de aluguel">R$ ' + formatCurrency(Imovel.valor_locacao) + '</div>' : '') + '\
									' + (Imovel.valor_venda > 0 ? '<div style="display: inline-block; color: #AAA !important; font-size: 11px; font-weight: bold;" title="Valor de venda">R$ ' + formatCurrency(Imovel.valor_venda) + '</div>' : '') + '\
								</div>'
							)							
						:
						'<div style="float: right; text-align: right; padding: 10px; cursor: default;" class="Preco">\
							' + (Imovel.valor_locacao > 0 ? '<div style="color: #888 !important; font-size: 12px; font-weight: bold;" title="Valor de aluguel">R$ ' + formatCurrency(Imovel.valor_locacao) + '</div>' : '') + '\
							' + (Imovel.valor_venda > 0 ? '<div style="display: inline-block; color: #AAA !important; font-size: 11px; font-weight: bold;" title="Valor de venda">R$ ' + formatCurrency(Imovel.valor_venda) + '</div>' : '') + '\
						</div>'
						)
					) + '\
					<div style="margin-left: 134px; padding: 10px 0px 10px 10px; font-size: 11px;">\
						<div style="padding-bottom: 3px;"><b>' + Imovel.tipo + '</b></div>\
						<div style="padding-bottom: 3px;">' + Imovel.endereco_logradouro + '</div>\
						<div style="padding-bottom: 10px;">' + Imovel.endereco_bairro + (Imovel.endereco_bairro != '' && Imovel.endereco_cidade != '' ? ' - ' : '') + Imovel.endereco_cidade + '</div>\
						<div>\
							<span style="float: right; font-size: 11px; text-align: right;">\
								<a id="lImv' + Imovel.sid + '" target="_blank" href="imovel/' + Imovel.sid + '" onclick="preventOpen = true;" style="display: block; outline: none;">Abrir em nova janela</a>\
								<img class="fav' + Imovel.sid + '" onclick="preventOpen = true; Favoritos.toggle(\'' + Imovel.sid + '\', this);" style="margin-top: 5px; cursor: pointer; vertical-align: middle;" src="imagens/favorito' + (Favoritos.find(Imovel.sid) ? '_checked' : '') + '.png" />\
							</span>\
							' + (Dormitorios != '' ? '<span style="display: inline-block; margin-right: 10px; float: left;" class="Dormitorios" title="' + TitleDormitorios + '">' + Dormitorios + '</span>' : '') + '\
							' + (Banheiros != '' ? '<span style="display: inline-block; margin-right: 10px; float: left;" class="Banheiros" title="' + TitleBanheiros + '">' + Banheiros + '</span>' : '') + '\
							' + (Garagem != '' ? '<span style="display: inline-block; margin-right: 10px; float: left;" class="Garagens" title="' + TitleGaragens + '">' + Garagem + '</span>' : '') + '\
						</div>\
					</div>\
				</div>\
			';
		}

		var ImobiliarioAtual;
		var BuscaTipo = -1;
		function ShowBusca(i) {
			if (BuscaTipo != i) {
				switch (i) {
					case 0: window.location.hash = '#Compra'; break;
					case 1: window.location.hash = '#Locacao'; break;
				}
				$("#ImovelInfo").slideUp(100);
				var Tipos = null;
				if (i == 0) { ImobiliarioAtual = Imobiliario.Venda; }
				else { ImobiliarioAtual = Imobiliario.Locacao; }
				
				if (i == 0) { Tipos = Imobiliario.Venda.Tipos; }
				else { Tipos = Imobiliario.Locacao.Tipos; }

				$("#BuscaVenda").css('background-position', '0px 0px');
				$("#BuscaAluguel").css('background-position', '-109px 0px');
	
				if (i == 0) { $("#BuscaVenda").css('background-position', '0px -28px'); }
				else { $("#BuscaAluguel").css('background-position', '-109px -28px'); }
				
				BuscaTipo = i;
				$("#BuscaFacil").slideUp(function() {
					var TiposChecked = Array();
					$('input[name=TipoImovel]:checked').each(function() { TiposChecked[Tipos.length] = $(this).val(); });
					var Html = '';
					for (var i in Tipos) {
						Html += '<div style="padding: 3px 0px;"><input type="checkbox" ' + (inArray(i, TiposChecked) ? 'checked="checked"' : '' ) + ' name="TipoImovel" id="t' + i.replace('/', '').replace(' ', '').replace(' ', '') + '" value="' + i + '" onchange="UpdateTipo()" onclick="UpdateTipo()" /><label ' + (inArray(i, TiposChecked) ? 'class="checked"' : '' ) + ' for="t' + i.replace('/', '').replace(' ', '').replace(' ', '') + '">' + i + '</label></div>';
					}
					
					$("#BuscaImoveis").slideUp(function() {
						$("#TiposImoveis").html(Html);
						$("#BuscaImoveis").slideDown(100, function() { $("#TiposImoveis").slideDown();});
						UpdateTipo();
					});
				});
			}
		}
		

		var ChangingImage = false;
		function ProximaImagem() {
			if (ChangingImage) { return; }
			if (CurrentImage + 1 < $(".ImagemImovel").length) {
				ChangingImage = true;
				if (CurrentImage + 2 == $(".ImagemImovel").length) { $('#btnProximaImagem').hide();  }
				else { $('#btnProximaImagem').show();  }
				$('#btnImagemAnterior').show();
				$(".ImagemImovel:visible").fadeOut(100, function() {
					$(".ImagemImovel.Img" + (++CurrentImage)).fadeIn(100, function() { ChangingImage = false; });
				});
			}
		}

		function ImagemAnterior() {
			if (ChangingImage) { return; }
			if (CurrentImage - 1 >= 0) {
				ChangingImage = true;
				if (CurrentImage - 1 == 0) { $('#btnImagemAnterior').hide();  }
				else { $('#btnImagemAnterior').show();  }
				$('#btnProximaImagem').show();
				$(".ImagemImovel:visible").fadeOut(100, function() {
					$(".ImagemImovel.Img" + (--CurrentImage)).fadeIn(100, function() { ChangingImage = false; });
				});
			}
		}
		
		var ChangingVideo = false;
		function ProximoVideo() {
			if (ChangingVideo) { return; }
			if (CurrentVideo + 1 < $("#Videos > iframe").length) {
				ChangingImage = true;
				if (CurrentImage + 2 == $("#Videos > iframe").length) { $('#btnProximoVideo').hide();  }
				else { $('#btnProximoVideo').show();  }
				$('#btnVideoAnterior').show();
				$("#Videos iframe:visible").fadeOut(100, function() {
					$(".Video" + (++CurrentVideo)).fadeIn(100, function() { ChangingVideo = false; });
				});
			}
		}

		function VideoAnterior() {
			if (ChangingVideo) { return; }
			if (CurrentVideo - 1 >= 0) {
				ChangingVideo = true;
				if (CurrentVideo - 1 == 0) { $('#btnVideoAnterior').hide();  }
				else { $('#btnVideoAnterior').show();  }
				$('#btnProximoVideo').show();
				$("#Videos > iframe:visible").fadeOut(100, function() {
					$(".Video" + (--CurrentVideo)).fadeIn(100, function() { ChangingVideo = false; });
				});
			}
		}
		
		var Current = "#Fotos";
		function ChangeToFotos() { if (Current != "#Fotos") { $(Current).fadeOut(100, function() { $("#Fotos").fadeIn(100); }); Current = "#Fotos"; } $("#MenuMapa > div").removeClass("active"); $("#MenuMapa > div#aFotos").addClass("active"); }
		function ChangeToVideos() { if (Current != "#Videos") { $(Current).fadeOut(100, function() { $("#Videos").fadeIn(100); }); Current = "#Videos"; } $("#MenuMapa > div").removeClass("active"); $("#MenuMapa > div#aVideos").addClass("active"); }
		function ChangeToMapa() {
			if (Current != "#MapaImovel") {
				$(Current).fadeOut(100, function() {
					$("#MapaImovel").fadeIn(100, function() {
						google.maps.event.trigger(Map, 'resize');
						Map.setCenter(Marker.getPosition());
						setTimeout(function() { Map.setCenter(Marker.getPosition()); }, 500);
					});
				});
				Current = "#MapaImovel";
			}
			$("#MenuMapa > div").removeClass("active");
			$("#MenuMapa > div#aMapa").addClass("active");
		}
		
		function CreateMap() {
			var latLng = new google.maps.LatLng(0, 0);
			var opt = {
				zoom: 15,
				center: latLng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControl: false,
				panControl: false,
				scaleControl: false,
				streetViewControl: false,
				zoomControl: false,
				noClear: true
			};
			
			Map = new google.maps.Map(document.getElementById("MapaImovel"), opt);
			Marker = new google.maps.Marker({
				draggable: false,
				flat: false,
				position: latLng,
				raiseOnDrag: true,
				title: 'Localização do imóvel',
				map: Map
			});
		}
		
		function VoltarBusca() {
			$('#ImovelInfo').hide();
			$('#SearchResults').show();
		}
		
		$(function() {
			$.history.init(function(hash){
				if(hash != "") {
					switch (hash) {
						case 'Compra':
							if (CurrentImovelSid != null) { VoltarBusca(); }
							$("#LoadingImovel").stop(true, true).css({ opacity: 0.5 }).hide();
							CurrentImovelSid = null;
							ShowBusca(0);
							break;
						case 'Locacao':
							if (CurrentImovelSid != null) { VoltarBusca(); }
							$("#LoadingImovel").stop(true, true).css({ opacity: 0.5 }).hide();
							CurrentImovelSid = null;
							ShowBusca(1);
							break;
						case 'Busca':
							CurrentImovelSid = null;
							if (ImovelBuscaCodigo != null) { buscarCodigo(true); }
							break;
						case 'Favoritos':
							mostrarFavoritos();
							break;
						default:
							var A = hash.split('-');
							if (A[0] == 'Imovel') {
								InfoImovel(A[1]);
							}
					}
					
				} else { cancelarBusca(); }
			});
		});
		
		var CurrentImage = 0;
		var CurrentVideo = 0;
		var preventOpen = false;
		var CurrentImovelSid = null;
		function InfoImovel(sid) {
			if (preventOpen) { preventOpen = false; return; }
			window.location.hash = 'Imovel-' + sid;
			CurrentImovelSid = sid;
			ShowLoading();
			$.ajax({
				url: 'imovelajax/' + sid,
				dataType: 'json',
				cache: false,
				success: function(data) {
					if (CurrentImovelSid == sid) {
						HideLoading();
						Html = '<div style="padding: 10px;" id="VoltarBusca"><a href="javascript:;" onclick="VoltarBusca()">Voltar para a busca</a></div>';
						$('#ImovelInfo').html(Html + data.html);
						$("#SearchResults").hide();
						$("#ImovelInfo").show();
						$("#Content").hide();
						$("#ImovelContent").show();
						//$('#Content').html(Html + data.html);					
						//$("#SearchResults").hide(function() {
						//	$("#Content").show();
						//	$(this).css('display', 'none');
						//});
					}
				}
			});
			return;
			
			//var Imovel = null;
			//for (var i in Imb.Venda.imoveis) {
			//	if (Imb.Venda.imoveis[i].sid == sid) { Imovel = Imb.Venda.imoveis[i]; break; }
			//}
			//if (Imovel == null) {
			//	for (var i in Imb.Aluguel.imoveis) {
			//		if (Imb.Aluguel.imoveis[i].sid == sid) { Imovel = Imb.Aluguel.imoveis[i]; break; }
			//	}
			//}
			//if (Imovel == null) {
			//	return;
			//}
			//
			//CurrentImage = 0;
			//
			//CurrentImovelSid = Imovel.sid;
			//
			//$(document.body).css({ overflow: 'hidden' });
			//var Comodidades = '';
			//$.each(getComodidades(Imovel), function(i, item) { Comodidades += '<span style="width: 180px; padding-bottom: 3px; display: inline-block;">' + item + '</span>'; });
			//
			//var Fotos = Array();
			//for (var i in Imovel.fotos) {
			//	Fotos[Fotos.length] = '<img class="ImagemImovel Img' + i + '" ' + (i > 0 ? 'style="display: none;"' : '') + ' src="imagem/' + Imovel.fotos[i] + '/View" />';
			//}
			//if (Fotos.length == 0) {
			//	Fotos[Fotos.length] = '<img class="ImagemImovel Img0" src="imagens/semfoto_grande.png" />';
			//}
            //
			//var Videos = Array();
			//for (var i in Imovel.videos) {
			//	Videos[Videos.length] = '<iframe class="Video' + i + '" ' + (i > 0 ? 'style="display: none;"' : '') + ' title="YouTube video player" width="358" height="200" src="http://www.youtube.com/embed/' + Imovel.videos[i] + '?wmode=transparent" frameborder="0" allowfullscreen></iframe>';
			//}
			//
			//var Html = '\
			//	<div style="padding: 10px;">\
			//		<div id="MenuFoto" style="position: relative; padding: 16px; display: inline-block; background: url(imagens/big_frame.png) no-repeat; width: 356px; height: 198px;">\
			//			<div id="MenuMapa" style="cursor: pointer; position: absolute; top: 25px; right: 25px; background: #FFF; font-size: 11px; -moz-border-radius: 2px; border: 1px solid #AAA; z-index: 1000000;">\
			//				<div id="aFotos" onclick="ChangeToFotos()" class="active" style="float: left; padding: 3px 10px 3px 10px;">Fotos</div>\
			//				' + (Videos.length == 0 ? '' : '<div id="aVideos" onclick="ChangeToVideos()" style="float: left; padding: 3px 10px 3px 10px;">Vídeos</div>') + '\
			//				' + (Imovel.geoposicionamento.lat == null ? '' :  '<div id="aMapa" onclick="ChangeToMapa()" style="float: left; padding: 3px 10px 3px 10px;">Mapa</div>') + '\
			//			</div>\
			//			<div id="Fotos">\
			//				<div id="NP" style="width: 358px; position: absolute; bottom: 25px; display: none;">\
			//					<img class="tHover" title="Foto anterior" id="btnImagemAnterior" src="imagens/prev_white.png" onclick="ImagemAnterior()" style="display: none; cursor: pointer; padding-left: 10px; float: left;" />\
			//					<img class="tHover" title="Próxima foto" id="btnProximaImagem" src="imagens/next_white.png" onclick="ProximaImagem()" style="cursor: pointer; padding-right: 10px; float: right;" />\
			//				</div>\
			//				' + Fotos.join('') + '\
			//			</div>\
			//			' + (Videos.length == 0 ? '' : '\
			//			<div id="Videos" style="text-align: center; display: none;">\
			//				<div id="NP" style="width: 358px; position: absolute; bottom: 95px; display: none;">\
			//					<img class="tHover" title="Vídeo anterior" id="btnVideoAnterior" src="imagens/prev_white.png" onclick="VideoAnterior()" style="display: none; cursor: pointer; padding-left: 10px; float: left;" />\
			//					<img class="tHover" title="Próximo video" id="btnProximoVideo" src="imagens/next_white.png" onclick="ProximoVideo()" style="cursor: pointer; padding-right: 10px; float: right;" />\
			//				</div>\
			//				' + Videos.join('') + '\
			//			</div>') + '\
			//			<div id="MapaImovel" style="display: none; height: 198px; width: 356px;"></div>\
			//		</div>\
			//		<div style="display: none; vertical-align: top; padding: 10px; width: 380px; font-size: 11px;" id="Indicar">\
			//			<div style="padding-bottom: 5px;"><b>Seu nome</b></div>\
			//			<div style="padding-bottom: 5px;"><input type="text" name="indicar_seunome" style="width: 370px;" /></div>\
			//			<div style="padding-bottom: 5px;"><b>E-mail da pessoa</b><span id="IndicarErro" style="display: none; color: #D62752; margin-left: 10px; font-size: 11px;">Preencha o email corretamente</span></div>\
			//			<div style="padding-bottom: 5px;"><input type="text" name="indicar_email" style="width: 370px;" /></div>\
			//			<div style="padding-bottom: 5px;">Nome da pessoa</div>\
			//			<div style="padding-bottom: 5px;"><input type="text" name="indicar_nome" style="width: 370px;" /></div>\
			//			<div style="padding-bottom: 5px;">Mensagem</div>\
			//			<div style="padding-bottom: 10px;"><textarea name="indicar_mensagem" style="width: 370px; height: 30px;"></textarea></div>\
			//			<div style="text-align: right;"><a href="javascript:void(0)" onclick="IndicarFechar()" style="margin-right: 15px;">Cancelar</a><a href="javascript:void(0)" onclick="EnviarIndicacao()">Enviar indicação</a></div>\
			//		</div>\
			//		<div style="font-size: 11px; display: inline-block; vertical-align: top; padding: 10px; width: 380px;" id="InfoImovelX">\
			//			<span style="float: right; font-size: 11px;" id="Icones">\
			//				<div style="text-align: right;">\
			//					<span onmouseover="$(\'span\', this).stop(true, false).animate({ width: 50 });" onmouseout="$(\'span\', this).stop(true, false).animate({ width: 1 });" onclick="window.print()" style="cursor: pointer; display: inline-block; margin-right: 5px;"><span style="display: inline-block; margin-right: 5px; vertical-align: top; padding-top: 2px; width: 1px; overflow: hidden;">&nbsp;Imprimir</span><img src="imagens/imprimir.png" /></span>\
			//					<span onclick="IndicarAbrir()" onmouseover="$(\'span\', this).stop(true, false).animate({ width: 40 });" onmouseout="$(\'span\', this).stop(true, false).animate({ width: 1 });" style="cursor: pointer; display: inline-block; margin-right: 5px;"><span style="display: inline-block; margin-right: 5px; vertical-align: top; padding-top: 2px; width: 1px; overflow: hidden;">&nbsp;Indicar</span><img src="imagens/indicar.png" /></span>\
			//					<span onclick="Favoritos.toggle(\'' + Imovel.sid + '\', $(\'img\', this))" onmouseover="$(\'span\', this).stop(true, false).animate({ width: 50 });" onmouseout="$(\'span\', this).stop(true, false).animate({ width: 1 });" style="cursor: pointer; display: inline-block; margin-right: 0px;"><span style="display: inline-block; margin-right: 5px; vertical-align: top; padding-top: 2px; width: 1px; overflow: hidden;">&nbsp;Favorito</span><img class="fav' + Imovel.sid + '" src="imagens/favorito' + (Favoritos.find(Imovel.sid) ? '_checked' : '') + '.png" /></span>\
			//				</div>\
			//			</span>\
			//			<span style="font-size: 12px; font-weight: bold;">' + getTipo(Imovel) + '</span>\
			//			<div>' + Imovel.logradouro + '</div>\
			//			<div>' + Imovel.bairro + ' - ' + Imovel.cidade + '</div>\
			//			' + (Imovel.dormitorios > 0 ? '\
			//			<div style="margin-top: 10px; background: #E7E7E7; padding: 8px 8px 8px 10px; -moz-border-radius: 1px;">\
			//				<span style="display: inline-block;">\
			//					' + repeat(Imovel.dormitorios - Imovel.suites, '<img style="margin-right: 5px;" src="imagens/dormitorio.png" />') + '\
			//					' + repeat(Imovel.suites, '<img style="margin-right: 5px;" src="imagens/suite.png" />') + '\
			//				</span>\
			//				<span style="float: right;">' + (Imovel.dormitorios - Imovel.suites > 0 ? (Imovel.dormitorios - Imovel.suites) + ' dormitório' + (Imovel.dormitorios - Imovel.suites > 1 ? 's' : '') : '') + (Imovel.suites > 0 ? (Imovel.dormitorios - Imovel.suites > 0 ? ' e ' : '') + Imovel.suites + ' suíte' + (Imovel.suites > 1 ? 's' : '') : '') + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.banheiros > 0 ? '\
			//			<div style="margin-top: 2px; background: #E7E7E7; padding: 8px 8px 8px 10px; -moz-border-radius: 1px;">\
			//				<span style="display: inline-block;">\
			//					' + repeat(Imovel.banheiros, '<img style="margin-right: 5px;" src="imagens/banheiro.png" />') + '\
			//				</span>\
			//				<span style="float: right;">' + (Imovel.banheiros == 1 ? 'um banheiro' : Imovel.banheiros + ' banheiros') + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.garagens > 0 ? '\
			//			<div style="margin-top: 2px; background: #E7E7E7; padding: 8px 8px 8px 10px; -moz-border-radius: 1px;">\
			//				<span style="display: inline-block;">\
			//					' + repeat(Imovel.garagens, '<img style="margin-right: 5px;" src="imagens/garagem.png" />') + '\
			//				</span>\
			//				<span style="float: right;">' + (Imovel.garagens == 1 ? 'uma garagem' : Imovel.garagens + ' garagens') + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.mobiliado ? '\
			//			<div style="margin-top: 2px; background: #E7E7E7; padding: 8px 8px 8px 10px; -moz-border-radius: 1px;">\
			//				<span style="display: inline-block;">\
			//					<img style="margin-right: 5px;" src="imagens/mobiliado.png" />\
			//				</span>\
			//				<span style="float: right;">imóvel mobiliado</span>\
			//			</div>\
			//			' : '' ) + '\
			//		</div>\
			//	</div>\
			//	<div style="padding: 0px 10px 0px 10px; font-size: 11px;">\
			//		<div style="float: left; width: 366px; padding: 11px;">\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Finalidade</b></span>\
			//				<span>' + Imovel.subtipo + '</span>\
			//			</div>\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Contrato</b></span>\
			//				<span>' + Imovel.contrato + '</span>\
			//			</div>\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Tipo de construção</b></span>\
			//				<span>' + Imovel.tipo_construcao + '</span>\
			//			</div>\
			//			' + (Imovel.area_total ? '\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Área total</b></span>\
			//				<span>' + Imovel.area_total + ' m²</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.area_privativa ? '\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Área privativa</b></span>\
			//				<span>' + Imovel.area_privativa + ' m²</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.comprimento ? '\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Comprimento</b></span>\
			//				<span>' + Imovel.comprimento + ' m</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.largura ? '\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Largura</b></span>\
			//				<span>' + Imovel.largura + ' m</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.ano_imovel ? '\
			//			<div style="margin-bottom: 5px;">\
			//				<span style="float: left; display: inline-block; width: 130px;"><b>Ano de construção</b></span>\
			//				<span>' + Imovel.ano_imovel + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//		</div>\
			//		<div style="width: 380px; float: left; padding: 0px 16px 10px 16px;">\
			//			<div style="margin-bottom: 10px;">\
			//				<b>Código</b>\
			//				<span style="float: right">' + Imovel.codigo + '</span>\
			//			</div>\
			//			' + (Imovel.valor_de_venda > 0 ? '\
			//			<div style="margin-bottom: 10px;">\
			//				<b>Valor de venda</b>\
			//				<span style="float: right">R$ ' + formatCurrency(Imovel.valor_de_venda) + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.valor_de_aluguel > 0 ? '\
			//			<div style="margin-bottom: 10px;">\
			//				<b>Valor de aluguel</b>\
			//				<span style="float: right">R$ ' + formatCurrency(Imovel.valor_de_aluguel) + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.iptu > 0 ? '\
			//			<div style="margin-bottom: 10px;">\
			//				<span><b>Valor IPTU</b></span>\
			//				<span style="float: right;">R$ ' + formatCurrency(Imovel.iptu) + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.condominio > 0 ? '\
			//			<div style="margin-bottom: 10px;">\
			//				<span><b>Valor do condomínio</b></span>\
			//				<span style="float: right;">R$ ' + formatCurrency(Imovel.condominio) + '</span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Imovel.aceita_financiamento ? '\
			//			<div style="margin-bottom: 10px;">\
			//				<span><b>Aceita financiamento</b></span>\
			//			</div>\
			//			' : '' ) + '\
			//			' + (Comodidades != '' ? '<div style="margin-top: 20px;">\
			//				<div style="padding-bottom: 3px;"><b>Comodidades</b></div>\
			//				' + Comodidades + '\
			//			</div>' : '') + '\
			//		</div>\
			//	</div>\
			//';
			//
			//DefinePrint(Imovel, Fotos, Comodidades);
			//$("#ImovelContent").html(Html);
			//
			//if (Fotos.length <= 1) { $("#btnProximaImagem").hide(); }
			//
			//$("#MenuMapa").css({ opacity: 0.8 });
			//$("#MenuMapa").hover(function() { $(this).stop(true, false).animate({ opacity: 1 }); }, function() { $(this).stop(true, false).animate({ opacity: 0.8 }); });
            //
			//$(".tHover").css({ opacity: 0.3 });
			//$(".tHover").hover(function() { $(this).stop(true, false).animate({ opacity: 1 }); }, function() { $(this).stop(true, false).animate({ opacity: 0.3 }); });
			//
			//$("#Fotos #NP").hide();
			//$("#Fotos #NP").hide();
			//$("#Fotos").hover(function() { $("#Fotos > #NP").stop(true, true).fadeIn(); }, function() { $("#Fotos > #NP").stop(true, true).fadeOut(); });
			//$("#Videos").hover(function() { $("#Videos > #NP").stop(true, true).fadeIn(); }, function() { $("#Videos > #NP").stop(true, true).fadeOut(); });
            //
			////$("#InfoImovel > div").css({
			////	top: ($("#InfoImovel").height() / 2) - ($("#InfoImovel > div").height() / 2),
			////	left: ($("#InfoImovel").width() / 2) - ($("#InfoImovel > div").width() / 2),
			////	display: 'none'
			////});
			//$("#InfoImovel").css('z-index', 100000).fadeIn(200, function() {
			//	$("#InfoImovel > div").fadeIn(200, function() {
			//		// Mapa
			//		CreateMap();
			//		if (Imovel.geoposicionamento.lat && Imovel.geoposicionamento.lng) {
			//			Marker.setPosition(new google.maps.LatLng(Imovel.geoposicionamento.lat, Imovel.geoposicionamento.lng));
			//			google.maps.event.addListener(Map, "resize", function() { Map.setCenter(Marker.getPosition()); });
			//		}
			//	});
			//});
			
		}
		
		function CloseInfoImovel() {
			$('#InfoImovel > div').fadeOut(function() { $('#InfoImovel').fadeOut(function() { $(document.body).css({ overflow: 'auto' }); }); });			
		}
		
		function DefinePrint(Imovel, Fotos, Comodidades) {
			$(".printTipo").html(getTipo(Imovel));
			$(".printLogradouro").html(Imovel.logradouro);
			$(".printLocal").html(Imovel.bairro + ' - ' + Imovel.cidade);
			
			$(".printDormitorio > .icons").html(repeat(Imovel.dormitorios, '<img style="margin-right: 5px;" src="imagens/print/dormitorio.png" />'));
			$(".printDormitorio > .text").html((Imovel.dormitorios - Imovel.suites > 0 ? (Imovel.dormitorios - Imovel.suites) + ' dormitório' + (Imovel.dormitorios - Imovel.suites > 1 ? 's' : '') : '') + (Imovel.suites > 0 ? (Imovel.dormitorios - Imovel.suites > 0 ? ' e ' : '') + Imovel.suites + ' suíte' + (Imovel.suites > 1 ? 's' : '') : ''));
			if (Imovel.dormitorios <= 0) { $(".printDormitorio").hide(); }

			$(".printBanheiro > .icons").html(repeat(Imovel.banheiros, '<img style="margin-right: 5px;" src="imagens/print/banheiro.png" />'));
			$(".printBanheiro > .text").html((Imovel.banheiros == 1 ? 'um banheiro' : Imovel.banheiros + ' banheiros'));
			if (Imovel.banheiros <= 0) { $(".printBanheiro").hide(); }

			$(".printGaragem > .icons").html(repeat(Imovel.garagens, '<img style="margin-right: 5px;" src="imagens/print/garagem.png" />'));
			$(".printGaragem > .text").html((Imovel.garagens == 1 ? 'uma garagem' : Imovel.garagens + ' garagens'));
			if (Imovel.garagens <= 0) { $(".printGaragem").hide(); }
			
			if (!Imovel.mobiliado) { $(".printMobiliado").hide(); }
			else { $(".printMobiliado").show(); }
			
			$(".printFinalidade > span").html(getFinalidade(Imovel));
			$(".printContrato > span").html(getContrato(Imovel));
			$(".printConstrucao > span").html(getConstrucao(Imovel));
			$(".printSituacao > span").html(getSituacao(Imovel));
			if (Imovel.situacao_financeira != '') { $(".printFinanceira > span").html(Imovel.situacao_financeira); } else { $(".printFinanceira").hide(); }
			if (Imovel.area_total > 0) { $(".printAreaTotal > span").html(Imovel.area_total + ' m²'); } else { $(".printAreaTotal").hide(); }
			if (Imovel.area_privativa > 0) { $(".printAreaPrivativa > span").html(Imovel.area_privativa + 'm²'); } else { $(".printAreaPrivativa").hide(); }
			if (Imovel.ano_imovel > 0) { $(".printAnoConstrucao > span").html(Imovel.ano_imovel); } else { $(".printAnoConstrucao").hide(); }
			
			if (Imovel.valor_de_venda > 0) { $(".printValorVenda > span").html('R$ ' + Imovel.valor_de_venda); } else { $(".printValorVenda").hide(); }
			if (Imovel.valor_de_aluguel > 0) { $(".printValorAluguel > span").html('R$ ' + Imovel.valor_de_aluguel); } else { $(".printValorAluguel").hide(); }
			if (Imovel.iptu > 0) { $(".printValorIptu > span").html('R$ ' + Imovel.iptu); } else { $(".printValorIptu").hide(); }
			if (Imovel.condominio > 0) { $(".printValorCondominio > span").html('R$ ' + Imovel.condominio); } else { $(".printValorCondominio").hide(); }
			if (!Imovel.aceita_financiamento) { $(".printFinanciamento").hide(); }
			
			if (Comodidades != '') { $(".printComodidadesText").html(Comodidades); } else { $(".printComodidades").hide(); }

			if (Imovel.fotos.length > 0) {
				$(".printFoto").show();
				$(".printImage").html('<img src="imagem/' + Imovel.fotos[0] + '/View" />');		
			} else { $(".printFoto").hide(); }
		}
		
		var UsarFiltrosExtras = false;
		function MaisOpcoes() {
			if (UsarFiltrosExtras) {
				$("#BuscaAvancada").slideUp();
				$("#tMaisOpcoes").html("+ opções de filtro");
				UsarFiltrosExtras = false;
				UpdateResults(false);
			} else {
				$("#BuscaAvancada").slideDown();
				$("#tMaisOpcoes").html("- Limpar opções extras");
				$("#BuscaAvancada input").attr("checked", false);
				UpdateCheckbox();
				UsarFiltrosExtras = true;
			}			
		}
		
		
		var MapType = 0;
		function ChangeMap(t) {
			if (t != MapType) {
				$("#LinkLista,#LinkMapa").removeClass('active');
				if (t == 1) {
					UpdateMapa();
					$("#LinkMapa").addClass('active');
					//$("#ImgResultados").attr('src', 'imagens/abas/resultados.png');
					//$("#ImgMapa").attr('src', 'imagens/abas/resultados_mapa_atual.png');
				} else {
					$("#LinkLista").addClass('active');
					$("#ResultadosMapa").hide();
					$("#Imoveis").show();
					//$("#ImgResultados").attr('src', 'imagens/abas/resultados_atual.png');
					//$("#ImgMapa").attr('src', 'imagens/abas/resultados_mapa.png');
				}
				MapType = t;
			}
		}
		
		var rMap = null;
		var MapaLoaded = false;
		var Markers = Array();
		var InfoWindow = null;
		function UpdateMapa() {
			$("#MapaLoading").fadeIn(100);
			if (!MapaLoaded) {
				var opt = {
					zoom: 15,
					center: new google.maps.LatLng(0, 0),
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					mapTypeControl: false,
					panControl: false,
					scaleControl: false,
					streetViewControl: false,
					zoomControl: false,
					noClear: true
				};
				rMap = new google.maps.Map(document.getElementById("MapaResultados"), opt);
				MapaLoaded = true;
				InfoWindow = new google.maps.InfoWindow();
				try { UpdateProximidades(); } catch (e) { }
			}
			
			for (var i in Markers) { Markers[i].setMap(null); }
			Markers = Array();
			
			$("#Imoveis").hide();
			$("#ResultadosMapa").show();

			if (ImoveisMapa.getLength() == 0) { $("#MapaNenhumResultado").show(); $("#MapaLoading").hide(); }
			else {
				for (var i =0; i < ImoveisMapa.getLength(); i++) {
					var NewMarker = new google.maps.Marker({
						draggable: false,
						flat: false,
						position: ImoveisMapa.getAt(i).pos,
						title: 'Localização do imóvel',
						map: rMap
					});
					NewMarker.ImovelId = ImoveisMapa.getAt(i).sid;
					google.maps.event.addListener(NewMarker, "click", function() {
						//InfoImovel(this.ImovelId);		
						Imovel = Imobiliario.Imoveis[this.ImovelId];
						
						var Html = '\
							<a href="javascript:;" onclick="InfoImovel(\'' + this.ImovelId + '\');"><img src="' + Imovel.imagem_capa + '" /></a>\
							<div class="inblock" style="vertical-align: top">\
								<div><b>' + Imovel.tipo + (Imovel.subtipo != '' ? ' - ' + Imovel.subtipo : Imovel.subtipo) + '</b></div>\
								<div>' + Imovel.endereco_cidade + '</div>\
								<div>' + Imovel.endereco_bairro + '</div>\
								' + (Imovel.valor_venda > 0 ? '<div>Valor de venda: R$ ' + formatCurrency(Imovel.valor_venda) + '</div>' : '') + '\
								' + (Imovel.valor_locacao > 0 ? '<div>Valor de aluguel: R$ ' + formatCurrency(Imovel.valor_locacao) + '</div>' : '') + '\
							</div>\
						';
						InfoWindow.setContent(Html);
						InfoWindow.open(rMap, this);
					});
					Markers[Markers.length] = NewMarker;
					
				}

				google.maps.event.trigger(rMap, 'resize');
				setTimeout(function() {
					google.maps.event.trigger(rMap, 'resize');
					FitToPath(rMap, ImoveisMapa);
					$("#MapaLoading").fadeOut(100);
				}, 500);
				$("#MapaNenhumResultado").hide();
			}
		}
		
function FitToPath(Map, Path) {
    if (Map && (Path.getLength() > 0)) {
        var North, South, East, West;
        North = 0;
        South = 0;
        East = 0;

        for (var i = 0; i < Path.getLength(); i++) {
            if (i == 0) {
                North = Path.getAt(i).pos.lat();
                South = Path.getAt(i).pos.lat();
                East = Path.getAt(i).pos.lng();
                West = Path.getAt(i).pos.lng();

            }
            if (Path.getAt(i).pos.lat() > North) { North = Path.getAt(i).pos.lat(); }
            if (Path.getAt(i).pos.lat() < South) { South = Path.getAt(i).pos.lat(); }
            if (Path.getAt(i).pos.lng() > East) { East = Path.getAt(i).pos.lng(); }
            if (Path.getAt(i).pos.lng() < West) { West = Path.getAt(i).pos.lng(); }
        }

        if (Path.getLength() > 0) {
            var sw = new google.maps.LatLng(South, West);
            var ne = new google.maps.LatLng(North, East);
            Map.fitBounds(new google.maps.LatLngBounds(sw, ne));
        }
    }
}		

function IndicarAbrir() {
	$("input,textarea", "#Indicar").val('');
	$('#InfoImovelX').fadeOut(function() { $('#Indicar').css({ display: 'inline-block' }).fadeIn(function() { $('input[name=indicar_seunome]').focus(); }); });
	$('#IndicarErro').hide();
}

function IndicarFechar() {
	$('#Indicar').fadeOut(function() { $('#InfoImovelX').css({ display: 'inline-block' }).fadeIn(); });
}

function EnviarIndicacao() {
	$("#IndicarErro").hide();
	if ($('input[name=indicar_email]').val() == '') { $("#IndicarErro").fadeIn(function() { $('input[name=indicar_email]').focus(); }); }
	else {
		$.ajax({
			url: 'indicar/' + CurrentImovelSid + '/',
			dataType: 'json',
			cache: false,
			type: 'POST',
			data: { email: $('input[name=indicar_email]').val(), nome: $('input[name=indicar_nome]').val(), mensagem: $('input[name=indicar_mensagem]').val() },
			success: function(data) {
				if (data.success) {
					IndicarFechar();
					alert('Indicação enviada com sucesso.');
				} else { alert(data.error); }
			},
			error: function () {
				alert('Um erro ocorreu, tente novamente.');
			}
		});
	}
	
}

function cancelarBusca() {
	if (BuscaTipo > -1) {
		if (typeof(StartBanner) != 'undefined' && $("#Banners").length > 0) { StartBanner(); }
		ResultsCheck = null;
		if (typeof(imovelPrint) != 'undefined') { imovelPrint(); }
		if ($("#SearchResults").is(':visible')) {
			$("#SearchResults").slideUp(function() {
				$("#ImovelContent").hide();
				$("#Content").slideDown();
				$(this).css('display', 'none');
			});
		} else {
			$("#ImovelInfo").hide();
			$("#SearchResults").hide(function() { $(this).css('display', 'none'); });
			$("#ImovelContent").hide();
			$("#Content").show();
		}
		$("#BuscaImoveis").slideUp(function() {
			$("#TiposImoveis,#Finalidades").hide().html('');
			$("#BuscaFacil").slideDown();
		});
		
		$("#BuscaVenda").css('background-position', '0px 0px');
		$("#BuscaAluguel").css('background-position', '-109px 0px');
		BuscaTipo = -1;
		
		$("#VoltarBusca").hide();
	}
}

		function mostrarFavoritos() {
			window.location.hash = 'Favoritos';
			if (typeof(StartBanner) != 'undefined') { StopBanner(); }
			var OldRC = ResultsCheck;
			ResultsCheck = '';

			var Html = '';
			var Resultados = 0;
			var ResultadosReais = 0;
			
			if (!ImoveisMapa) { ImoveisMapa = new google.maps.MVCArray(); }
			ImoveisMapa.clear();
			
			for (var k in Favoritos.list) {
				var found = false;
				for (var i in Imobiliario.Imoveis) {
					var Imovel = Imovel;
					if (Imobiliario.Imoveis[i].sid == Favoritos.list[k]) {
						var ImovelId = Imobiliario.Imoveis[i].sid;
						var Pos = { sid: ImovelId, pos: new google.maps.LatLng(Imobiliario.Imoveis[i].geoposicionamento.lat, Imobiliario.Imoveis[i].geoposicionamento.lng) }; 
						ImoveisMapa.push(Pos);
						Html += HtmlResultado(Imobiliario.Imoveis[i], i);
						ResultsCheck += Imobiliario.Imoveis[i].sid;
						Resultados++;
						ResultadosReais++;
						found = true;
						break;
					}
				}
			}
			
			Html = '<div style="background: #ffc8cb; color: #000; padding: 5px 10px 5px 10px; margin-bottom: 5px; margin-top: 5px; font-size: 11px;"><span style="float: right; padding-top: 2px;"><a style="color: #000" href="javascript:cancelarBusca()">Voltar</a></span><img style="vertical-align: middle;" src="imagens/favorito_checked.png" /><span style="vertical-align: middle;margin-left: 10px; display: inline-block;">Imóveis favoritos</span></div>' + Html;
			if (ResultadosReais == 0) {
				Html += '<div style="padding: 10px;"><em>Nenhum imóvel adicionado aos favoritos</em></div>';
			}
			
			//if (OldRC != ResultsCheck) {
				$("#Content").slideUp(function() {
					$("#ImovelContent").show();
					$("#Imoveis").fadeOut(100, function() {
						$("#Imoveis").html(Html);
						$(".Imovel [title]").tooltip({ position: "bottom center", opacity: 0.9 });
						$("#SearchResults").slideDown(function() {
							$("#Imoveis").fadeIn(100); 
							$(this).css('display', 'block');
						});
					});
				});
				
				if (MapType == 1) { UpdateMapa(); }
			//}
			$("#Filtros").hide();
			
			// Cancela busca
			$("#ImovelInfo").slideUp(100);
			$("#BuscaImoveis").slideUp(function() {
				$("#TiposImoveis,#Finalidades").hide().html('');
				$("#BuscaFacil").slideDown();
			});
			if (typeof(imovelPrint) != 'undefined') { imovelPrint(); }
			$("#BuscaVenda").css('background-position', '0px 0px');
			$("#BuscaAluguel").css('background-position', '-109px 0px');
			BuscaTipo = 3;
		}
		
		var ImovelBuscaCodigo = null;
		function buscarCodigo(oldCod) {
			if (typeof(oldCod) != 'undefined' && oldCod && ImovelBuscaCodigo != null) {
				cod = ImovelBuscaCodigo;
			} else {
				var cod = $('input[name=codigo]').val().replace(/\D/g, '');
			}
			if (!(cod > 0)) { return; }

			if (typeof(StartBanner) != 'undefined') { StopBanner(); }
			ResultsCheck = null;
			
			ImovelBuscaCodigo = cod;
			window.location.hash = 'Busca';
			
			$('input[name=codigo]').val('');
			$("#BuscaCodigo").css('background-position', 'center bottom');
			setTimeout(function() { $("#BuscaCodigo").css('background-position', 'center top'); }, 300);
			
			var OldRC = ResultsCheck;
			ResultsCheck = '';

			var Html = '';
			var Resultados = 0;
			var ResultadosReais = 0;
			
			if (!ImoveisMapa) { ImoveisMapa = new google.maps.MVCArray(); }
			ImoveisMapa.clear();
			
			var ImoveisEncontrados = Array();
			
			var found = false;
			for (var i in Imobiliario.Imoveis) {
				if (Imobiliario.Imoveis[i].codigo.indexOf(cod) > -1) {
					var ImovelId = Imobiliario.Imoveis[i].sid;
					var Pos = { sid: ImovelId, pos: new google.maps.LatLng(Imobiliario.Imoveis[i].geoposicionamento.lat, Imobiliario.Imoveis[i].geoposicionamento.lng) }; 
					ImoveisMapa.push(Pos);
					Html += HtmlResultado(Imobiliario.Imoveis[i], i);
					ResultsCheck += Imobiliario.Imoveis[i].sid;
					Resultados++;
					ResultadosReais++;
					ImoveisEncontrados[ImoveisEncontrados.length] = Imobiliario.Imoveis[i].sid;
				}
			}
			
			Html = '<div style="background: #ffc8cb; color: #000; padding: 5px 10px 5px 10px; margin-bottom: 5px; margin-top: 5px; font-size: 11px;"><span style="float: right;"><a style="color: #000" href="javascript:cancelarBusca()">Voltar</a></span>' + (ResultadosReais == 0 ? 'Nenhum imóvel encontrado' : (ResultadosReais == 1 ? 'Um imóvel encontrado' : '<b>' + ResultadosReais + '</b> imóveis encontrados' )) + '</div>' + Html;
			
			//if (OldRC != ResultsCheck) {
				$("#Content").slideUp(function() {
					$("#ImovelContent").show();
					$("#Imoveis").fadeOut(100, function() {
						$("#Imoveis").html(Html);
						$(".Imovel [title]").tooltip({ position: "bottom center", opacity: 0.9 });
						$("#SearchResults").slideDown(function() {
							$("#Imoveis").fadeIn(100); 
							$(this).css('display', 'block');
						});
					});
				});
				
				if (MapType == 1) { UpdateMapa(); }
			//}
			$("#Filtros").hide();
			
			// Cancela busca
			$("#ImovelInfo").slideUp(100);
			$("#BuscaImoveis").slideUp(function() {
				$("#TiposImoveis,#Finalidades").hide().html('');
				$("#BuscaFacil").slideDown();
			});
			if (typeof(imovelPrint) != 'undefined') { imovelPrint(); }
			$("#BuscaVenda").css('background-position', '0px 0px');
			$("#BuscaAluguel").css('background-position', '-109px 0px');
			BuscaTipo = 2;
			ResultsCheck = null;
		}


