var s = null;
$(function() {
	$(".submenu").each(function() {
		$(this).mouseover(function() {
			clearTimeout(s);
			//$('.submenu div').stop(true, true).slideUp();
			$('div', this).stop(true, true).slideDown();
		}).mouseout(function() {
			var $x = $('div', this);
			clearTimeout(s);
			s = setTimeout(function() { $('.submenu div').stop(true, true).slideUp(); }, 500);
		});
	});
});
function AbrirChat() {
	window.open ("chat/", "imobiliaria", "menubar=0,resizable=1,width=800,height=320");
}

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).getPosition().lat();
				South = Path.getAt(i).getPosition().lat();
				East = Path.getAt(i).getPosition().lng();
				West = Path.getAt(i).getPosition().lng();

			}
			if (Path.getAt(i).getPosition().lat() > North) { North = Path.getAt(i).getPosition().lat(); }
			if (Path.getAt(i).getPosition().lat() < South) { South = Path.getAt(i).getPosition().lat(); }
			if (Path.getAt(i).getPosition().lng() > East) { East = Path.getAt(i).getPosition().lng(); }
			if (Path.getAt(i).getPosition().lng() < West) { West = Path.getAt(i).getPosition().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 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');
	}
}	

/* Busca */
var Busca = {
	LastSearchHash: '',
	Etapa: 0,
	PreventShow: false,
	ShowPath: Array(),
	Feedback: '#ffffff',
	CodigoImobiliaria: '',
	
	Path: {
		List: Array(),
		
		Find: function(a) {
			for (var i in Busca.Path.List) {
				if (Busca.Path.List[i] == a) { return true; }
			}
			return false;
		},
		
		Remove: function(a) {
			var newArray = Array();
			for (var i in Busca.Path.List) {
				if (Busca.Path.List[i] != a) { newArray[newArray.length] = Busca.Path.List[i]; }
			}
			Busca.Path.List = newArray;
		},
		
		Add: function (a) {
			Busca.Path.Remove(a);
			Busca.Path.List[Busca.Path.List.length] = a;
		},
		
		Pop: function() {
			var a = Busca.Path.List[Busca.Path.List.length-1];
			Busca.Path.Remove(a);
			return a;
		},
		
		Last: function() {
			return Busca.Path.List[Busca.Path.List.length-1];
		}
	},
	
	AddPath: function(a) {
		
	},

	
	Tipos: {
		Locacao: Array(),
		Compra: Array()
	},
	
	Subtipos: {
		Locacao: Array(),
		Compra: Array()
	},
	
	Imoveis: Array(),
	_findImovel: function(codigo) {
		for (var i in Busca.Imoveis) {
			if (Busca.Imoveis[i].Codigo == codigo) { return Busca.Imoveis[i]; }
		}
		return null;
	},
	
	Filtros: {
		Contrato: "Nenhum",
		Tipos: [],
		Subtipos: [],
		ToggleTipo: function(tipo) {
			if ($.inArray(tipo, Busca.Filtros.Tipos) > -1) {
				Busca.Filtros.Tipos.splice( $.inArray(tipo, Busca.Filtros.Tipos), 1 );
				$("#tipo" + tipo).attr('src', 'imagens/checkbox_inativo.png');
			} else {
				Busca.Filtros.Tipos.push(tipo);
				$("#tipo" + tipo).attr('src', 'imagens/checkbox_ativo.png');
			}
			if (Busca.Subtipos[Busca.Filtros.Contrato][Busca.Tipos[Busca.Filtros.Contrato][tipo]].length > 0) {
				if (Busca.Etapa > 1) { Busca.MostrarImoveis(true); }
				Busca.MostrarSubtipos();
			}
			else { Busca.MostrarImoveis(true); }
		},
		ToggleSubtipo: function(subtipo) {
			if ($.inArray(subtipo, Busca.Filtros.Subtipos) > -1) {
				Busca.Filtros.Subtipos.splice( $.inArray(subtipo, Busca.Filtros.Subtipos), 1 );
				$("#subtipo" + subtipo).attr('src', 'imagens/checkbox_inativo.png');
			} else {
				Busca.Filtros.Subtipos.push(subtipo);
				$("#subtipo" + subtipo).attr('src', 'imagens/checkbox_ativo.png');
			}
			
			//if (Busca.Filtros.Subtipos.length > 0) {
				Busca.MostrarImoveis(true);
			//}
		}				
	},
	
	DefinirTipo: function(t, o) {
		if (Busca.Filtros.Contrato == t) { return; }
		
		window.location.hash = 'Busca';
		
		$("#mobiliado,#alto_padrao,#financiavel").attr('checked', false);
		$("#comodidades input").attr('checked', false);

		$("#MenuContrato > a").removeClass('active');
		$(o).addClass('active');
		Busca.Filtros.Contrato = t;
		if (Busca.Etapa == 0) {
			Busca.Etapa = 1;
			$("#MenuInfo").animate({ width: 0 }, 500);
			$("#MenuContrato").animate({ left: 18 }, 500);
			$("#MenuSeta").animate({ left: 0 }, 500, function() {
				$(this).animate({ left: 100 }, function() { Busca.MostrarTipos(); });
				$("#MenuContrato").animate({ left: 0 });
			});
			$("#FiltrosExtras").slideUp();
		} else {
			Busca.Etapa = 1;
			Busca.Filtros.Tipos = [];
			Busca.Filtros.Subtipos = [];
			Busca.MostrarSubtipos();
			Busca.MostrarTipos();
			$("#FiltrosExtras").slideUp();
		}
	},
	
	MostrarTipos: function() {
		var html = '<div style="float: left; margin-right: 10px;">';
		var count = 0;
		for (var i in Busca.Tipos[Busca.Filtros.Contrato]) {
			html += '\
				<div style="cursor: default; margin: 5px 0px;" onclick="Busca.Filtros.ToggleTipo(' + i + ');">\
					<img id="tipo' + i + '" src="imagens/checkbox_inativo.png" style="vertical-align: middle;" /><span style="margin-left: 5px; vertical-align: middle;">' + Busca.Tipos[Busca.Filtros.Contrato][i] + '</span>\
				</div>\
			';
			count++;
			if (count%4 == 0) { html += '</div><div style="float: left; margin-right: 10px;">'; }
		}
		html += '</div>';
		$("#MenuTipos").html(html).show();
		$("#MenuTipos > div").hide();
		$("#MenuTipos > div").each(function(i, item) {
			setTimeout(function() { $(item).stop(true, false).fadeIn(); }, i * 200);
		});
	},
	
	MostrarSubtipos: function() {
		var html = '<div style="float: left; margin-right: 10px;">';
		var count = 0;
		var subTipos = Array();
		for (var i in Busca.Filtros.Tipos) {
			for (var j in Busca.Subtipos[Busca.Filtros.Contrato][Busca.Tipos[Busca.Filtros.Contrato][Busca.Filtros.Tipos[i]]]) {
				if ($.inArray(Busca.Subtipos[Busca.Filtros.Contrato][Busca.Tipos[Busca.Filtros.Contrato][Busca.Filtros.Tipos[i]]][j], subTipos) < 0) {
					var t = $.inArray(Busca.Tipos[Busca.Filtros.Contrato][Busca.Filtros.Tipos[i]], Busca.Tipos[Busca.Filtros.Contrato]);
					html += '\
						<div style="cursor: default; margin: 5px 0px;" onclick="Busca.Filtros.ToggleSubtipo(\'' + t + '-' + j + '\');">\
							<img id="subtipo' + t + '-' + j + '" src="imagens/checkbox_' + ($.inArray(t + '-' + j, Busca.Filtros.Subtipos) > -1 ? 'ativo' : 'inativo') + '.png" style="vertical-align: middle;" /><span style="margin-left: 5px; vertical-align: middle;">' + Busca.Subtipos[Busca.Filtros.Contrato][Busca.Tipos[Busca.Filtros.Contrato][Busca.Filtros.Tipos[i]]][j] + '</span>\
						</div>\
					';
					count++;
					subTipos[subTipos.length] = Busca.Subtipos[Busca.Filtros.Contrato][Busca.Tipos[Busca.Filtros.Contrato][Busca.Filtros.Tipos[i]]][j];
					if (count%4 == 0) { html += '</div><div style="float: left; margin-right: 10px;">'; }
				}
			}
		}
		html += '</div>';
		
		if (Busca.Filtros.Tipos.length == 0) {
			Busca.Etapa = 1;
			$("#MenuSubtipos").fadeOut();
			$("#MenuSetaTipos").animate({ left: 100 }, function() { $(this).hide(); });
		} else if (Busca.Etapa == 1) {
			Busca.Etapa = 2;
			$("#MenuSetaTipos").css({ left: 100 }).show().animate({ left: 100 + 18 + 10 + $("#MenuTipos").width() },
			function() {
				$("#MenuSubtipos").html(html).css({ left: 118 + 18 + 10 + $("#MenuTipos").width() }).show();
				$("#MenuSubtipos > div").hide();
				$("#MenuSubtipos > div").each(function(i, item) {
					setTimeout(function() { $(item).stop(true, false).fadeIn(); }, i * 200);
				});

			});
		} else {
			$("#MenuSubtipos").html(html);
		}
	},
	
	MostrarFavoritos: function() {
		Busca.Path.Add("Favoritos");
		
		var html = '';
		var Results = 0;
		for (var i in Busca.Imoveis) {
			var Imovel = Busca.Imoveis[i];
			if ($.inArray(Imovel.Codigo, Favoritos.List) > -1) {
				html += Busca.getImovelHtml(Imovel);
				Results++;
			}
		}

		$("#Favoritos > .divContent").html(html);
		//$("#Favoritos > .divContent > .Imovel").css({ opacity: 0 });
		$("#conteudo").fadeOut(function() {
			$("#Imoveis > div").hide();
			$("#Favoritos").show();
			$("#Favoritos > .divContent > .Imovel").show();
			//$("#Favoritos > .divContent > .Imovel").each(function(i, item) {
			//	setTimeout(function() {
			//		$(item).stop(true, false).show().animate({ opacity: 1 }, 1000);
			//	}, i * 200);
			//});
			$("#Imoveis").fadeIn();
		});
		
		
		$("#Favoritos > .divContent > .Imovel").hover(function() {
			$(this).stop(true, false).animate({ opacity: 1, backgroundColor: Busca.Feedback });
		}, function() {
			$(this).stop(true, false).animate({ opacity: 1, backgroundColor: '#ffffff' });
		});
		
		if (Results > 0) { 
			$("#Favoritos > .divContent > .Imovel").each(function(i, item) {
				$('[title]', item).each(function() {
					var Title = $(this).attr('title');
					$(this).attr('title', null);
					$(this).hover(function() {
						$("#tooltip").html(Title).show();
						$("#tooltip").css({ zIndex: 1000, left: $(this).offset().left + ($(this).width() / 2) - ($("#tooltip").width() / 2), top: $(this).offset().top + $(this).height() + 10, opacity: 0 }).stop(true, false).animate({ opacity: 0.7 });
					}, function() {
						$("#tooltip").stop(true, false).animate({ opacity: 0 }, function() { $(this).hide(); });
					});
				});
			});
			$("#ImoveisFavoritos").html((Results > 1 ? Results + " imóveis encontrados" : '1 imóvel encontrado'));
		} else {
			$("#Favoritos > .divContent").html('<div style="text-align: center;">Nenhum imóvel encontrado</div>');
			$("#ImoveisFavoritos").html('Nenhum imóvel encontrado');				
		}
		Favoritos.Refresh();
	},

	ImoveisMarkers: null,
	MostrarImoveis: function(AtualizarFiltros) {
		//if (Busca.Etapa >= 1) {
			if (Busca.Etapa == 3) { Busca.Voltar(); }
			
			Busca.Path.Add('Lista');
		
			var Maximas = {
				Valores: { Min: 10000000000, Max: -10000000000 },
				Dormitorios: { Min: 10000000000, Max: -10000000000 },
				Garagens: { Min: 10000000000, Max: -10000000000 },
				Banheiros: { Min: 10000000000, Max: -10000000000 }
			};
			
			var FiltroTipo = Array();
			var FiltroSubtipo = Array();
			for (var i in Busca.Filtros.Tipos) { FiltroTipo.push(Busca.Tipos[Busca.Filtros.Contrato][Busca.Filtros.Tipos[i]]); }
			for (var i in Busca.Filtros.Subtipos) {
				var a = Busca.Filtros.Subtipos[i].split('-');
				FiltroSubtipo[FiltroSubtipo.length] = Busca.Subtipos[Busca.Filtros.Contrato][Busca.Tipos[Busca.Filtros.Contrato][parseInt(a[0])]][parseInt(a[1])];
			}
			
			for (var i =0; i < Busca.ImoveisMarkers.getLength(); i++) { Busca.ImoveisMarkers.getAt(i).setMap(null); }
			Busca.ImoveisMarkers.clear();
			
			var html = '';
			var Results = 0;
			var Hash = '';
			var Comodidades = Array();
			var ResultsImoveis = Array();
			for (var i in Busca.Imoveis) {
				var Imovel = Busca.Imoveis[i];
				var Show = ($.inArray(Busca.Filtros.Contrato, Imovel.Contrato.split(',')) > -1) && ($.inArray(Imovel.Tipo, FiltroTipo) > -1) && (Busca.Subtipos[Busca.Filtros.Contrato][Imovel.Tipo].length == 0 || ($.inArray(Imovel.Subtipo, FiltroSubtipo) > -1));
				if (Show) {
					if (AtualizarFiltros) {
						if (Imovel.Dormitorios > Maximas.Dormitorios.Max) { Maximas.Dormitorios.Max = Imovel.Dormitorios; }
						if (Imovel.Dormitorios < Maximas.Dormitorios.Min) { Maximas.Dormitorios.Min = Imovel.Dormitorios; }
						if (Imovel.Garagens > Maximas.Garagens.Max) { Maximas.Garagens.Max = Imovel.Garagens; }
						if (Imovel.Garagens < Maximas.Garagens.Min) { Maximas.Garagens.Min = Imovel.Garagens; }
						if (Imovel.Banheiros > Maximas.Banheiros.Max) { Maximas.Banheiros.Max = Imovel.Banheiros; }
						if (Imovel.Banheiros < Maximas.Banheiros.Min) { Maximas.Banheiros.Min = Imovel.Banheiros; }
						
						if (Busca.Filtros.Contrato == "Locacao") {
							if (Imovel.Valores.Locacao > 0 && parseInt(Imovel.Valores.Locacao) > parseInt(Maximas.Valores.Max)) { Maximas.Valores.Max = Imovel.Valores.Locacao; }
							if (Imovel.Valores.Locacao > 0 && parseInt(Imovel.Valores.Locacao) < parseInt(Maximas.Valores.Min)) { Maximas.Valores.Min = Imovel.Valores.Locacao; }
						} else {
							if (Imovel.Valores.Venda > 0 && parseInt(Imovel.Valores.Venda) > parseInt(Maximas.Valores.Max)) { Maximas.Valores.Max = Imovel.Valores.Venda; }
							if (Imovel.Valores.Venda > 0 && parseInt(Imovel.Valores.Venda) < parseInt(Maximas.Valores.Min)) { Maximas.Valores.Min = Imovel.Valores.Venda; }
						}
						
						for (var cc in Imovel.Comodidades) {
							if ($.inArray(Imovel.Comodidades[cc], Comodidades) == -1) { Comodidades[Comodidades.length] = Imovel.Comodidades[cc]; }
						}
						
					} else {
						var values = $( "#range-valores" ).slider( "option", "values" );
						if (Busca.Filtros.Contrato == "Locacao" && Imovel.Valores.Locacao > 0) { if (!(Imovel.Valores.Locacao >= values[0] && Imovel.Valores.Locacao <= values[1])) { continue; } }
						else if (Imovel.Valores.Venda > 0) { if (!(Imovel.Valores.Venda >= values[0] && Imovel.Valores.Venda <= values[1])) { continue; } }
						
						values = $( "#range-dormitorios" ).slider( "option", "values" );
						
						if (!(Imovel.Dormitorios >= values[0] && Imovel.Dormitorios <= values[1])) { continue; }
						values = $( "#range-garagens" ).slider( "option", "values" );
						if (!(Imovel.Garagens >= values[0] && Imovel.Garagens <= values[1])) { continue; }
						values = $( "#range-banheiros" ).slider( "option", "values" );
						if (!(Imovel.Banheiros >= values[0] && Imovel.Banheiros <= values[1])) { continue; }
					}
					
					if ($('#mobiliado').attr('checked') && !Imovel.Mobiliado) { continue; }
					if ($('#alto_padrao').attr('checked') && !Imovel.AltoPadrao) { continue; }
					if ($('#financiavel').attr('checked') && !Imovel.Financiavel) { continue; }
					if (Busca.MaisFiltros) {
						var Stop = false;
						if ($('#comodidades input:checked').length > 0) {
							for (var o = 0; o < $('#comodidades input:checked').length; o++) {
								if ($($('#comodidades input:checked')[o]).is(':checked')) {
									if ($.inArray($($('#comodidades input:checked')[o]).val(), Imovel.Comodidades) == -1) {
										Stop = true;
										break;
									}
								}
							}
						}
						if (Stop) { continue; }
					}

					//html += Busca.getImovelHtml(Imovel);
					ResultsImoveis[ResultsImoveis.length] = Imovel;
					Results++;
					Hash += Imovel.Codigo;
					
					if (Busca.Visao == 2) {
						var Marker = new google.maps.Marker({
							draggable: false,
							flat: false,
							position: new google.maps.LatLng(Imovel.Geoposicionamento.Lat, Imovel.Geoposicionamento.Lng),
							title: 'Localização do imóvel',
							map: Busca.Mapa.Ref,
							Imovel: Busca.Imoveis[i]
						});
						
						google.maps.event.addListener(Marker, "click", function() {
							var Imv = this.Imovel;
							var InfoHtml = '\
								<div style="position: relative; float: left;">\
									<span class="icone favorito disabled" title="Favorite este imóvel" style="position: absolute; top: 10px; right: 10px; cursor: pointer; margin-right: 10px;" onclick="Busca.Prevent(); Favoritos.Toggle(\'' + Imv.Codigo + '\')" rel="' + Imv.Codigo + '"></span>\
									<a href="javascript:;" onclick="Busca.Mostrar(\'' + Imv.Codigo + '\')">\
										<div style="font-size: 8pt; color: #000; opacity: 0.5; padding: 2px 5px; border-radius: 5px; z-index: 100000; background: #FFF; position: absolute; bottom: 15px; left: 10px; font-weight: bold;">' + Busca.CodigoImobiliaria + ' ' + Imv.Codigo + '</div>\
										<img style="padding: 5px; border: 1px solid #e7e7e7; margin-right: 10px; width: 124px; height: 84px;" src="' + Imv.Imagens.Capa + '" />\
									</a>\
								</div>\
								<div style="padding: 5px; float: left; font-size: 8pt; min-width: 200px; position: relative;">\
									<div style="margin-bottom: 5px;"><b>' + Imv.Tipo + ' - ' + Imv.Subtipo + '</b></div>\
									' + (Imv.Endereco.Logradouro ? '<div style="margin-bottom: 5px; color: #888;">' + Imv.Endereco.Logradouro + '</div>' : '') + '\
									<div style="margin-bottom: 10px; color: #888;">' + (Imv.Endereco.Bairro ? Imv.Endereco.Bairro + (Imv.Endereco.Cidade ? ' - ' : '') : '') + Imv.Endereco.Cidade + '</div>\
									<div>\
										' + (Imv.Valores.Locacao > 0 ? '<div style="margin-bottom: 5px;">Valor de locação: <b>R$ ' + formatCurrency(Imv.Valores.Locacao) + '</b></div>' : '') + '\
										' + (Imv.Valores.Venda > 0 ? '<div style="margin-bottom: 5px;">Valor de compra: <b>R$ ' + formatCurrency(Imv.Valores.Venda) + '</b></div>' : '') + '\
									</div>\
								</div>\
							';
							
							Busca.Mapa.Info.setContent(InfoHtml);
							Busca.Mapa.Info.open(Busca.Mapa.Ref, this);										
							Favoritos.Refresh();
						});
						
						Busca.ImoveisMarkers.push(Marker);
					}
				}
			}
			
			if (Maximas.Valores.Min == 10000000000) { Maximas.Valores.Min = Maximas.Valores.Max = 0;  }
			if (Maximas.Dormitorios.Min == 10000000000) { Maximas.Dormitorios.Min = Maximas.Dormitorios.Max = 0;  }
			if (Maximas.Garagens.Min == 10000000000) { Maximas.Garagens.Min = Maximas.Garagens.Max = 0;  }
			if (Maximas.Banheiros.Min == 10000000000) { Maximas.Banheiros.Min = Maximas.Banheiros.Max = 0;  }
			
			if (AtualizarFiltros) {
				$("#comodidades").html('');
				if (Comodidades.length > 0) {
					for (var cc in Comodidades) {
						$('<div style="float: left; width: 200px; margin-bottom: 5px;"><label><input type="checkbox" onchange="Busca.MostrarImoveis(false)" value="' + Comodidades[cc] + '" style="vertical-align: middle;" /> ' + Comodidades[cc] + '</label></div>').appendTo("#comodidades");
					}
					$('<br style="clear: both;" />').appendTo('#comodidades');
					$("#comodidadesContainer").show();
				} else { $("#comodidadesContainer").hide(); }
			
				$("#range-valores").slider("option", "min", parseInt(Maximas.Valores.Min));
				$("#range-valores").slider("option", "max", parseInt(Maximas.Valores.Max));
			
				$("#range-dormitorios").slider("option", "max", parseInt(Maximas.Dormitorios.Max));
				$("#range-dormitorios").slider("option", "min", parseInt(Maximas.Dormitorios.Min));

				$("#range-garagens").slider("option", "max", parseInt(Maximas.Garagens.Max));
				$("#range-garagens").slider("option", "min", parseInt(Maximas.Garagens.Min));

				$("#range-banheiros").slider("option", "max", parseInt(Maximas.Banheiros.Max));
				$("#range-banheiros").slider("option", "min", parseInt(Maximas.Banheiros.Min));

				$("#range-dormitorios").slider("option", "values", [ Maximas.Dormitorios.Min, Maximas.Dormitorios.Max ]);
				$("#range-garagens").slider("option", "values", [ Maximas.Garagens.Min, Maximas.Garagens.Max ]);
				$("#range-banheiros").slider("option", "values", [ Maximas.Banheiros.Min, Maximas.Banheiros.Max ]);
				//alert(parseInt(Maximas.Valores.Min) + '-' + parseInt(Maximas.Valores.Max));
				$("#range-valores").slider("option", "values", [ parseInt(Maximas.Valores.Min), parseInt(Maximas.Valores.Max) ]);
				
				$("#range-dormitorios").slider("option", "disabled", (Maximas.Dormitorios.Max == Maximas.Dormitorios.Min));
				$("#range-garagens").slider("option", "disabled", (Maximas.Garagens.Max == Maximas.Garagens.Min));
				$("#range-banheiros").slider("option", "disabled", (Maximas.Banheiros.Max == Maximas.Banheiros.Min));
				$("#range-valores").slider("option", "disabled", (Maximas.Valores.Max == Maximas.Valores.Min));
				
				var values = $( "#range-dormitorios" ).slider( "option", "values" );
				$( "#texto-dormitorios" ).html( values[ 0 ] + " à " + values[ 1 ] );
				values = $( "#range-garagens" ).slider( "option", "values" );
				$( "#texto-garagens" ).html( values[ 0 ] + " à " + values[ 1 ] );
				values = $( "#range-banheiros" ).slider( "option", "values" );
				$( "#texto-banheiros" ).html( values[ 0 ] + " à " + values[ 1 ] );
				values = $( "#range-valores" ).slider( "option", "values" );
				$( "#texto-valores" ).html( 'R$ ' + formatCurrency(values[ 0 ]) + " à R$ " + formatCurrency(values[ 1 ]) );
			}

			if (Busca.Visao == 2) {
				FitToPath(Busca.Mapa.Ref, Busca.ImoveisMarkers);
			}
			
			if ((Busca.LastSearchHash == Hash || Results == 0) && AtualizarFiltros) {
				if (Results == 0) { $("#FiltrosExtras").slideUp(); }
				else if (Results > 1) { $("#FiltrosExtras").slideDown(); }
				return;
			}
			$(".ImoveisEncontrados").html((Results > 1 ? Results + " imóveis encontrados" : '1 imóvel encontrado'));
			$("#ToggleVisao").show();
			if (Results == 0) { $(".ImoveisEncontrados").html('Nenhum imóvel encontrado. <a href="solicite-um-imovel/">Clique aqui</a> para solicitar um imóvel com as características de seu interesse.'); $("#ToggleVisao").hide(); }
			Busca.LastSearchHash = Hash;
			
			var html = '';
			for (var i in ResultsImoveis) {
				if (Busca.Filtros.Contrato == 'Locacao') { if (ResultsImoveis[i].Valores.Locacao == 0) { continue; } }
				else { if (ResultsImoveis[i].Valores.Venda == 0) { continue; } }
				html += Busca.getImovelHtml(ResultsImoveis[i]);
			}
			for (var i in ResultsImoveis) {
				if (Busca.Filtros.Contrato == 'Locacao') { if (ResultsImoveis[i].Valores.Locacao > 0) { continue; } }
				else { if (ResultsImoveis[i].Valores.Venda > 0) { continue; } }
				html += Busca.getImovelHtml(ResultsImoveis[i]);
			}
			
			$("#Lista > .divContent").html(html);
			//$("#Lista > .divContent > .Imovel").css({ opacity: 0 });
			$("#conteudo").fadeOut(function() {
				$("#Imoveis > div").hide();
				$("#Lista").show();
				$("#Lista > .divContent > .Imovel").show();
				//$("#Lista > .divContent > .Imovel").each(function(i, item) {
				//	setTimeout(function() {
				//		$(item).stop(true, false).show().animate({ opacity: 1 }, 1000);
				//	}, i * 200);
				//});
				$("#Imoveis").fadeIn();
			});
			
			
			$("#Lista > .divContent > .Imovel").hover(function() {
				$(this).stop(true, false).animate({ opacity: 1, backgroundColor: Busca.Feedback });
			}, function() {
				$(this).stop(true, false).animate({ opacity: 1, backgroundColor: '#ffffff' });
			});
			
			$("#Lista > .divContent > .Imovel").each(function(i, item) {
				$('[title]', item).each(function() {
					var Title = $(this).attr('title');
					$(this).attr('title', null);
					$(this).hover(function() {
						$("#tooltip").html(Title).show();
						$("#tooltip").css({ zIndex: 1000, left: $(this).offset().left + ($(this).width() / 2) - ($("#tooltip").width() / 2), top: $(this).offset().top + $(this).height() + 10, opacity: 0 }).stop(true, false).animate({ opacity: 0.7 });
					}, function() {
						$("#tooltip").stop(true, false).animate({ opacity: 0 }, function() { $(this).hide(); });
					});
				});
			});
			
			if (AtualizarFiltros) {
				if (Results > 1) { $("#FiltrosExtras").slideDown(); }
				else if (AtualizarFiltros) { $("#FiltrosExtras").slideUp(); }
			}
			Favoritos.Refresh();
		//}		
	},
	
	Slideshow: function(codigo) {
		var Imovel = Busca._findImovel(codigo);
		if (Imovel) {
			$.fancybox(Imovel.Imagens.Items, { 'padding': 0, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type': 'image', 'changeFade': 0 });
		}
	},
	
	getImovelHtml: function(Imovel) {
		return '\
			<div onclick="Busca.Mostrar(\'' + Imovel.Codigo + '\')" class="Imovel" style="background: #ffffff; position: relative; width: 435px; padding: 10px 5px; float: left; margin: 15px 0px;">\
				<div style="background: #fff; border-radius: 5px; opacity: 0.6; font-weight: bold; font-size: 8pt; padding: 2px 5px; position: absolute; top: 80px; left: 15px">' + Busca.CodigoImobiliaria + ' ' + Imovel.Codigo + '</div>\
				' + (Imovel.Imagens.Items.length > 0 ? '<img src="imagens/slideshow.png" onclick="Busca.Prevent(); Busca.Slideshow(\'' + Imovel.Codigo + '\');" style="position: absolute; top: 20px; left: 115px; cursor: pointer;" alt="Slideshow" title="Mostrar imagens do imóvel" />' : '') + '\
				<img src="' + Imovel.Imagens.Capa + '" style="background: #ffffff; padding: 5px; border: 1px solid #c7c7c7; float: left; width: 124px; height: 84px;" />\
				<div style="position: relative; float: left; margin-left: 5px; width: 280px; height: 94px; overflow: hidden;">\
					<div style="position: absolute; right: 0px; top: 0px;">\
						' + (Busca.Filtros.Contrato == 'Locacao' ? 
								'<div title="Valor para locação" style="font-weight: bold; font-size: 11pt; text-align: right;">' + (Imovel.Valores.Locacao == 0 ? '<span style="font-size: 10px; font-weight: normal;">Consulte o valor de locação</span>' : 'R$ ' + formatCurrency(Imovel.Valores.Locacao)) + '</div>'
								+ (Imovel.Valores.Venda > 0 ? '<div title="Valor para compra" style="font-weight: bold; font-size: 8pt; text-align: right; margin-top: 10px;">R$ ' + formatCurrency(Imovel.Valores.Venda) + '</div>' : '')
							:
								'<div title="Valor para compra" style="font-weight: bold; font-size: 11pt; text-align: right;">' + (Imovel.Valores.Venda == 0 ? '<span style="font-size: 10px; font-weight: normal;">Consulte o valor de venda</span>' : 'R$ ' + formatCurrency(Imovel.Valores.Venda)) + '</div>'
								+ (Imovel.Valores.Locacao > 0 ? '<div title="Valor para locação" style="font-weight: bold; font-size: 8pt; text-align: right; margin-top: 10px;">R$ ' + formatCurrency(Imovel.Valores.Locacao) + '</div>' : '')
							) + '\
					</div>\
					<b>' + (Imovel.Subtipo == null ? Imovel.Tipo : Imovel.Subtipo) + '</b>\
					<div style="color: #888; margin: 15px 0px 5px 0px;">' + (Imovel.Endereco.Logradouro ? Imovel.Endereco.Logradouro : '') + '</div>\
					<div style="color: #888;">' + (Imovel.Endereco.Bairro ? Imovel.Endereco.Bairro + (Imovel.Endereco.Cidade ? ' - ' : '') : '') + (Imovel.Endereco.Cidade ? Imovel.Endereco.Cidade : '') + '</div>\
					<div style="position: absolute; bottom: 0px;">\
						' + (Imovel.Dormitorios > 0 ?
							'<div title="' + Imovel.Dormitorios + ' dormitórios" style="position: relative; float: left; width: 24px; height: 20px; margin-right: 10px;">\
								<span class="icone dormitorio"></span>\
								<span style="font-weight: bold; color: #aaa; position: absolute; right: 0px; bottom: 0px; font-size: 7pt;">' + Imovel.Dormitorios + '</span>\
							</div>' : '') +								
						(Imovel.Banheiros > 0 ?
							'<div title="' + Imovel.Banheiros + ' banheiros" style="position: relative; float: left; width: 24px; height: 20px; margin-right: 10px;">\
								<span class="icone banheiro"></span>\
								<span style="font-weight: bold; color: #aaa; position: absolute; right: 0px; bottom: 0px; font-size: 7pt;">' + Imovel.Banheiros + '</span>\
							</div>' : '') +
						(Imovel.Garagens > 0 ?
							'<div title="' + Imovel.Garagens + ' vagas para carro" style="position: relative; float: left; width: 24px; height: 20px; margin-right: 10px;">\
								<span class="icone garagem"></span>\
								<span style="font-weight: bold; color: #aaa; position: absolute; right: 0px; bottom: 0px; font-size: 7pt;">' + Imovel.Garagens + '</span>\
							</div>' : '') +
						(Imovel.Mobiliado ? '<span title="Imóvel mobiliado" class="icone mobiliado"></span>' : '') + '\
					</div>\
					<div style="position: absolute; bottom: 0px; right: 0px;">\
						<span class="icone favorito disabled" title="Favorite este imóvel" style="cursor: pointer; margin-right: 10px;" onclick="Busca.Prevent(); Favoritos.Toggle(\'' + Imovel.Codigo + '\')" rel="' + Imovel.Codigo + '"></span>\
						<a onclick="Busca.Prevent();" href="imovel/' + Imovel.Codigo + '" target="_blank" class="icone janela disabled" title="Abrir informações em nova janela" style="cursor: pointer;" onmouseover="$(this).removeClass(\'disabled\')" onmouseout="$(this).addClass(\'disabled\')"></a>\
					</div>\
				</div>\
				<br style="clear: both;" />\
			</div>\
		';
	},
	
	BuscarCodigo: function() {
		var Codigo = parseInt($("input[name=busca_codigo]").val().match(/\d/g).join(''));
		if (Codigo > 0) {
			if (Busca._findImovel(Codigo) != null) { Busca.Mostrar(Codigo); }
			else { alert('Imóvel não encontrado'); }					
		}
		return false;
	},
	MostrarImovel: null,
	
	Setup: function() {
		if (Busca.Tipos.Locacao == 0) { $("#MenuContratoLocacao").hide(); $("#MenuContratoCompra").css({ marginTop: 20 }); }
		if (Busca.Tipos.Compra == 0) { $("#MenuContratoCompra").hide(); }
		$("input[name=busca_codigo]").focus(function() {
			if (!$(this).hasClass('v')) {
				$(this).val('');
				$(this).css({ color: '#000' });
			}
		}).keydown(function() {
			$(this).addClass('v');
		}).blur(function() {
			if ($(this).val() == '') {
				$(this).removeClass('v');
				$(this).val('código');
				$(this).css({ color: '#c7c7c7' });
			}
		});
		Busca.ImoveisMarkers = new google.maps.MVCArray();
		
		
		$.history.init(function(hash){
			if(hash != "") {
				switch (hash) {
					case 'Busca':
						$("#Loader").stop(true, true).css({ opacity: 0.5 }).hide();
						Busca.MostrarImovel = null;
						Busca.Voltar(); break;
					default:
						var A = hash.split('-');
						if (A[0] == 'Imovel') {
							Busca.Mostrar(A[1]);
						}
				}
				
			} else if (Busca.Etapa > 0) { Busca.Cancelar(); }
			else {
				Busca.Voltar();
			}
		});
	},
	
	Cancelar: function() {
		window.location.hash = '';
		$("#mobiliado,#alto_padrao,#financiavel").attr('checked', false);
		$("#comodidades input").attr('checked', false);
		if (Busca.Etapa > 0) {
			$("#FiltrosExtras").slideUp(function() {
				$("#MenuSetaTipos").animate({ left: 100 }, function() { $(this).hide(); });
				$("#MenuSubtipos").fadeOut(function() {
					$("#MenuTipos").fadeOut();
					$("#MenuSeta").animate({ left: 0 }, function() {
						$("#MenuContrato > a").removeClass('active');
						$("#MenuSeta").animate({ left: 580 });
						$("#MenuContrato").animate({ left: 598 });
						$("#MenuInfo").animate({ width: 580 });
					});
				});
			});
		} else {
			$("#FiltrosExtras").hide();
			$("#MenuContrato > a").removeClass('active');
			$("#MenuSeta").animate({ left: 580 });
			$("#MenuContrato").animate({ left: 598 });
			$("#MenuInfo").animate({ width: 580 });
		}
		Busca.Etapa = 0;
		Busca.Filtros.Tipos = [];
		Busca.Filtros.Subtipos = [];
		Busca.Filtros.Contrato = "Nenhum";
		Busca.LastSearchHash = null;
		
		$("#Imoveis").fadeOut(function() {
			$("#conteudo").fadeIn();
		});
		
		Busca.Path.List = Array();
	},
	
	Visao: 1,
	ToggleVisao: function() {
		if (Busca.Visao == 1) {
			$("#ToggleVisao").html("Ver resultados em lista");
			Busca.Visao = 2;
			$("#Lista > .divContent").fadeOut(function() {
				$("#Mapa").fadeIn(function() {
					if (!Busca.Mapa.Criado) {
						Busca.Mapa.Criar();
						setTimeout(function() { Busca.MostrarImoveis(false); }, 1000);
					} else { FitToPath(Busca.Mapa.Ref, Busca.ImoveisMarkers); }
				});
			});
		} else {
			$("#ToggleVisao").html("Ver resultados no mapa");
			Busca.Visao = 1;
			$("#Mapa").fadeOut(function() {
				$("#Lista > .divContent").fadeIn();
			});
		}
	},

	Mapa: {
		Criado: false,
		Ref: null,
		Info: null,
		Criar: function() {
			if (Busca.Mapa.Criado) { return; }
			
			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
			};
			
			Busca.Mapa.Ref = new google.maps.Map(document.getElementById("Mapa"), opt);
			Busca.Mapa.Info = new google.maps.InfoWindow();
			
			
			Busca.Mapa.Criado = true;
		}
	},
	
	Prevent: function() {
		Busca.PreventShow = true;
	},
	
	Mostrar: function(codigo) {
		if (Busca.PreventShow) { Busca.PreventShow = false; return; }
		Busca.Path.Add("Imovel");
		window.location.hash = 'Imovel-' + codigo;
		Busca.MostrarImovel = codigo;
		$("#Loader").css({ opacity: 0.5 }).fadeIn();
		$.ajax({
			url: 'imovelinfo/' + codigo,
			dataType: 'html',
			success: function(d) {
				if (Busca.MostrarImovel == codigo) {
					$("#Loader").fadeOut();
					$("#conteudo").fadeOut(function() {
						$("#Imoveis").fadeOut(function() {
							$("#Imoveis > div").hide();
							$("#Imovel > .divContent").html(d);
							$("#Imovel").show();
							$("#Imoveis").fadeIn();
							Favoritos.Refresh();
						});
					});
				}
			}
		});
	},
	
	Voltar: function() {
		$("#mobiliado,#alto_padrao,#financiavel").attr('checked', false);
		$("#comodidades input").attr('checked', false);
		Busca.Path.Pop();
		if (Busca.Path.List.length > 0) {
			$("#Imoveis").fadeOut(function() {
				$('#Imoveis > div').hide();
				$('#' + Busca.Path.Last()).show();
				$(this).fadeIn();
			});
		} else {
			$("#Imoveis").fadeOut(function() { $("#conteudo").fadeIn(); });
		}
	},
	
	MaisFiltros: false,
	ToggleMaisFiltros: function() {
		$("#mobiliado,#alto_padrao,#financiavel").attr('checked', false);
		$("#comodidades input").attr('checked', false);
		if (Busca.MaisFiltros) {
			Busca.MaisFiltros = false;
			$('#maisFiltros').slideUp();
			$("#maisFiltrosLink").html('mais filtros');
			Busca.MostrarImoveis(false);
		} else {
			Busca.MaisFiltros = true;
			$('#maisFiltros').slideDown();
			$("#maisFiltrosLink").html('esconder');
		}		
	}
};

$(function() {
	Busca.Setup();
	$( "#range-valores" ).slider({ range: true, min: 0, max: 500, values: [ 0, 500 ], slide: function( event, ui ) { $( "#texto-valores" ).html( "R$ " + formatCurrency(ui.values[ 0 ]) + " à R$ " + formatCurrency(ui.values[ 1 ]) ); }, stop: function() { Busca.MostrarImoveis(false); } });
	$( "#range-dormitorios" ).slider({ range: true, min: 0, max: 500, values: [ 0, 500 ], slide: function( event, ui ) { $( "#texto-dormitorios" ).html( ui.values[ 0 ] + " à " + ui.values[ 1 ] ); }, stop: function() { Busca.MostrarImoveis(false); } });
	$( "#range-garagens" ).slider({ range: true, min: 0, max: 500, values: [ 0, 500 ], slide: function( event, ui ) { $( "#texto-garagens" ).html( ui.values[ 0 ] + " à " + ui.values[ 1 ] ); }, stop: function() { Busca.MostrarImoveis(false); } });
	$( "#range-banheiros" ).slider({ range: true, min: 0, max: 500, values: [ 0, 500 ], slide: function( event, ui ) { $( "#texto-banheiros" ).html( ui.values[ 0 ] + " à " + ui.values[ 1 ] ); }, stop: function() { Busca.MostrarImoveis(false); } });
});

var Favoritos = {
	List: Array(),
	
	Refresh: function() {
		$(".favorito[rel]").addClass('disabled');
		for (var i in Favoritos.List) {
			$(".favorito[rel=" + Favoritos.List[i] + "]").removeClass('disabled');
		}
	},
	
	Toggle: function(id) {
		if (Favoritos.Find(id)) { Favoritos.Remove(id); }
		else { Favoritos.Add(id); }
	},
	
	Add: function(id) {
		$(".favorito[rel=" + id + "]").removeClass('disabled');
		Favoritos.List[Favoritos.List.length] = id;
		$.cookie("favoritos", Favoritos.List.join(','), { expires: 360, path: '/' });
		$(".FavoritosCount").html(Favoritos.List.length);
	},
	
	Remove: function(id, obj) {
		$(".favorito[rel=" + id + "]").addClass('disabled');
		var newArray = Array();
		for (var i in Favoritos.List) {
			if (Favoritos.List[i] != id) { newArray[newArray.length] = Favoritos.List[i]; }
		}
		Favoritos.List = newArray;
		$.cookie("favoritos", Favoritos.List.join(','), { expires: 360, path: '/' });
		$(".FavoritosCount").html(Favoritos.List.length);
	},
	
	Find: function(id) {
		for (var i in Favoritos.List) { if (Favoritos.List[i] == id) { return true; } }
		return false;
	},
	
	Count: function() {
		var c = 0;
		for (var i in Favoritos.List) {
			if (Favoritos.List[i]) { c++; }
		}
		return c;
	}	
};

$(function() {
	if ($.cookie("favoritos")) {
		var f = $.cookie("favoritos").split(',');
		for (var i in f) {
			if (f[i]) {
				Favoritos.Add(f[i], null);		
			}
		}
	}
});
