$(document).ready(function() {

	tipos();	
	$("#cidade").change(function(){ tipos(); });		
	bairros();	
	$("#cidade").change(function(){ bairros(); });		
	$("#cidade").change(function(){ $("select[name='tipo'] option").html('Tipo de Im&oacute;vel');});
	
	$("#tipo").click(function(e){
		e.stopPropagation();
		var index = "#tipos";
		if ($(index).is(':visible')){	
			$(index).hide();
		}else{		
			$(index).show();
		}
	});	
	
	$("#tipos").click(function(e) {
		e.stopPropagation();
	});		
	
	$("body").click(function() {
		$("#tipos").hide();
	});	
	
	function tipos(){
		var cidade = $('#cidade').val();
		$("#tipos").load("loader.php?act=tipo", {cidade: cidade},function(){
			$("input[name='tipo[]']").click(function(){
			
				var checked = $("input[name='tipo[]']").filter(":checked").length;
				if (checked == 0 ) {
					txt = 'Tipo de Im&oacute;vel'; 		
				}else if (checked == 1) {
					txt = $("input[name='tipo[]']").filter(":checked").parents("label").text(); 				
				}else{
					txt = checked + ' selecionado(s)';
				}
				$("select[name='tipo'] option").html(txt);			
			
				if($("input[name='tipo[]']").filter(":checked").length >= 4) {
					$("input[name='tipo[]']").not(":checked").attr("disabled","disabled");
					$("input[name='tipo[]']").not(":checked").parent().addClass('disabled'); 
				}
				else {
					$("input[name='tipo[]']").removeAttr("disabled"); 
					$("input[name='tipo[]']").parent().removeClass('disabled'); 
				}	
				
			});
		});
	}		

	
	function bairros() {
		var cidade = $('#cidade').val();
		$("#bairros").load("loader.php?act=bairros", {cidade: cidade},function(){
			$("input[name='bairro[]']").click(function(){			
				
				if($("input[name='bairro[]']").filter(":checked").length >= 8) {
					$("input[name='bairro[]']").not(":checked").attr("disabled","disabled");
					$("input[name='bairro[]']").not(":checked").parent().addClass('disabled'); 
				}
				else {
					$("input[name='bairro[]']").removeAttr("disabled");
					$("input[name='bairro[]']").parent().removeClass('disabled');
				}	
				
			});
		});
	}			
		
	if ($("#redirect").length>0) {
		$("#redirect").change(function() { 
			var destino = $("#redirect :selected").val();
			window.location = destino;
		});	
	}
	if ($('a.fav').length>0) {
		$('a.fav').click(function(){
			var id = $(this).attr('rel');
			var fav = $(this);
			if ($(this).hasClass('favon')) {
				$.post('favoritos.php', {delid: id},	
					function(data){ fav.removeClass('favon'); 
					}
				);
			} else {
				 $.post('favoritos.php', {addid: id},				
					function(data){ fav.addClass('favon'); 
					}
				);
			}
			return false;
		});
	}
});
