$(document).ready(function() {
	
	//Se for ie6, carrega menu por js e roda o pngfix
	if($.browser.msie && $.browser.version=="6.0") {
		$.getScript("inc/dropdown/jquery.dropdown.js");
		$.getScript("inc/js/jquery.pngfix.js",function(xhr){
			var aplicar_pngfix = ".imoveisHome .foto .label";
			try {
				$(aplicar_pngfix).pngfix();
			} catch(err) {
				eval(xhr);
				$(aplicar_pngfix).pngfix();
			}
		});
	}


	
//
// Menu principal
//
	//manter hover do menu principal ativo quando vai pro submenu
	$("#header #menu li.dir ul").mouseover(function(){
		$(this).parents("li.dir").find("a:first").addClass("active");
	});
	$("#header #menu li.dir ul").mouseout(function(){
		$(this).parents("li.dir").find("a:first").removeClass("active");
	});
	
//-------------------------------------//

	
	//labelify
	$.getScript("inc/js/jquery.labelify.js",function(xhr){
		var aplicar_labelify = "#busca .codigo";
		try {
			$(aplicar_labelify).labelify();
		} catch(err) {
			eval(xhr);
			$(aplicar_labelify).labelify();
		}
	});
	
	//"voltar" nos Hs
	$("h1.voltar, h2.voltar").each(function(){
		var h = $(this).html();
		$(this).html('<span>'+h+'</span><a href="#" onclick="history.go(-1);return false;" class="voltar">&laquo; Voltar</a>');
	});
	
	//"topo" nos Hs
	$("h3.topo").each(function(){
		var h = $(this).html();
		$(this).html('<span>'+h+'</span><a href="#" class="topo">Topo ^</a>');
	});
	

	//---------- Voltar topo ----------//
	//--------------------------------//
	$('#footer_topo_link').live('click',function(){
		$('html, body').animate({scrollTop:0}, 1000);
		return false;
	});

	
	//------------ Bairros ------------//
	//--------------------------------//
	letras_bairros();
	$(".divbairros select").click(function(){
		$(this).html('');
		$(this).slideUp("slow",function(){
			$(".divbairros .bairros").slideDown("slow");
		});
	});
 	
$(".bairros").hover(
	function (){
		bloqueador=1;}, 
	function(){
		bloqueador=0;
		$("#busca").click(function(){
			if(bloqueador==0){
				$("#busca .divbairros .bairros:visible").slideUp("slow",function(){
					$("#busca .divbairros .bairros label").show();
					$("#busca .divbairros select").slideDown("slow",function(){
						c = conta_bairros();
						if (c>0) {
							if (c==1) s = ""; else s = "s";
							$(this).html('<option value="" selected="selected">'+c+' selecionado'+s+'</option>');
						} else {
							$(this).html('<option value="" selected="selected">Nenhum bairro selecionado</option>');
						}
					});
				});
			}
		});	
	}
);



	function conta_bairros(){
		c = 0;
		$("#busca .divbairros .bairros input").each(function(){
			if ($(this).is(":checked")) c++;
		});
		return c;
	}
	
	carregaBairros();
	$("#busca_cidade").change(function(){ carregaBairros(); });		
	
//------ Formulário de busca ------//
//--------------------------------//
	
	//Envia formulário
	$("#fbusca").submit(function(){
		var livre = $.trim($("#placa").val());
		if (isNaN(livre)) { $("#fbusca").attr('action','imoveis.php'); }
		else 			  { $("#fbusca").attr('action','detalhes.php'); }	 
	});			

	//Finalidade busca avançada
	$("#de_locacao").hide();
	$("#ate_locacao").hide();
	trocar_finalidade();
	$('input[name=finalidade]:radio').click(function()	{ trocar_finalidade($(this).attr('value'));});	
	
//--------------------------------//


	//------- Enviar por email ---------//
	//--------------------------------//
	// (Não verificada)
	if ($("#enviar-por-email").length>0) {
		$("#enviar-por-email").dialog({
			autoOpen: false,
			bgiframe: true,
			minHeight: 140,
			modal: true,
			width: 330,
			resizable: false
		});
		$("#detalhes .links .email").click(function(){
			$("#enviar-por-email").dialog('open');
			return false;
		});
	}
	//tooltips
	if ($(".tooltip").length>0) {
		$(".tooltip").tooltip({ 
			track: true, 
			delay: 0, 
			showURL: false, 
			showBody: " - ", 
			fade: 250 
		});
	}

	//fotos do imovel
	if ($("#fotos").length>0) {
		$('#fotos .items a').lightBox();
		$("#fotos div.scrollArea").scrollable({
			loop: true, 
			speed: 1200,
			size: 3
		});
	}
	
	//home
	if ($("#leftContent .imoveisHome").length>0) {
		$("#leftContent .imoveisHome").each(function(){
			if ($(this).find(".imovel").length>3) {
				var lis = $(this).find(".imovel");
				for (var i = 0; i < lis.length; i+=3) lis.slice(i, i+3).wrapAll('<div class="set"></div>');
				$(this).find(".seta").fadeIn("slow");
				$(this).find(".slides").after('<div class="nav">').cycle({
					fx:		'scrollHorz',
					prev:	$(this).find(".esq"),
					next:	$(this).find(".dir"),
					pager:	$(this).find(".nav"),
					pause:	true,
					timeout:  15000,
					pauseOnPagerHover: true
				});
			}
		});
	}

	//favoritos
	$(".numfav").load('inc/lib/fnc_favoritos.php?act=count_imo');
	$("a.fav").click(function(event){
		var codigo = $(this).attr("rel");
		var fav = $(this);
		if ($(this).hasClass("favon")) {
			$.get("inc/lib/fnc_favoritos.php?act=del_imo&delid="+codigo,
				function(data){ fav.removeClass("favon").html("Adicionar aos favoritos"); $(".numfav").load('inc/lib/fnc_favoritos.php?x=1&act=count_imo'); }
			);
		} else {
			 $.get("inc/lib/fnc_favoritos.php?act=add_imo&addid="+codigo,				
				function(data){ fav.addClass("favon").html("Remover dos favoritos"); $(".numfav").load('inc/lib/fnc_favoritos.php?x=1&act=count_imo'); }
			);
		}
		event.stopPropagation();
		return false;
	});
	
	//imoveis
	$(".imoveisHome .imovel, .imoveis .imovel").live('click',function(){
		href = $(this).find(".foto .base a").attr("href");
		window.location = href;
		return false;
	});
	
	//imoveis da direita
	if ($("#imoveisRight").length>0) {
		$("#imoveisRight .imovel:odd").addClass("odd");
	}

	/*ligamos para voce*/
	$('a#ligar').fancybox({
		'hideOnContentClick': true,
		'height': 150
	});
	
	$('a#enviaremail').fancybox({
		'hideOnContentClick': true,
		'height': 200
	});

	$('a#botao_buscaAvan').fancybox({
		'hideOnContentClick': true,
		'width':900
	});	
});//Fim $(Document).ready


