var cancel = false;

$(function(){

	var regiao = {};
	var dormitorio = {};
	var finalidade = {};
	var cidade = {};
	var bairro = {};
	var zona = {};
	var maximo = {};
	var minimo = {};
	var vagas = {};
	var financiamento = {};
	var tipo = {};
	var maximo = {};
	var minimo = {};
	var suites = {};
	var vagas = {};

	var regiaoUrl = {};
	var dormitorioUrl = {};
	var finalidadeUrl = "";
	var cidadeUrl = {};
	var bairroUrl = {};
	var zonaUrl = {};
	var maximoUrl = {};
	var minimoUrl = {};
	var vagasUrl = {};
	var financiamentoUrl = {};
	var tipoUrl = "";
	var maximoUrl = {};
	var minimoUrl = {};
	var suitesUrl = {};
	var vagasUrl = {};
	var todos = new Array();
	var maxItensUl = 4;
	var prioridade = 0;

	$('.bto-fechar').click(function() {
		cancel = true;
		$.fancybox.close();
	});

	$('.bto-continuar').click(function() {
		$.fancybox.close();
	});


	$(".ValorMaximo, .ValorMinimo, .dormitorio, .tipo").sSelect();

	var Settings =
	{
	   "Finalidade" : {
			"Prioridade" : 8,
			"Tipo" : "null"
		},
	   "Financiamento" : {
			"Prioridade" : 7,
			"Tipo" : "null"
		},
		"Regiao" : {
			"Prioridade" : 6,
			"Tipo" : "checkBox",
			"id"   : "regiaoSelect .conteudo-listagem",
			"attr": "regiaoCheck"
		},
		"Cidade" : {
			"Prioridade" : 5,
			"Tipo" : "checkBox",
			"id" : "cidadeSelect .conteudo-listagem",
			"attr": "cidadeCheck"
		},
		"Zona" : {
			"Prioridade" : 3,
			"Tipo" : "checkBox",
			"id" : "zonaSelect .conteudo-listagem",
			'attr': "zonaCheck"
		},
		"Bairro" : {
			"Prioridade" : 3,
			"Tipo" : "checkBox",
			"id" : "bairroSelect .conteudo-listagem",
			"attr": "bairroCheck"
		},
		"Tipo" : {
			"Prioridade" : 3,
			"Tipo" : "select",
			"id" : "tipo",
			"attr": "tipo",
			"label": "tipo",
			"max": 5,
			"default" : "Todos os Tipos"
		},
		"Dormitorios" : {
			"Prioridade" : 1,
			"Tipo" : "select",
			"id" : "dormitorio",
			"attr": "Dormitorio",
			"label": "dormitorio",
			"max": 5,
			"default" : "Todos Dormitorios"
		},
		"ValorMaximo" : {
			"Prioridade" : 1,
			"Tipo" : "select",
			"id" : "ValorMaximo",
			"attr": "Maximo",
			"label": "",
			"default" : "Indiferente"
		},
		"ValorMinimo" : {
			"Prioridade" : 1,
			"Tipo" : "select",
			"id" : "ValorMinimo",
			"attr": "Minimo",
			"label": "",
			"default" : "Indiferente"
		},
	   "Vagas" : {
			"Prioridade" : 0,
			"Tipo" : "null"
		},
		"Suites" : {
			"Prioridade" : 0,
			"Tipo" : "null"
		},
		"Total" : {
			"Prioridade" : 100000,
			"Tipo" : "null"
		}
	}

	$(".todos").live('click',function(){
		if ($(this).is(":checked")){
			$(this).parents("div .titulo-lista").parent("div").parent("div").find("input[type='checkbox']").attr("checked","checked");
			todos[$(this).val()] =  true;            
		} else {
			$(this).parents("div .titulo-lista").parent("div").parent("div").find("input[type='checkbox']").removeAttr("checked")
			todos[$(this).val()] =  false;
			$("."+$(this).val()).text($(this).val());
		}
	});

	var optionsRegiao =
	{
		showCloseButton : false,centerOnScroll: true, hideOnOverlayClick: false, enableEscapeButton: false, overlayOpacity: 0.8, overlayColor: '#fff', titleShow : false,
		onStart: function() {
			cancel = false;
		},
		onClosed: function(){
			if (cancel == false) {
			   regiao = {};
			   regiaoUrl = {};
			   cidade = {};
			   cidadeUrl =  {};
			   zona = {};
			   zonaUrl = {};
			   bairro = {};
			   bairroUrl = {};
			   $(".regiaoCheck:checked").each(function(){
					regiao[$(this).val()] = $(this).val();
					regiaoUrl[$(this).attr("tittle")] = $(this).attr("tittle");    
			   });

			   prioridade = 6;
			   sendBusca();
		   }
		}
	}

	var optionsCidade = {
		showCloseButton : false,centerOnScroll: true, hideOnOverlayClick: false, enableEscapeButton: false, overlayOpacity: 0.8, overlayColor: '#fff', titleShow : false,
		onStart: function() {
			cancel = false;
		},
		onClosed: function (){
			if (cancel == false) {
			   cidade = {};
			   cidadeUrl =  {};
			   zona = {};
			   zonaUrl = {};
			   bairro = {};
			   bairroUrl = {};
			   $(".cidadeCheck:checked").each(function(){
					cidade[$(this).val()] = $(this).val();
					cidadeUrl[$(this).attr("tittle")] = $(this).attr("tittle");
			   });

			   prioridade = 5;
			   sendBusca();
		   }
		}
	}

	var optionsZona =
	{
		showCloseButton : false,centerOnScroll: true, hideOnOverlayClick: false, enableEscapeButton: false, overlayOpacity: 0.8, overlayColor: '#fff', titleShow : false,
		onStart: function() {
			cancel = false;

			if ($.isEmptyObject(cidade)  ) {
				alert("Selecione ao menos uma cidade");
				return false;
			}
		},
		onClosed: function(){
			if (cancel == false) {
			   zona = {};
			   zonaUrl = {};
			   bairro = {};
			   bairroUrl = {};
			   $(".zonaCheck:checked").each(function(){
					zona[$(this).val()] = $(this).val();
					zonaUrl[$(this).parent("input").text()] = $(this).parent("input").text().substr(1);
			   });

			   $(this).html(zona.toString());

			   prioridade = 4;
			   sendBusca();
		   }
		}
	}

	var optionsBairro =
	{
		showCloseButton : false,centerOnScroll: true, hideOnOverlayClick: false, enableEscapeButton: false, overlayOpacity: 0.8, overlayColor: '#fff', titleShow : false,
		onStart: function() {
			cancel = false;

			if ($.isEmptyObject(regiao) && $.isEmptyObject(cidade)  ) {
				alert("Selecione ao menos uma região ou uma cidade");
				return false;
			}
		},
		onClosed: function(){
			if (cancel == false) {
			   bairro = {};
			   bairroUrl = {};
			   $(".bairroCheck:checked").each(function(){
					bairro[$(this).val()] = $(this).val();
                                        
					bairroUrl[$(this).attr("tittle")] = $(this).attr("tittle");
			   });
			   $(this).html(bairro.toString());
			   prioridade = 3;
			   sendBusca();
		   }
		}
	}

	$(".Regiao").fancybox(optionsRegiao);
	$(".Cidade").fancybox(optionsCidade);
	$(".Zona").fancybox(optionsZona);
	$(".Bairro").fancybox(optionsBairro);

	$("#Busca").ready(function(){
		$("#Busca").tabs({
			fx: {
				opacity: 'toggle',
				duration: 200
			}
		}).css('display', 'inline');
	});
	$("#suites").click(function(){

		if ($(this).is(":checked")) {
			suites[1] = "null";
			suitesUrl[1] = 1;
			suitesUrl[2] = 2;
			suitesUrl[3] = 3;
			suitesUrl[4] = 4;
			suitesUrl[5] = 5;

		} else {
			suites = {};
			suitesUrl = {};
		}

		prioridade = 1;

		sendBusca();
	});
	$("#financiamento").click(function(){

		if ($(this).is(":checked")) {
			financiamento[1] = 1;
			financiamentoUrl[1] = 1;

		} else {
			financiamento = {};
			financiamentoUrl = {};
		}

		prioridade = 7;
		sendBusca();
	});
	$("#vagas").click(function(){

		if ($(this).is(":checked")) {
			vagas[1] = "null";
		} else {
			vagas = {};
		}

		prioridade = 0;
		sendBusca();
	});
	$(".FinalidadeBusca").click(function(){
		finalidade = {};
		finalidade = $(this).val();
		finalidadeUrl = $(this).val();
		prioridade = 8;
		sendBusca();
	});
	$(".dormitorio").click(function(){
		dormitorio = {};
		dormitorio[$(this).val()] = $(this).getSetSSValue();
		prioridade = 2;
		sendBusca();
	});
	$(".tipo").change(function(){
		tipo = {};
		tipo[$(this).getSetSSValue()] = $(this).getSetSSValue();
		prioridade = 3;
		tipoUrl = $(this).find(":selected").html();
		sendBusca();
	});


	function sendBusca(){
		var pesquisa = {};

		pesquisa["pesquisa"] = {};

		pesquisa["pesquisa"]["Regiao"]        = (  $.isEmptyObject(regiao)       ) ? "null" : regiao;
		pesquisa["pesquisa"]["Cidade"]        = (  $.isEmptyObject(cidade)       ) ? "null" : cidade;
		pesquisa["pesquisa"]["Bairro"]        = (  $.isEmptyObject(bairro)       ) ? "null" : bairro;
		pesquisa["pesquisa"]["Zona"]          = (  $.isEmptyObject(zona)         ) ? "null" : zona;
		pesquisa["pesquisa"]["Finalidade"]    = (  $.isEmptyObject(finalidade)   ) ? "null" : finalidade;
		pesquisa["pesquisa"]["Dormitorios"]   = (  $.isEmptyObject(dormitorio)   ) ? "null" : dormitorio;
		pesquisa["pesquisa"]["ValorMaximo"]   = (  $.isEmptyObject(maximo)       ) ? "null" : maximo;
		pesquisa["pesquisa"]["ValorMinimo"]   = (  $.isEmptyObject(minimo)       ) ? "null" : minimo;
		pesquisa["pesquisa"]["Vagas"]         = (  $.isEmptyObject(vagas)        ) ? "null" : vagas;
		pesquisa["pesquisa"]["Suites"]        = (  $.isEmptyObject(suites)       ) ? "null" : suites;
		pesquisa["pesquisa"]["Financiamento"] = (  $.isEmptyObject(financiamento)) ? "null" : financiamento;


		exibirLoading();
		generateMsg();
		$.ajax({
			"url": BASE_URL+"procurar/possibilidades",
			"data": pesquisa,
			"type": "Post",
			"dataType": "json",
			success: function(data){
				for ( var i in data['response'] ) { 
					
					if ( i == "Zona" ) {
						generateGruposZona(data['cidadeZona']);
						continue;
					}                    
					if ( i == "Bairro" ) {
						generateGruposBairros(data['cidadeBairro']);
						continue;
					}
					
					if (prioridade > Settings[i]["Prioridade"]) {
						if ( i == "Cidade") {
							generateGruposCidade(data['regiaoCidade']);
							continue;
						}
						
						switch(Settings[i]["Tipo"]){
							case "checkBox":
								generateCheckBox(data['response'][i], Settings[i]["id"], Settings[i]["attr"]);
								break;
							case "select":
								generateSelect(data['response'][i], Settings[i]["id"], Settings[i]["attr"],Settings[i]["label"], ( Settings[i]["max"] ) ? Settings[i]["max"] : 0, Settings[i]["default"]);
								break;
							default:
								continue;
						}
					}
				}

				removerLoading();
			}


		});
		var pesquisaUrl = {};
		pesquisaUrl['pesquisa'] = {};
		if ( !$.isEmptyObject(regiaoUrl)  && todos['Regiao'] != true ) {
			pesquisaUrl["pesquisa"]["regiao"] =  regiaoUrl;
		}
		
                
		if ( !$.isEmptyObject(cidadeUrl) && todos['Cidade'] != true ) {
			pesquisaUrl["pesquisa"]["cidade"]        = cidadeUrl;
			pesquisaUrl["pesquisa"]["ic"]        = cidade;
		}

		if (  !$.isEmptyObject(bairroUrl)  && todos['Bairro'] != true) {
			pesquisaUrl["pesquisa"]["bairro"]        = bairroUrl;
		}

		if ( !$.isEmptyObject(zonaUrl)  && todos['Zona'] != true ) {
			pesquisaUrl["pesquisa"]["zona"]  = zonaUrl;
		}
		if ( !$.isEmptyObject(dormitorio) ) {
			pesquisaUrl["pesquisa"]["dormitorios"] = dormitorio;
		}
		if ( !$.isEmptyObject(maximo)) {
			pesquisaUrl["pesquisa"]["valorMax"] =  maximo;
		}
		if ( !$.isEmptyObject(minimo)) {
			pesquisaUrl["pesquisa"]["valorMin"] = minimo;
		}

		if ( !$.isEmptyObject(vagas) ) {
			pesquisaUrl["pesquisa"]["vagas"] = vagas;
		}

		if ( !$.isEmptyObject(suites) ) {
			 pesquisaUrl["pesquisa"]["suites"] = suites;
		}
		if ( !$.isEmptyObject(financiamento) ) {
			pesquisaUrl["pesquisa"]["financiado"]  = financiamento;
		}

		var tourl = "";

		switch(parseInt(finalidadeUrl)){
			case 1:
				tourl = "venda";
				break;
			case 2:
				tourl = "locacao";
				break;
			case 3:
				tourl = "temporada";
				break;
			default:
				tourl = "todos";
		} // switch

		if (!tipoUrl) {
			tipoUrl = "todos";
		}

		$(".sendBusca").attr("href",BASE_URL+retira_acentos(tourl+"/"+tipoUrl.toLowerCase()) + "#!?" + JSON.stringify(pesquisaUrl['pesquisa']));


	}

	$(".sendBusca").click(function(){
		document.location = $(this).attr("href");
	});
	
	function generateGruposCidade( data ){
		var html = "";
		for ( var regiao in data ){
			html += "<div class='Group'>";  
			html += "<div class='GroupName'>" + data[regiao]['name'] + "</div>";
			html += generateCheckBox(data[regiao]['City'] , null,"cidadeCheck",true, "name")
			html += "</div>"; 
		}
		
		$("#cidadeSelect .conteudo-listagem").html(html);
	}
	
	function generateGruposBairros ( data ){
		var html = "";
		for ( var bairro in data ){
			html += "<div class='Group'>";  
			html += "<div class='GroupName'>" + data[bairro]['name'] + "</div>";
			html += generateCheckBox(data[bairro]['Neighborhood'] , null,"bairroCheck",true, "name")
			html += "</div>"; 
		}
		
		$("#bairroSelect .conteudo-listagem").html(html);
	}
	
	function generateGruposZona( data ){
		var html = "";
		for ( var zona in data ){
			html += "<div class='Group'>";  
			html += "<div class='GroupName'>" + data[zona]['name'] + "</div>";
			html += generateCheckBox(data[zona]['Zone'] , null,"zonaCheck",true, "name")
			html += "</div>"; 
		}
		
		$("#zonaSelect .conteudo-listagem").html(html);
	}
	
	
	function generateCheckBox(array, id, attr, returnHtml, valor){

		var html = "<ul>";
		//html += "<li><label><input type='checkbox' name='"+attr+"' class='"+attr+" todos' value='todos'> Todos</label></li>";
		var count = 0;
		
		
		
		for (var element in array ) {
			
			if (!array[element] || array[element] == "null" ){
				continue;
			}

			if (count > maxItensUl ) {
				count = 0;
				html += "</ul> <ul>";
			}
			
			if ( valor ) {
				campo = array[element]["name"];
				id = array[element]["id"]
			} else {
				campo = array[element];
				id = element;
			}
			
			var tooLong = ( campo.length > 25 ) ? "...": ""; 
			html += "<li><label><input type='checkbox' name='"+attr+"' tittle='"+campo+"' class='"+attr+"' value='"+id+"'> "+campo.substr(0,25)+tooLong +"</label></li>";

			count++;
		}

		html += "</ul>";
		if ( returnHtml ) {
			return html;
		}
		$("#"+id).html(html);
	}


	function generateSelect(array, id, attr, label, max,option){
		var html = "<option value=''>"+option+"</option>";;
		var count = 0;
							 
		for ( var element in array ) {
			mostrar = label;
			if (array[element] > 1) {
				mostrar = label+"s";
			}

			if (max > 0 && array[element] > max) {
				array[element] += "+";
			}
			html += "<option value='"+element+"'>"+array[element]+" "+mostrar+"</option>";
		}

		$("."+id).html(html).resetSS();
	}

	function retira_acentos(palavra) {
		com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';
		sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
		nova='';
		for(i=0;i<palavra.length;i++) {
			if (com_acento.search(palavra.substr(i,1))>=0) {
				nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);
			}
			else {
				nova+=palavra.substr(i,1);
			}
		}
		return nova;
	}

	function generateMsg(){
		var label = "";

		$(".cidadeCheck:checked").each(function(){

			if (label == "") {
				label = $(this).parent("label").text();
			}else {
				label += ", "+$(this).parent("label").text();
			}

			if (label.length > 13) {
				label = label.substr(0,11) + "...";
				return;
			}
		});
		if (label != "" && todos['Cidade'] != true) {
			$(".Cidade").text(label);
		}else if (todos['Cidade'] == true){
			$(".Cidade").text("Todas as Cidades");
		}else {
			$(".Cidade").text("Cidade");
		}

		label = "";

		$(".zonaCheck:checked").each(function(){
			if (label == "") {
				label += $(this).parent("label").text();
			}else {
				label += ", "+$(this).parent("label").text();
			}

			if (label.length > 13) {
				label = label.substr(0,11) + "...";
				return;
			}
		});
		
		if (label != "" && todos['Zona'] != true) {
			$(".Zona").text(label);
		}else if( todos['Zona'] == true) {
			$(".Zona").text("Todas as Zonas");
		} else {
			$(".Zona").text("Zona");
		}

		label = "";

		$(".bairroCheck:checked").each(function(){

			if (label == "") {
				label += $(this).parent("label").text();
			}else {
				label += ", "+$(this).parent("label").text();
			}

			if (label.length > 13) {
				label = label.substr(0,11) + "...";
				return;
			}
		});


		if (label != "" && todos['Bairro'] != true) {
			$(".Bairro").text(label);
		}else if ( todos['Bairro'] == true ){
			$(".Bairro").text("Todos os Bairros");
		} else {
			$(".Bairro").text("Bairro");
		}


		label = "";

		$(".regiaoCheck:checked").each(function(){

			if (label == "") {
				label += $(this).parent("label").text();
			}else {
				label += ", "+$(this).parent("label").text();
			}


			if (label.length > 16) {
				label = label.substr(0,11) + "...";
				return;
			}
		});
		
		if (label != "" && todos['Regiao'] != true) {
			$(".Regiao").text(label);
		}else if (todos['Regiao'] == true){
			$(".Regiao").text("Todas as Regiões");
		}else {
			$(".Regiao").text("Regiao");
		}

	}

});
