var TopSearch =
{
	/* global vars */
	arEstados		: [],
	arCidades		: [],
	arBairro		: [],
	arTipo			: [],
	arEtapa			: [],
	arPreco			: [],
	arTamanho		: [],
	arDorms			: [],
	arLazer			: [],
	arZona			: [],
	
	totalXMLsOK		: 0,
	
	curState		: 0,
	curCity			: 0,
	curDistrict		: 0,
	
	tempState		: 0,
	
	arEmpLength		: new Array(),
	
	arAcentos		: ' áâãàäéêèëíîìïóôõòöúûùüç',
	arNormalize		: '+aaaaaeeeeiiiiooooouuuuc',
	
	parsed          : false,
	urlFilters      : false,
	firstSetCity    : true,
	firstSetState	: true,
	xml             : null,
	
	arListIDs       : [],
	strDivisor		: "/",
	strConcatenacao	: ",",
	
	/* methods */
	loadStates		: function()
	{
		/** Carrega os xmls dos estados */
		if(this.arEstados != "")
		{
			this.curState = jQuery('#cEstado').val();
			
			for(w = 0; w < this.arEstados.length; w++)
			{
				jQuery.ajax({
					url		: '_xmldata/empreendimento-lista-' + this.arEstados[w] + '.xml',
					cache	: false,
					type	: 'POST',
					data	: 'idEstado=' + this.arEstados[w],
					dataType: 'xml',
					error	: function()
					{
						
					},
					success	: function(data, request, settings)
					{
						TopSearch.tempState = this.data.split("=")[1];
						
						TopSearch.xml = data;
						TopSearch.feedData(data);
						TopSearch.parseURL();
						
						TopSearch.totalXMLsOK++;
						
						//se estiver dentro da página de busca
						if(Search.SEPage)
						{
							//se o estado buscado é o mesmo que foi carregado (nesse caso São Paulo)
							if( parseInt(jQuery('#cEstado').val()) == TopSearch.tempState )
							{
								TopSearch.curState = jQuery('#cEstado').val();
								
								//salva o objeto xml na função principal da página de busca (Object Search)
								Search.xml = data;
								Search.setValues();
								Search.feedItens();
							}
						}
						else
						{
							if( jQuery('#uf-filter').val() == TopSearch.tempState )
							{
								TopSearch.setState(jQuery('#uf-filter').val());
							}
						}
						TopSearch.defaultValues( TopSearch.tempState );
						
						TopSearch.feedFilters	(data);
						
						if( Search.SEPage )
						{
							if(jQuery('#cEstado').val() == TopSearch.tempState )
							{
								TopSearch.curState = TopSearch.tempState;
								TopSearch.defaultValues( TopSearch.curState );
							}
						}
					}
				});
			}
			
			jQuery('#tipo-filter').bind('change',function() {
				TopSearch.setTipo(jQuery(this).val());
			});
			
			jQuery('#etapa-filter').bind('change',function() {
				TopSearch.setEtapa(jQuery(this).val());
			});
			
			jQuery('#preco-filter').bind('change',function() {
				TopSearch.setPreco(jQuery(this).val());
			});
		}
	},
	
	feedData		: function( data )
	{
		/**
		 * Alimenda os arrays do objeto:
		 * 		arCidades[idEstado][n] - com as cidades
		 * 		arBairros[idCidade][n] - com os bairros
		 * 		arTipo[idEstado][tipo]
		 * 		arEtapa[idEstado][etapa]
		 * 		arPreco[idEstado][preco]
		 * 		arDorms[idEstado][dorm]
		 * 		arEstrutura[idEstado][estrutura]
		 * 		arTamanho[idEstado][tamanho]
		 */
		TopSearch.arCidades  [TopSearch.tempState] = new Array();
		TopSearch.arEmpLength[TopSearch.tempState] = new Array();
		
		var Cs = TopSearch.tempState,strCpValues;
		
		/** @cidade */
		jQuery(data).find('cidade').find('item').each(function(i) {
			
			TopSearch.arCidades[Cs][i]			= new Array();
			TopSearch.arCidades[Cs][i]['id']	= jQuery(this).attr('id');
			TopSearch.arCidades[Cs][i]['label']	= jQuery(this).attr('label');
			TopSearch.arCidades[Cs][i]['list']	= jQuery(this).text().split(",");
			
			var idItem = parseInt(jQuery(this).attr('id'));
			TopSearch.arBairro[idItem] = new Array();
			
			if(Search.campaign)/** @campanha */
			{
				if(Search.arCampaign.matchCount(TopSearch.arCidades[Cs][i]['list']))
				{
					strCpValues = jQuery("#cCidade").val() + "," + jQuery(this).attr('id');
					if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
					
					jQuery("#cCidade").val(strCpValues);
				}
			}
			
			var counter = 0;
			strCpValues="";
			jQuery(data).find('bairro').find('item').each(function(e) {
				if(jQuery(this).attr('idCidade') == idItem)
				{
					TopSearch.arBairro[idItem][counter]				= new Array();
					TopSearch.arBairro[idItem][counter]['idEstado'] = Cs;
					TopSearch.arBairro[idItem][counter]['idBairro']	= jQuery(this).attr('idBairro');
					TopSearch.arBairro[idItem][counter]['idCidade']	= jQuery(this).attr('idCidade');
					TopSearch.arBairro[idItem][counter]['label']	= jQuery(this).attr('label');
					TopSearch.arBairro[idItem][counter]['list']		= jQuery(this).text();
					
					if(Search.campaign)
					{
						if(Search.arCampaign.matchCount(jQuery(this).text().toString().split(",")))
						{
							strCpValues = jQuery("#cBairro").val() + "," + jQuery(this).attr('idBairro');
							if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
							
							jQuery("#cBairro").val(strCpValues);
						}
					}
					
					counter++;
				}
			});
			
			TopSearch.parseValues( jQuery(this).text() );
		});
		
		/** @tipo */
		strCpValues="";
		TopSearch.arTipo[Cs] = new Array();
		jQuery(data).find('tipo').find('item').each(function() {
			if( jQuery(this).text() != "" )
			{
				TopSearch.arTipo[Cs][jQuery(this).attr('id')] = jQuery(this).text();
				if(Search.campaign)
				{
					if(Search.arCampaign.matchCount( jQuery(this).text().toString().split(",") ))
					{
						strCpValues = jQuery("#cTipo").val() + "," + jQuery(this).attr('id');
						if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
						
						jQuery("#cTipo").val(strCpValues);
					}
				}
			}
		});
		
		/** @preço */
		strCpValues="";
		TopSearch.arPreco[Cs] = new Array();
		jQuery(data).find('preco').find('item').each(function() {
			if( jQuery(this).text() != "" )
			{
				TopSearch.arPreco[Cs][jQuery(this).attr('id')] = jQuery(this).text();
				if(Search.campaign)
				{
					if(Search.arCampaign.matchCount( jQuery(this).text().toString().split(",") ))
					{
						strCpValues = jQuery("#cPreco").val() + "," + jQuery(this).attr('id');
						if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
						
						jQuery("#cPreco").val(strCpValues);
					}
				}
			}
		});
		
		/** @etapa */
		strCpValues = "";
		TopSearch.arEtapa[Cs] = new Array();
		jQuery(data).find('etapa').find('item').each(function() {
			if( jQuery(this).text() != "" )
			{
				TopSearch.arEtapa[Cs][jQuery(this).attr('id')] = jQuery(this).text();
				if(Search.campaign)
				{
					if(Search.arCampaign.matchCount( jQuery(this).text().toString().split(",") ))
					{
						strCpValues = jQuery("#cEtapa").val() + "," + jQuery(this).attr('id');
						if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
						
						jQuery("#cEtapa").val(strCpValues);
					}
				}
			}
		});
		
		/** @tamanhos */
		strCpValues="";
		TopSearch.arTamanho[Cs] = new Array();
		jQuery(data).find('tamanho').find('item').each(function() {
			if( jQuery(this).text() != "" )
			{
				TopSearch.arTamanho[Cs][jQuery(this).attr('id')] = jQuery(this).text();
				if(Search.campaign)
				{
					if(Search.arCampaign.matchCount( jQuery(this).text().toString().split(",") ))
					{
						strCpValues = jQuery("#cMetragem").val() + "," + jQuery(this).attr('id');
						if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
						
						jQuery("#cMetragem").val(strCpValues);
					}
				}
			}
		});
		
		/** @dormitórios */
		strCpValues="";
		TopSearch.arDorms[Cs] = new Array();
		jQuery(data).find('dormitorios').find('item').each(function() {
			if( jQuery(this).text() != "" )
			{
				TopSearch.arDorms[Cs][jQuery(this).attr('id')] = jQuery(this).text();
				if(Search.campaign)
				{
					if(Search.arCampaign.matchCount( jQuery(this).text().toString().split(",") ))
					{
						strCpValues = jQuery("#cDorms").val() + "," + jQuery(this).attr('id');
						if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
						
						jQuery("#cDorms").val(strCpValues);
					}
				}
			}
		});
		
		/** @lazer */
		strCpValues="";
		TopSearch.arLazer[Cs] = new Array();
		jQuery(data).find('lazer').find('item').each(function() {
			if( jQuery(this).text() != "" )
			{
				TopSearch.arLazer[Cs][jQuery(this).attr('id')] = jQuery(this).text();
				if(Search.campaign)
				{
					if(Search.arCampaign.matchCount( jQuery(this).text().toString().split(",") ))
					{
						strCpValues = jQuery("#cLazer").val() + "," + jQuery(this).attr('id');
						if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
						
						jQuery("#cLazer").val(strCpValues);
					}
				}
			}
		});
		
		/** @zona */
		strCpValues="";
		TopSearch.arZona[Cs] = new Array();
		jQuery(data).find('zona').find('item').each(function() {
			if( jQuery(this).text() != "" )
			{
				TopSearch.arZona[Cs][jQuery(this).attr('id')] = jQuery(this).text();
				if(Search.campaign)
				{
					if(Search.arCampaign.matchCount( jQuery(this).text().toString().split(",") ))
					{
						strCpValues = jQuery("#cZona").val() + "," + jQuery(this).attr('id');
						if(strCpValues.charAt(0) == ",") strCpValues = strCpValues.substring(1);
						
						jQuery("#cZona").val(strCpValues);
					}
				}
			}
		});
		
		if( jQuery('#uf-filter').val() == TopSearch.tempState )
		{
			TopSearch.feedComboBox();
		}
		
		jQuery('#cidade-filter').unbind('change');
		jQuery('#cidade-filter').bind('change', { obS: jQuery('#cidade-filter') }, TopSearch.setCity);
	},
	feedComboBox	: function()
	{
		/** @alimenta as cidades */
		for(city in TopSearch.arCidades[TopSearch.tempState])
		{
			if(typeof(TopSearch.arCidades[TopSearch.tempState][city]) != 'function')
			{
				nCidade = TopSearch.arCidades[TopSearch.tempState][city]['label'];
				uid		= TopSearch.arCidades[TopSearch.tempState][city]['id'];
				
				jQuery('#cidade-filter').append('<option value="' + uid + '">' + nCidade + '</option>');
			}
		}
		/** @alimenta os tipos de obras */
		for(tipo in TopSearch.arTipo[TopSearch.tempState])
		{
			if(typeof(TopSearch.arTipo[TopSearch.tempState][tipo]) != 'function')
			{
				nTypes = TopSearch.arTipo[TopSearch.tempState][tipo].split(',');
				
				jQuery(TopSearch.xml).find('tipo').find('item').each(function() {
					
					if(jQuery(this).text() != "")
					{
						if(nTypes.matchCount(jQuery(this).text().split(',')))
						{
							jQuery('#tipo-filter').append('<option value="'+jQuery(this).attr('id')+'">' + jQuery(this).attr('label') + '</option>');
						}
					}
				})
			}
		}
		/** @alimenta as etapas */
		
		for(etapa in TopSearch.arEtapa[TopSearch.tempState])
		{
			if(typeof(TopSearch.arEtapa[TopSearch.tempState][etapa]) != 'function')
			{
				nEtapas = TopSearch.arEtapa[TopSearch.tempState][etapa].split(',');
				jQuery(TopSearch.xml).find('etapa').find('item').each(function() {
					if(jQuery(this).text() != "")
					{
						if(nEtapas.matchCount( jQuery(this).text().split(',') ))
						{
							jQuery('#etapa-filter').append('<option value="'+jQuery(this).attr('id')+'">' + jQuery(this).attr('label') + '</option>');
						}
					}
				})
			}
		}
		
		/** @alimenta os preços */
		for(preco in TopSearch.arPreco[TopSearch.tempState])
		{
			if(typeof(TopSearch.arPreco[TopSearch.tempState][preco]) != 'function')
			{
				nPreco = TopSearch.arPreco[TopSearch.tempState][preco].split(',');
				jQuery(TopSearch.xml).find('preco').find('item').each(function() {
					if(jQuery(this).text() != "")
					{
						if(nPreco.matchCount( jQuery(this).text().split(',') ))
						{
							jQuery('#preco-filter').append('<option value="'+jQuery(this).attr('id')+'">'+jQuery(this).attr('label')+'</option>');
						}
					}
				});
			}
		}
	},
	feedFilters		: function(data)
	{
		jQuery('#tipo-filter').removeAttr('disabled');
		jQuery('#etapa-filter').removeAttr('disabled');
		jQuery('#preco-filter').removeAttr('disabled');
	},
	
	/**
	* Parseia, em "Cidade" os valores que vieram pela url
	*/
	parseURL        : function()
	{
		if(!TopSearch.parsed) //Garante que parseie apenas uma vez
		{
			if(Search.campaign) //case esteja em uma campanha
			{
				//trace(Search.arCampaign);
			}
			
			/** @estado */
			if(jQuery('#cEstado').val() == TopSearch.tempState)
			{
				TopSearch.parsed = true;
				var tmpValues = "";
				
				/** @cidade */
				if(jQuery('#cCidade').val() == "")
				{
					if( Search.hashValues[1] != undefined )
					{
						var arValues = Search.hashValues[1].toString().split(',');
						
						for( cf in TopSearch.arCidades[TopSearch.tempState] )
						{
							if( typeof(TopSearch.arCidades[TopSearch.tempState][cf]) != 'function' )
							{
								nCidade		= TopSearch.arCidades[TopSearch.tempState][cf]['label'];
								idCidade	= TopSearch.arCidades[TopSearch.tempState][cf]['id'];
								
								for(w=0;w<arValues.length;w++)
								{
									if(TopSearch.normalize(nCidade.toLowerCase()) == arValues[w])
									{
										tmpValues += idCidade + TopSearch.strConcatenacao;
									}
								}
							}
						}
						jQuery('#cCidade').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
				
				/** @bairros */
				if(jQuery('#cBairro').val() == "")
				{
					if(Search.hashValues[2] != undefined)
					{
						tmpValues	= "";
						arValues	= Search.hashValues[2].toString().split(",");
						
						jQuery(TopSearch.xml).find('bairro').find('item').each(function() {
							idBairro = jQuery(this).attr('idBairro');
							for(w=0;w<arValues.length;w++)
							{
								
								if(TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w])
								{
									tmpValues += idBairro + TopSearch.strConcatenacao;
								}
							}
						});
						if(Search.campaign == true){
							jQuery('#cBairro').val( tmpValues.substring(0,tmpValues.length-1) );
						}
					}
				}
				
				/** @url params for values "Tipo" */
				if(jQuery('#cTipo').val() == "")
				{
					if(Search.hashValues[3] != undefined)
					{
						tmpValues	= "";
						arValues	= Search.hashValues[3].toString().split(",");
						
						jQuery(TopSearch.xml).find('tipo').find('item').each(function() {
							for(w=0;w<arValues.length;w++)
							{
								idTipo = jQuery(this).attr('id');
								if( TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w] )
								{
									tmpValues += idTipo + TopSearch.strConcatenacao;
								}
							}
						});
						jQuery('#cTipo').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
				
				/** @url params for values "Etapa" */
				if(jQuery('#cEtapa').val() == "")
				{
					if(Search.hashValues[4] != undefined)
					{
						tmpValues	= "";
						arValues	= Search.hashValues[4].toString().split(",");
						
						jQuery(TopSearch.xml).find('etapa').find('item').each(function() {
							for(w=0;w<arValues.length;w++)
							{
								idEtapa = jQuery(this).attr('id');
								if( TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w] )
								{
									tmpValues += idEtapa + TopSearch.strConcatenacao;
								}
							}
						});
						jQuery('#cEtapa').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
				
				/** @url params for values "Preço" */
				if(jQuery('#cPreco').val() == "")
				{
					if(Search.hashValues[5] != undefined)
					{
						tmpValues	= "";
						arValues	= Search.hashValues[5].toString().split(",");
						
						jQuery(TopSearch.xml).find('preco').find('item').each(function() {
							for(w=0;w < arValues.length;w++)
							{
								idPreco = jQuery(this).attr('id');
								if( TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w] )
								{
									tmpValues += idPreco + TopSearch.strConcatenacao;
								}
							}
						});
						jQuery('#cPreco').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
				
				/***
				 * URLs adicionais, não fazem parte da busca,
				 * somente tem aqui, nos filtros laterais
				 */
				
				/** @dormitorios, 6 */
				if( jQuery('#cDorms').val() == "" )
				{
					if( Search.hashValues[6] != undefined )
					{
						tmpValues	= "";
						arValues	= Search.hashValues[6].toString().split(",");
						
						jQuery(TopSearch.xml).find('dormitorios').find('item').each(function() {
							for(w=0;w<arValues.length;w++)
							{
								idDorm = jQuery(this).attr('id');
								
								if( TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w].toString().split("-")[0] )
								{
									tmpValues += idDorm + TopSearch.strConcatenacao;
								}
							}
						});
						jQuery('#cDorms').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
				
				/** @metragem, 7 */
				if( jQuery('#cMetragem').val() == "" )
				{
					if( Search.hashValues[7] != undefined )
					{
						tmpValues	= "";
						arValues	= Search.hashValues[7].toString().split(",");
						
						jQuery(TopSearch.xml).find('tamanho').find('item').each(function() {
							for(w=0;w<arValues.length;w++)
							{
								idTamanho = jQuery(this).attr('id');
								if( TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w] )
								{
									tmpValues += idTamanho + TopSearch.strConcatenacao;
								}
							}
						});
						jQuery('#cMetragem').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
				
				/** @lazer, 8 */
				if( jQuery('#cLazer').val() == "" )
				{
					if( Search.hashValues[8] != undefined )
					{
						tmpValues	= "";
						arValues	= Search.hashValues[8].toString().split(",");
						
						jQuery(TopSearch.xml).find('lazer').find('item').each(function() {
							for(w=0;w<arValues.length;w++)
							{
								idLazer = jQuery(this).attr('id');
								if( TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w] )
								{
									tmpValues += idLazer + TopSearch.strConcatenacao;
								}
							}
						});
						jQuery('#cLazer').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
				
				/** @zona, 9 */
				if( jQuery('#cZona').val() == "" )
				{
					if( Search.hashValues[9] != undefined )
					{
						tmpValues	= "";
						arValues	= Search.hashValues[9].toString().split(",");
						
						jQuery(TopSearch.xml).find('zona').find('item').each(function() {
							for(w=0;w<arValues.length;w++)
							{
								idZona = jQuery(this).attr('id');
								if( TopSearch.normalize(jQuery(this).attr('label').toLowerCase()) == arValues[w].toString().split("-")[1] )
								{
									tmpValues += idZona + TopSearch.strConcatenacao;
								}
							}
						});
						jQuery('#cZona').val( tmpValues.substring(0,tmpValues.length-1) );
					}
				}
			}
		}
	},
	setState		: function(idEstado)
	{
		TopSearch.curState  = idEstado;
		TopSearch.arListIDs = [];
		
		if( TopSearch.arCidades[idEstado] != undefined )
		{
			//Existe cidades que atendem esse critério
			jQuery('#cidade-filter').removeAttr('disabled');
			
			jQuery('#cidade-filter').empty();
			jQuery('#cidade-filter').append('<option value="">Cidade (todas)</selecione>\n');
			
			jQuery('#bairro-filter').empty();
			jQuery('#bairro-filter').append('<option value="">Bairro (todos)</option>\n');
			
			for( w = 0; w < TopSearch.arCidades[TopSearch.curState].length; w++ )
			{
				jQuery('#cidade-filter').append('<option value="' + TopSearch.arCidades[TopSearch.curState][w]['id'] + '">' + TopSearch.arCidades[TopSearch.curState][w]['label'] + '</option>\n');
			}
			
			for(w=0;w<TopSearch.arCidades[idEstado].length;w++)
			{
				this.arListIDs.uniquePush(TopSearch.arCidades[idEstado][w]['list']);
			}
			this.updateFields('estado');
		}
		else
		{
			//se não houver, desabilita o combo cidades
			jQuery('#cidade-filter').attr('disabled','disabled');
			jQuery('#cidade-filter option:first').attr('selected','true');
		}
	},
	setCity		: function(obS)
	{
		if( jQuery(obS.data.obS).val() != "" )
		{
			var uf = jQuery('#uf-filter').val();
			
			TopSearch.curCity = jQuery(obS.data.obS).val();
			
			var index = parseInt( jQuery(obS.data.obS).val() );
			
			jQuery('#bairro-filter').removeAttr('disabled');
			jQuery('#bairro-filter').empty();
			jQuery('#bairro-filter').append('<option value="">Bairro (todos)</option>\n');
			
			jQuery('#bairro-filter').unbind('change');
			jQuery('#bairro-filter').bind('change',function(e) {
				TopSearch.curDistrict = e.target.value;
				TopSearch.setBairro( e.target.value, jQuery('#cidade-filter').val() );
			});
			
			for( w = 0; w < TopSearch.arBairro[jQuery(obS.data.obS).val()].length; w++ )
			{
				var bairroLabel = TopSearch.arBairro[index][w]['label'];
				jQuery('#bairro-filter').append('<option value="' + TopSearch.arBairro[index][w]['idBairro'] + '">' + bairroLabel + '</option>\n');
			}
			
			var count_Cidade = 0;
			
			for(w = 0; w < TopSearch.arCidades[uf].length; w++)
			{
				if( TopSearch.arCidades[uf][w]['id'] == index )
				{
					count_Cidade = TopSearch.arCidades[uf][w]['list'].length;
					break;
				}
			}
			
			/** @bairro */
			if(jQuery('#cBairro').val() == "")
			{
				if(Search.hashValues[2] != undefined)
				{
					jQuery('#bairro-filter option').each(function() {
						if( Search.hashValues[2] == TopSearch.normalize(jQuery(this).text().toLowerCase()) )
						{
							jQuery('#bairro-filter').val( jQuery(this).val() );
							Search.setValues();
							Search.feedItens();
						}
					});
				}
			}
			
			for(l=0;l < TopSearch.arCidades[uf].length;l++)
			{
				if( jQuery(obS.data.obS).val() == TopSearch.arCidades[uf][l]['id'] )
				{
					break;
				}
			}
			
			TopSearch.countItens();
			
			TopSearch.arListIDs = TopSearch.arEmpLength[ uf ].intersect( TopSearch.arCidades[uf][l]['list'] );
			TopSearch.updateFields('cidade');
			
			jQuery('#btn-buscar-total').text('ENCONTRAR (' + TopSearch.arListIDs.length + ')');
		}
		else
		{
			TopSearch.countItens();
			TopSearch.updateFields('');
		}
	},
	setBairro       : function(idBairro,idCidade)
	{
		TopSearch.countItens();
		TopSearch.updateFields('bairro');
		return false;
	
		if( idCidade!="" && idBairro != "" )
		{
			for(c=0;c<TopSearch.arBairro[idCidade].length;c++)
			{
				if( idBairro == TopSearch.arBairro[idCidade][c]['idBairro'] )
					break;
			}
			TopSearch.countItens();
			TopSearch.updateFields('bairro');
		}
		else
		{
			TopSearch.countItens();
		}
		return true;
	},
	parseValues		: function(values)
	{
		/** 
		* parseia os valores encontrados nos nodes de cidades para preencher o total do botão enviar
		*/
		var arValues = values.split(",");
		
		for(w = 0; w < arValues.length; w++)
		{
			TopSearch.arEmpLength[TopSearch.tempState].push(arValues[w]);
		}
	},
	setTipo     : function(idTipo)
	{
		TopSearch.countItens();
		TopSearch.updateFields('tipo');
	},
	setEtapa       : function(idEtapa)
	{
		TopSearch.countItens();
		TopSearch.updateFields('etapa');
	},
	setPreco        : function(idPreco)
	{
		TopSearch.countItens();
		TopSearch.updateFields('preco');
	},
	
	/**
	* Getters dos valores de url
	*/
	getStateValue	: function()
	{
		if( jQuery('#cEstado').val() == "" )
		{
			return jQuery('#uf-filter option:selected').text().toLowerCase();
		}
		
		var uf="";
		jQuery('#uf-filter option').each(function() {
			if(jQuery('#cEstado').val() == jQuery(this).val())
			{
				uf = jQuery(this).text().toLowerCase();
			}
		});
		
		return uf;
	},
	getCityValue	: function()
	{
		return TopSearch.normalize(jQuery('#cidade-filter option:selected').text().toLowerCase());
	},
	getDistrictValue: function()
	{
		return TopSearch.normalize(jQuery('#bairro-filter option:selected').text().toLowerCase());
	},
	normalize	: function(value)
	{
		var re, acento, fs;
		
		for(y = 0; y < TopSearch.arAcentos.length; y++)
		{
			acento = TopSearch.arAcentos.charAt(y);
			
			re		= new RegExp(RegExp.quote(acento), "g");
			value	= value.replace(re,TopSearch.arNormalize.charAt(y));
		}
		
		return value;
	},
	
	makeSearch	: function(obF)
	{
		var estado, cidade, bairro, tipo, etapa, preco, urlTo;
		urlTo = "#" + TopSearch.getStateValue();
		
		if( jQuery('#cidade-filter :selected').text().toLowerCase().indexOf('(todas)') < 0 )
			urlTo += this.strDivisor + TopSearch.getCityValue();
		else
			urlTo += this.strDivisor;
		
		if( jQuery('#bairro-filter :selected').text().toLowerCase().indexOf('(todos)') < 0 && jQuery('#bairro-filter :selected').text().toLowerCase().indexOf('bairro') < 0 )
			urlTo += this.strDivisor + TopSearch.getDistrictValue();
		else
			urlTo += this.strDivisor;
		
		if( jQuery('#tipo-filter :selected').text().toLowerCase().indexOf('(todos)') < 0 )
			urlTo += this.strDivisor + this.normalize(jQuery('#tipo-filter :selected').text().toLowerCase());
		else
			urlTo += this.strDivisor;
		
		if( jQuery('#etapa-filter :selected').text().toLowerCase().indexOf('(todas)') < 0 )
			urlTo += this.strDivisor + this.normalize(jQuery('#etapa-filter option:selected').text().toLowerCase());
		else
			urlTo += this.strDivisor;
		
		if( jQuery('#preco-filter :selected').text().toLowerCase().indexOf('faixa') < 0 )
		{
			urlTo += this.strDivisor + this.normalize(jQuery('#preco-filter option:selected').text().toLowerCase());
		}
		else
			urlTo += this.strDivisor;
		
		
		for(u=urlTo.length;u>=0;u--)
		{
			if(urlTo.charAt(u) == '')
				continue;
			
			if(urlTo.charAt(u) != this.strDivisor)
				break;
			else
				urlTo = urlTo.substring(0,urlTo.length-1)
		}
		
		jQuery('#frmTopSearch').attr('action','busca.php' + urlTo);
		jQuery('#frmTopSearch').submit();
		
		return true;
	},
	
	defaultValues : function(id)
	{
		//seleciona o estado
		//jQuery('#uf-filter').val(id);
		
		if(Search.SEPage)
		{
			if(!Search.firstLoaded)
			{
				Search.feedItens();
			}
		}
	},
	
	updateFields   : function(from)
	{
		var uf = jQuery('#uf-filter').val();
		
		if(from != undefined)
		{
			//if(!TopSearch.firstSetCity && !TopSearch.firstSetState)
			{
				/** adiciona a cidade ao filtro, caso esteja uma cidade selecionada */
				if(from != 'cidade' && TopSearch.curCity != 0)
				{
					for(k in TopSearch.arCidades[TopSearch.curState])
					{
						
						if( typeof(TopSearch.arCidades[TopSearch.curState][k]) != "function" )
						{
							var arItens = TopSearch.arCidades[TopSearch.curState][k]['list'].toString().split(',');
							if( arItens.matchCount(TopSearch.arEmpLength[uf]) )
							{
								if( jQuery('#cidade-filter').val() == TopSearch.arCidades[uf][k]['id'] )
								{
									TopSearch.arListIDs = TopSearch.arListIDs.intersect(arItens);
								}
							}
						}
					}
				}
				
				/** adiciona o bairro ao filtro */
				if(from != 'bairro' && TopSearch.curCity != 0) //não veio do filtro "bairro" e nem a cidade esta vazia
				{
					if(jQuery('#bairro-filter').val() == "") //porem se o filtro "bairro" já estiver selecionado, pula isso
					{
						jQuery('#bairro-filter').empty();
						jQuery('#bairro-filter').append('<option value="">Bairro (todos)</option>');
						
						for(b in TopSearch.arBairro[TopSearch.curCity] )
						{
							if(typeof(TopSearch.arBairro[TopSearch.curCity][b]) != 'function')
							{
								var arItens = TopSearch.arBairro[TopSearch.curCity][b]['list'].toString().split(',');
								if( arItens.matchCount( TopSearch.arEmpLength[uf] ) )
								{
									jQuery('#bairro-filter').append('<option value="' + TopSearch.arBairro[TopSearch.curCity][b]['idBairro'] + '">'+ TopSearch.arBairro[TopSearch.curCity][b]['label'] +'</option>');
								}
							}
						}
					}
				}
				
				/** adiciona o tipo ao filtro */
				jQuery('#tipo-filter').removeAttr('disabled');
				if( from != 'tipo' && jQuery('#tipo-filter').val() == "" )
				{
					var tipo_OK = false;
					jQuery('#tipo-filter').empty();
					jQuery('#tipo-filter').append('<option value="">Tipo (todos)</option>');
					
					for(t in TopSearch.arTipo[uf] )
					{
						if(typeof(TopSearch.arTipo[uf][t]) != 'function')
						{
							if( TopSearch.arListIDs.matchCount(TopSearch.arTipo[uf][t].toString().split(',')) )
							{
								jQuery(TopSearch.xml).find('tipo').find('item').each(function() {
									if( jQuery(this).attr('id') == t )
									{
										tipo_OK = true;
										jQuery('#tipo-filter').append('<option value="'+t+'">' + jQuery(this).attr('label') + '</option>');
									}
								});
							}
						}
					}
					if(!tipo_OK)
						jQuery('#tipo-filter').attr('disabled','disabled');
				}
				
				/** adiciona a etapa ao filtro */
				jQuery('#etapa-filter').removeAttr('disabled');
				if( from != 'etapa' && jQuery('#etapa-filter').val() == "" )
				{
					var etapa_OK = false;
					jQuery('#etapa-filter').empty();
					jQuery('#etapa-filter').append('<option value="">Etapa da obra (todas)</option>');
					
					for(t in TopSearch.arEtapa[uf] )
					{						
						if(typeof(TopSearch.arEtapa[uf][t]) != 'function')
						{
							if( TopSearch.arListIDs.matchCount(TopSearch.arEtapa[uf][t].toString().split(',')) )
							{
								jQuery(TopSearch.xml).find('etapa').find('item').each(function() {
									if( jQuery(this).attr('id') == t )
									{
										etapa_OK = true;
										jQuery('#etapa-filter').append('<option value="'+t+'">' + jQuery(this).attr('label') + '</option>');
									}
								});
							}
						}
					}
					if(!etapa_OK)
						jQuery('#etapa-filter').attr('disabled','disabled');
				}
				
				/** adiciona o preço ao filtro */
				jQuery('#preco-filter').removeAttr('disabled');
				if( from != 'preco' )
				{
					var preco_OK = false;
					jQuery('#preco-filter').empty();
					jQuery('#preco-filter').append('<option value="">Faixa de preço (R$)</option>');
					
					
					for(t in TopSearch.arPreco[uf] )
					{
						if(typeof(TopSearch.arPreco[uf][t]) != 'function')
						{
							var listIds = TopSearch.arPreco[uf][t].toString().split(',');
							
							if( TopSearch.arListIDs.matchCount( listIds ) )
							{
								var total = jQuery(TopSearch.xml).find('preco').find('item').length;
								
								var y = 0;
								for(w = 0; w < total; w++)
								{
									var item = jQuery(TopSearch.xml).find('preco').find('item');
									
									if( jQuery(item).eq(y).attr('id') == t )
									{
										if(jQuery(item).eq(y).attr('id') != undefined)
										{
											jQuery('#preco-filter').append('<option value="'+t+'">' + jQuery(item).eq(y).attr('label') + '</option>\n');
											preco_OK = true;
										}
									}
									y++;
								}
							}
						}
					}
					if(!preco_OK)
						jQuery('#preco-filter').attr('disabled','disabled');
				}
				
				if(this.firstSetCity == false)
				{
					jQuery('#btn-buscar-total').text('ENCONTRAR (' + TopSearch.arListIDs.length + ')');
				}
				else
					jQuery('#btn-buscar-total').text('ENCONTRAR');
			}
			
			TopSearch.firstSetCity = false;
			TopSearch.firstSetState = false;
		}
	},
	
	/**
	* Soma todos os empreendimentos, contando Estado -> Cidade -> Bairro -> Tipo -> Etapa -> Preco
	*/
	countItens      : function()
	{
		var ab_count = 0;
		for(ab in TopSearch.arCidades)
		{
			if(typeof(TopSearch.arCidades[ab]) != 'function')
			{
				bc_count = 0;
				for(bc in TopSearch.arCidades[ab])
				{
					if(typeof(TopSearch.arCidades[ab][bc]) != 'function')
					{
						if(TopSearch.arCidades[ab][bc]['id'] == jQuery('#cidade-filter').val())
							break;
						bc_count++;
					}
				}
				ab_count++;
			}
		}
		
		if(TopSearch.arCidades[TopSearch.curState] != undefined)
		{
			if(bc_count < TopSearch.arCidades[TopSearch.curState].length)
			{
				for(cy in TopSearch.arCidades[TopSearch.curState] )
				{
					if(typeof(TopSearch.arCidades[TopSearch.curState][cy]) != 'function')
					{
						TopSearch.arListIDs.uniquePush(TopSearch.arCidades[TopSearch.curState][cy]['list']);
					}
				}
			}
			else
			{
				for(w=0;w<TopSearch.arCidades[TopSearch.curState].length;w++)
				{
					TopSearch.arListIDs.uniquePush(TopSearch.arCidades[TopSearch.curState][w]['list']);
				}
			}
		}
		
		if( TopSearch.curCity != 0 )
		{
			if(jQuery('#bairro-filter').val() != "")
			{
				for( n in TopSearch.arBairro[TopSearch.curCity] )
				{
					if(TopSearch.arBairro[TopSearch.curCity][n]['idBairro'] == jQuery('#bairro-filter').val())
					{
						break;
					}
				}
				if(n >= 0)
				{
					TopSearch.arListIDs = TopSearch.arBairro[TopSearch.curCity][n]['list'].split(',');
				}
			}
		}
		
		if(jQuery('#tipo-filter').val() != "")
		{
			for(n in TopSearch.arTipo[TopSearch.curState])
			{
				if(jQuery('#tipo-filter').val() == n)
				{
					break;
				}
			}
			
			var arItens = TopSearch.arTipo[TopSearch.curState][n].split(',');
			TopSearch.arListIDs = arItens.intersect(TopSearch.arListIDs);
		}
		
		if(jQuery('#etapa-filter').val() != "")
		{
			for(n in TopSearch.arEtapa[TopSearch.curState])
			{
				if(jQuery('#etapa-filter').val() == n)
				{
					break;
				}
			}
			
			var arItens = TopSearch.arEtapa[TopSearch.curState][n].split(',');
			TopSearch.arListIDs = arItens.intersect(TopSearch.arListIDs);
		}
		
		if(jQuery('#preco-filter').val() != "")
		{
			for(n in TopSearch.arPreco[TopSearch.curState])
			{
				if(jQuery('#preco-filter').val() == n)
				{
					break;
				}
			}
			
			var arItens = TopSearch.arPreco[TopSearch.curState][n].split(',');
			TopSearch.arListIDs = arItens.intersect( TopSearch.arListIDs );
		}
	}
}

jQuery(function()
{
	TopSearch.loadStates();
	
	jQuery('#btn-buscar-total').bind(
		'click',
		function(ev)
		{
			TopSearch.makeSearch();
			return true;
		}
	);
});

RegExp.quote = function(S) { return S.replace(/([.?*+^$[\]\\(){}-])/g,'\\$1'); }

function trace()
{
	var str="";
	for(w=0;w<arguments.length;w++)
	{
		str+=arguments[w]+' ';
	}
	str = str.substring(0,str.length-1);
	
	if ( jQuery.browser.msie ) alert(str)
	else console.info(str);
}