//--------------------------------//
//----------- Funções ------------//
//--------------------------------//
function carregaBairros() {
	var cidade = $('#busca_cidade').val();
	var lista  = $('#listabairros').val();
	$(".bairros").load("inc/lib/fnc_load-busca.php?act=bairros", {cidade: cidade, lista: lista},
		function(data){
		letras_bairros();
	})			 }		

function trocar_finalidade(finalidade) {
	if (finalidade=='locacao') {
		$("#de_venda").css('display','none');
		$("#ate_venda").css('display','none');
		$("#de_locacao").css('display','block');
		$("#ate_locacao").css('display','block');
	}
	else {
		$("#de_locacao").css('display','none');
		$("#ate_locacao").css('display','none');
		$("#de_venda").css('display','block');
		$("#ate_venda").css('display','block');
	}	}

function mapa_imovel(l1,l2,tipo,controles,mapid) {
	if ( tipo === undefined ) tipo = 'ponto';
	if ( controles === undefined ) controles = true;
	if ( mapid === undefined ) mapid = "map";
	if ($("#"+mapid).length>0) {
		if (GBrowserIsCompatible()) {
			var map = new GMap2(document.getElementById(mapid));
			map.setCenter(new GLatLng(l1,l2), 15);
			var latlng = new GLatLng(l1,l2);
			if (controles) {
				map.addControl(new GSmallMapControl());
				map.addControl(new GMapTypeControl());
			}
			if (tipo=='circulo') {
				var marcador = GPolygon.Circle(latlng, 500,"#72B128",2,1,"#000",0.2)
				map.addOverlay(marcador);
			} else {
				var icone = new GIcon(G_DEFAULT_ICON);
				icone.image = "img/design/gmaps_icon.png";
				icone.iconSize = new GSize(26, 30);
				markerOptions = { icon:icone };
				map.addOverlay(new GMarker(latlng, markerOptions));
				//map.addOverlay(new GMarker(latlng));
			}
		}
	} }

function letras_bairros() {
	if($.browser.msie && $.browser.version=="6.0") {
		$(".divbairros .bairros p").hide();
	} else {
		$(".divbairros .bairros").prepend("<p></p>");
		letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		letras_usadas = "";
		$(".divbairros .bairros label").each(function(){
			str = $(this).html();
			v = str.split("> ");
			nome_bairro = v[1];
			letras_usadas += nome_bairro.substr(0,1);
		});
		letras_links = '<a href="#" class="todos">Todos</a><br />&nbsp;';
		for (i=0;i<=letras.length-1;i++) {
			tem = letras_usadas.indexOf(letras.substr(i,1));
			if (tem>=0) {
				letras_links += '<a href="#" class="letra">'+letras.substr(i,1)+'</a>';
			} else {
				letras_links += letras.substr(i,1);
			}
		}
		$(".divbairros .bairros p").html(letras_links);
		$(".divbairros .bairros p a.letra").click(function(){
			letra = $(this).html();
			$("#busca .divbairros .bairros label").each(function(){
				str = $(this).html();
				v = str.split("> ");
				nome_bairro = v[1];
				bletra = nome_bairro.substr(0,1);
				if (bletra==letra) $(this).show(); else $(this).hide();
			});
			return false;
		});
		$(".divbairros .bairros p a.todos").click(function(){
			$(".divbairros .bairros label").show();
			return false;
		});
	} }

