var filters;
var pre_filters;
var ajax;
var ajax_stats;
var baseurl;
var page			= 1;
var total_imv	= 0;
var update_msg = null;
var limit_imv	= -1;
var bold_imv	= -1;
var analytics	= null;
var cities		= [];
var states		= [];
var neighs		= [];
var location_index	= 1;
var location_color	= null;
var location_before	= null;
var custom_filters	= [];
var stats_filters		= [];
var detail = false;
var home_type = -1; // 1-sell, 2-rent

function init_filters(ajax_call){
	filters		= [];
	pre_filters = [];
	try {
		var inputs			= document.getElementById("filtros").getElementsByTagName("input");
		var selects			= document.getElementById("filtros").getElementsByTagName("select");
		var collections	= [inputs,selects];
		var collection, name, type, obj, city, neighborhood, state, url, anchor, search;

		city = "";
		neighborhood = "";
		state	= "";

		try {
			for(var c=0; c<collections.length; c++){
				collection = collections[c];
				for(var i=0; i<collection.length; i++){
					obj	= collection[i];
					name	= obj.name;
					type	= obj.type;
					if(name.length<1)
						continue;
					if(type=="checkbox"){
						if(obj.value=="#")
							obj.onclick = all_and_query;
						else
							obj.onclick = other_and_query;
					}else if(type=="text")
						obj.onblur	= rest_and_query;
					else
						obj.onchange = rest_and_query;
					filters[collection[i].name] = collection[i].type;
				}
			}
		}catch(ec){
			alert("ERRO: init_filters: filter collection: "+ec);
		}

		try {
			ajax			= get_http_request();
			ajax_stats	= get_http_request();
			baseurl		= location.protocol+"//"+location.host+location.pathname+(/\?$/.test(location.href)?"?":location.search);
			url			= location.href;
			anchor		= location.hash.substring(1);
			search		= location.search.substring(1);
		}catch(ep){
			alert("ERRO: init_filters: processing ajax and url: "+ep);
		}

		// search for page on the anchor
		try {
			page_search = /(page=)(\d+)/.exec(location.hash);
			if(page_search && page_search.length==3){
				page = parseInt(page_search[2]);
				enable_next_page(page>1);
				enable_prev_page(page>1);
				update_page_num();
			}
		}catch(ea){
			alert("ERRO: init_filters: anchors: "+ea);
		}

		// translate the URL to the parameters
		try {
			//                            http://                vericia.com            SP          Sao Paulo   Pinheiros   Artur de Azevedo
			var reg		= new RegExp("^("+location.protocol+"//"+location.host+")+(\/)?(\\w+)?(\/)?(\\w+)?(\/)?(\\w+)?(\/)?(\\w+)?(.*)$");
			var regd		= new RegExp("^("+location.protocol+"//"+location.host+")+(\/[a-z]+\/)+([0-9]{1,15})+(\/)?(.*)$");
			home_type	= 1;	// default is sell

			// special cases ...
			if(/para-alugar/.test(location.href))
				reg = new RegExp("^("+location.protocol+"//"+location.host+"\/para-alugar)+(\/)?(\\w+)?(\/)?(\\w+)?(\/)?(\\w+)?(\/)?(\\w+)?(.*)$");

			if(/para-alugar/.test(location.href) ||
				/aluguel/.test(location.href)){
				custom_filters.push("home_type=2");
				stats_filters.push("type=2");
				home_type = 2; // we're renting!
			}
			var bold_s  = "";

			// detail! 
			if(regd.test(url)){
				detail = true;
				// search for info ...
				var info = document.getElementById("info");
				try {
					if(info){
						state				= get_elements_by_class_name(info,"state")[0].innerHTML.replace(/^\s+/,"").replace(/\s+$/,"");
						city				= get_elements_by_class_name(info,"city")[0].innerHTML.replace(/^\s+/,"").replace(/\s+$/,"");
						neighborhood	= get_elements_by_class_name(info,"neighborhood")[0].innerHTML.replace(/^\s+/,"").replace(/\s+$/,"");

						if(state.length<1 || city.length<1 || neighborhood.length<1)
							info = false;
					}
				}catch(ei){
					info = false;
				}

				// default values
				if(!info){
					state				= "SP";
					city				= "Sao_Paulo";
					neighborhood	= "Itaim_Bibi";
				}
				bold_rst		= regd.exec(url);
				bold_imv		= bold_rst[3];
				limit_imv	= 4;
				bold_s		= get_bold_url();
			}else{
				var tokens	= reg.exec(url);
				var keys		= [[3,"state"],[5,"city"],[7,"neighborhood"],[9,"street"]];
				for(var i=0; i<keys.length; i++){
					var ref = keys[i];
					var val = tokens[ref[0]];
					var key = ref[1];
					if(!val || val.length<1)
						continue;
					eval(key+"=\""+val+"\"");
				}
			}
			states[0]	= state;
			cities[0]	= city.replace(/^\s+/,"").replace(/\s+$/,"");
			neighs[0]	= neighborhood.replace(/^\s+/,"").replace(/\s+$/,"");

			// if not on detail page, try to render the statistics
			if(!detail){
				ajax_queues["stats"] = [];
				reflect_statistics();
			}

			if(ajax_call){
				update(query_locations()+"&"+anchor+bold_s+"&"+custom_filters.join("&"));
			}else{
				update_controls(anchor+"&"+search);
				update_links(anchor+"&"+search);
				update_page();
			}
		}catch(eu){
			alert("ERRO: init_filters: translate URL: "+eu);
		}

		// pre filters
		try{
			pre_filters["radius"] = [pega_coordenadas,[point]];
		}catch(pf){
			alert("ERRO: pre filters: "+pf);
		}

		// autocompletes
		try {
			$("#imob_complete").autocomplete("/busca_imob", {width: 260,selectFirst: false,extraParams:{city:cities[0],state:states[0],home_type:home_type}});
			$("#imob_complete").result(function(event,data,formatted){
				if(!data)
					return false;
				var reg = /(.*)(<span>)([\d,]+)(<\/span>)/;
				if(reg.test(data)){
					var tokens = reg.exec(data);
					$("#imob_complete").val(tokens[1]);
					$("#imob_id").val(tokens[3]);
				}
				rest_and_query();
			});
		}catch(ia){
			alert("ERRO: imob autocomplete: "+ia);
		}

		try {
			$("#location_complete").autocomplete("/ac_location", {width: 260,selectFirst: false}).change(function(){ location_before = $(this).val(); });
			$("#location_complete").result(function(event,data,formatted){
				if(!data)
					return false;
				add_location(formatted);
			});
			$("#location_complete").val(get_default_location_text());
		}catch(la){
			alert("ERRO: location autocomplete: "+la);
		}
	}catch(e){
		alert("ERRO: init_filters: "+e);
	}
}

function reflect_statistics(){
	var this_city, this_neigh, this_url;
	try {
		if(!document.getElementById("dyn_statistics"))
			return;
		$("#dyn_statistics").empty();
		for(var i=0; i<cities.length; i++){
			this_url = location.protocol+"//"+location.host+"/preco_medio/?";
			if(!cities[i])
				continue;
			this_url += "state="+states[i];
			this_url += "&city="+cities[i];
			if(neighs[i])
				this_url += "&neighborhood="+neighs[i];
			if(stats_filters.length>0)
				this_url += "&"+stats_filters[0];
			ajax_queues["stats"].push(this_url);
		}
		query_statistic();
	}catch(e){
		alert("ERRO: reflect_statistics: "+e);
	}
}

function query_statistic(){
	ajax_send(ajax_stats,"get",ajax_queues["stats"].shift(),add_statistic);
}

function add_statistic(){
	try {
		if(ajax_stats.readyState==4 && ajax_stats.status==200){
			$(ajax_stats.responseText).appendTo("#dyn_statistics");
			if(ajax_queues["stats"].length>0)
				setTimeout("query_statistic()",250);
		}
	}catch(e){
		alert("ERRO: add_statistic: "+e);
	}
}

function add_location(data){
	var locations	= document.getElementById("locations");
	var locationt	= document.getElementById("location_complete");
	var clocation	= document.getElementById("custom_location");
	var defaultt	= "Bairro, cidade, UF";
	var noloc	   = /Localidade inexistente/;

	if(noloc.test(data)){
		locationt.value = location_before;
		return false;
	}
	if(!locations)
		return;
	if(!data && locationt.value!=defaultt)
		data = locationt.value;
	if(data.length<1)		
		return;
	if(location_exists(data))
		return;
	if(data.length<1)
		return;

	if(data.length>0 && data!=get_default_location_text()){
		var tokens = data.split(",");
		neighs[location_index]	= tokens.length>2 ? tokens.shift().replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s/g,"_") : "";
		cities[location_index]	= tokens.shift().replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s/g,"_");
		states[location_index]	= tokens.shift().replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s/g,"_");
		location_index ++;
	}

	if(!location_color){
		location_color = locationt.style.color;
		locationt.onblur = function(){
			this.value = defaultt;
			this.style.color = "#aaa";
		}
		locationt.onfocus = function(){
			this.value = "";
			this.style.color = location_color;
		}
		locationt.value = defaultt;
		locationt.style.color = "#aaa";
	}
	reflect_location();
	clocation.focus();
}

function delete_location(idx) {
	var qtde = 0;
	for(var i=0; i<cities.length; i++)
		qtde += cities[i] ? 1 : 0;
	if(qtde>1){
		neighs[idx]	= null; 
		cities[idx]	= null;
		states[idx]	= null;
		reflect_location();
	}else
		alert("Você não pode remover a última localidade!");
}

function get_location_text(idx){
	var txt = "";
	try {
		if(neighs[idx].length>0)
			txt += neighs[idx].replace(/_/g," ")+", ";
		txt += cities[idx].replace(/_/g," ")+", "+states[idx];
	}catch(e){
		alert("ERRO: get_location_text: "+e);
	}
	return txt;
}

function get_default_location_text(){
	return get_location_text(0);
}

function reflect_location(){
	try {
		var locations	= document.getElementById("locations");
		var li, lis, txt;

		// remove
		while(locations.childNodes[0])
			locations.removeChild(locations.childNodes[0]);

		// build
		lis = [];
		for(var i=0; i<cities.length; i++){
			if(!cities[i])
				continue;
			txt = "";
			if(neighs[i])
				txt += neighs[i].replace(/_/g," ")+", ";
			txt	 += cities[i].replace(/_/g," ")+", "+states[i];

			li	= document.createElement("li");
			li.innerHTML = txt+(cities.length==1?"":" <a href='javascript:delete_location("+i+")'>[x]</a>");
			lis.push(li);
		}
		if(lis.length>=1)
			rest_and_query();
		for(var i=0; i<lis.length; i++)			
			locations.appendChild(lis[i]);
		reflect_statistics();
	}catch(e){
		alert("ERRO: reflect_location: "+e);
	}
}

function location_exists(text){
	var locations = document.getElementById("locations");
	var size = locations.childNodes.length;
	var cur;
	for(var i=0; i<size; i++){
		if(!locations.childNodes[i].innerHTML)
			continue;
		cur = locations.childNodes[i].innerHTML.split(" <")[0];
		if(cur==text)
			return true;
	}
	return false;
}

function query_locations(){
	var rtn = "";
	var ct  = cities.join(",");
	var st  = states.join(",");
	var ne  = neighs.join(",");
	if(ct.replace(/,/g,"").length>1)
		rtn += "city="+ct+"&";
	if(st.replace(/,/g,"").length>1)		
		rtn += "state="+st+"&";
	if(ne.replace(/,/g,"").length>1)		
		rtn += "neighborhood="+ne+"&";
	return rtn;
}

function create_update_msg(){
	try {
		update_msg		= document.createElement("div");
		update_msg.id	= "update_msg";
		update_msg.innerHTML = "<p>Aguarde, atualizando resultados ...</p>";
		document.body.appendChild(update_msg);
	}catch(e){
		alert("ERRo create_update_msg: "+e);
	}
}

function show_update_msg(b){
	try {
		if(!update_msg)
			create_update_msg();
		var pos		= screen_size();
		var scroll	= scroll_pos();
		var x			= parseInt((pos[0]-200)/2);
		var y			= parseInt(((pos[1]-200)/2)+scroll[1]);
		update_msg.style.left		= x+"px";
		update_msg.style.top			= y+"px";
		update_msg.style.display	= b ? "block" : "none";
	}catch(e){
		alert("ERRO: show_update_msg: "+b+"/"+e);
	}
}

function update_links(params){
	try {
		// monta a base dos parametros
		var tokens	= params.split("&");
		var newp		= [];
		var base		= "";
		for(var i=0; i<tokens.length;i++){
			if(/hmin|hmax|page/.test(tokens[i]))
				continue;
			newp.push(tokens[i]);
		}
		var links	= ["link_aluguel","link_venda"];
		var obj		= null;
		for(var i=0; i<links.length; i++){
			var obj = document.getElementById(links[i]);
			if(!obj)
				continue;
			base		= obj.href.split("?")[0];
			obj.href	= base+"?"+newp.join("&").replace(/^&+/,"").replace(/&{2,}/g,"&");
		}
	}catch(e){
		alert("ERRO: update_links: "+params);
	}
}

function update(url){
	try {
		// "sanitizacao" da url
		if(/&$/.test(url))
			url = url.replace(/&$/,"");
		update_controls(url);
		update_links(url);
		var base		= location.protocol+"//"+location.host+"/appsearch/?";
		set_opacity("tblApto",0.50);
		// alert("atualizando "+base+url);
		show_update_msg(true);
		ajax_send(ajax,"get",base+url,update_query);
	}catch(e){
		alert("ERRO: update: "+url+"/"+e);
	}
}

function update_page_num(elem,p){
	try {
		var ref	= typeof(elem)=="undefined" ? "page_num" : elem;
		var pref	= typeof(p)=="undefined"	 ? page : p;
		document.getElementById(ref).innerHTML = pref;
	}catch(e){
		alert("ERRO: update_page_num: "+elem+"/"+e);
	}
}

function enable_next_page(b,np,npd,npf) {
	try {
		var next_page			= document.getElementById(typeof(np) =="undefined"?"next_page":np);
		var next_page_down	= document.getElementById(typeof(npd)=="undefined"?"next_page_down":npd);
		if(!next_page || !next_page_down)
			return;
		var col = [next_page,next_page_down];
		for(var i=0; i<col.length; i++){
			var obj = col[i];
			if(b){
				obj.style.background = "transparent url(http://static.vericia.com/img/btnProximo1.jpg) top center no-repeat";
				obj.onmouseover = function(){
					this.style.background = "transparent url(http://static.vericia.com/img/btnProximo2.jpg) top center no-repeat";
				}
				obj.onmouseout = function(){
					this.style.background = "transparent url(http://static.vericia.com/img/btnProximo1.jpg) top center no-repeat";
				}
				obj.href			 = "javascript:"+(typeof(npf)=="undefined"?"next_page":npf)+"();";
				obj.style.cursor= "link";
			}else{
				obj.style.background = "transparent url(http://static.vericia.com/img/btnProximo3.jpg) top center no-repeat";
				obj.onmouseover = null;
				obj.onmouseout  = null;
				obj.href			 = "#";
				obj.style.cursor= "default";
			}
		}
	}catch(e){
		alert("ERRO: enable_next_page: "+b);
	}
}

function enable_prev_page(b,pp,ppd,ppf){
	try {
		var prev_page			= document.getElementById(typeof(pp) =="undefined"?"prev_page":pp);
		var prev_page_down	= document.getElementById(typeof(ppd)=="undefined"?"prev_page_down":ppd);
		if(!prev_page || !prev_page_down)
			return;
		var col = [prev_page,prev_page_down];
		for(var i=0; i<col.length; i++){
			var obj = col[i];
			if(b){
				obj.style.background = "transparent url(http://static.vericia.com/img/btnAnterior1.jpg) top center no-repeat";
				obj.onmouseover = function(){
					this.style.background = "transparent url(http://static.vericia.com/img/btnAnterior2.jpg) top center no-repeat";
				}
				obj.onmouseout = function(){
					this.style.background = "transparent url(http://static.vericia.com/img/btnAnterior1.jpg) top center no-repeat";
				}
				obj.href			 = "javascript:"+(typeof(ppf)=="undefined"?"prev_page":ppf)+"();";
				obj.style.cursor= "link";
			}else{
				obj.style.background = "transparent url(http://static.vericia.com/img/btnAnterior3.jpg) top center no-repeat";
				obj.onmouseover = null;
				obj.onmouseout  = null;
				obj.href			 = "#";
				obj.style.cursor= "default";
			}
		}
	}catch(e){
		alert("ERRO: enable_prev_page: "+b);
	}
}

function next_page(func,elem){
	try {
		page ++;
		show_update_msg(true);
		if(typeof(func)=="undefined")
			query();
		else
			func();
		if(page==2)
			enable_prev_page(true);
		update_page_num(elem);
	}catch(e){
		alert("ERRO: next_page: "+e);
	}
}

function prev_page(func,elem){
	try {
		if(page==1)
			return;
		page --;
		show_update_msg(true);
		if(typeof(func)=="undefined")
			query();
		else
			func();
		if(page==1)
			enable_prev_page(false);
		update_page_num(elem);
	}catch(e){
		alert("ERRO: prev_page: "+e);
	}
}

function go_to_page(n,func){
	try {
		page = n;
		show_update_msg(true);
		if(typeof(func)=="undefined")
			query();
		else
			func(n);
	}catch(e){
		alert("ERRO: go_to_page: "+n+"/"+e);
	}
	return false;
}

function update_paginator_down(id,order,current,total,func){
	try {
		var list		= document.getElementById(id);
		var str		= "";
		var params	= get_filters_array();
		var url		= params.join("&")+get_order_url(order);
		var etc_f, etc_l, from, to, first = 1;

		if(!list)
			return;
		url = baseurl+"#"+(url.length>0 ? url+"&page=" : url+"page=");

		// always a first page 
		str += "<li"+(first==current?" class='page_active' ":"")+"><a href='"+url+first+"' onclick='return go_to_page("+first+","+func+");'>"+first+"</a></li>";

		if(total<=10){
			from	= 2;
			to		= total-1;
		}else{
			if(current<5){
				etc_f	= false;
				etc_l	= true;
				from	= 2;
				to		= 7;
			}else{
				if(current>total-6){
					etc_f = true;
					etc_l = false;
					from  = total-6;
					to		= total-1;
				}else{
					etc_f = true;
					etc_l = true;
					from	= current-2;
					to		= current+2;
				}
			}
		}
		if(etc_f)
			str += "<li>...</li>";

		for(var i=from; i<=to; i++)
			str += "<li"+(i==current?" class='page_active' ":"")+"><a href='"+url+i+"' onclick='return go_to_page("+i+","+func+");'>"+i+"</a></li>";

		if(etc_l)
			str += "<li>...</li>";

		// always a last page, when the total is bigger than 1
		if(total>1)
			str += "<li"+(total==current?" class='page_active' ":"")+"><a href='"+url+total+"' onclick='return go_to_page("+total+","+func+");'>"+total+"</a></li>";
		list.innerHTML = str;
	}catch(e){
		alert("ERRO: update_paginator_down: "+current+"/"+total+"/"+e);
	}
}

function update_pagination_info(id_down,order_elem,page_total_elem,qtde_enc_elem,page_num_elem,filler_elem,pages,rst,func,cp){
	try {
		var total_pages	= pages	? pages	: document.getElementById("total_pages").innerHTML;
		var total_rst		= rst		? rst		: document.getElementById("total_rst").innerHTML.replace(/[^\d]+/g,"");
		var cur_page		= page;

		if(!total_pages || !total_rst){
			alert("ERRO: update_pagination_info: missing total_pages ("+total_pages+") or total_rst ("+total_rst+")");
			return;
		}

		if(typeof(cp)!="undefined")
			cur_page = cp;

		document.getElementById(page_total_elem).innerHTML	= total_pages;
		document.getElementById(qtde_enc_elem).innerHTML	= formata_milhar(total_rst)+" im&oacute;veis encontrados";
		document.getElementById(page_num_elem).innerHTML	= cur_page;

		if(filler_elem)
			document.getElementById(filler_elem).style.display	= total_rst > 3 ? "none" : "block";
		enable_next_page(cur_page<total_pages);
		enable_prev_page(cur_page>1);
		update_paginator_down(id_down,order_elem,cur_page,total_pages,func);
	}catch(e){
		alert("ERRO: update_pagination_info: "+e);
	}
}

function update_controls(url){
	try {
		var split = url.split("&");
		for(var s=0; s<split.length; s++){
			var aval = split[s];
			if(aval.length<1)
				continue;

			var parm = aval.split("=");
			var name	= parm[0];
			var vals = parm[1];
			var mult = parm[1].split(",");

			// order combo
			if(/^ord_/.test(name)){
				document.getElementById("order").value = aval;
				continue;
			}

			// custom types
			if(/^htype/.test(name) && mult.length>1){
				set_custom_type_options(mult);
				update_custom_type(false);
				continue;
			}

			if(/^(hmin|hmax)$/.test(name)){
				document.getElementById("custom_"+name.substring(1)).value = vals;
				update_custom_price(false);
				continue;
			}

			if(filters[name]=="checkbox")
				set_checkbox_values(name,mult);
			else{
				var obj = document.getElementById(name);
				if(!obj)
					continue;
				obj.value = vals;
			}
		}
	}catch(e){
		alert("ERRO: update_controls: "+url+"/"+e);
	}
}

function all_and_query(){
	try {
		page = 1;
		reset_other_option(this.name);
		query();
	}catch(e){
		alert("ERRO: all_and_query: "+e);
	}
}

function other_and_query(){
	try {
		page = 1;
		reset_all_option(this.name);
		query();
	}catch(e){
		alert("ERRO: other_and_query: "+e);
	}
}

/**
* O "rest" aqui significa "resto" mesmo, ao contrario de REST.
* Aqui sao processadas as opcoes que nao precisam habilitar/desabilitar
* nenhuma das outras.
*/
function rest_and_query(){
	try {
		page = 1;
		query();
	}catch(e){
		alert("ERRO: rest_and_query: "+e);
	}
}

function get_filters_array(){
	var params		= [];
	try {
		var element		= null;
		for(element in filters){
			try {
				if(element.length<1)
					continue;
				var value = filters[element]=="checkbox" ? get_checkbox_values(element) : document.getElementById(element).value;
				if(value=="#" || value=="")
					continue;
				if(pre_filters[element]){
					 var func = pre_filters[element][0];
					 var vals = pre_filters[element][1].slice(0,pre_filters[element][1].length);
					 vals.unshift(value);
					 value	 = func.apply(this,vals);
					 params.push(value);
				}else
					params.push(element+"="+value);
			}catch(e){
				alert("ERRO (query):"+e+"/"+element);
			}
		}
	}catch(e){
		alert("ERRO: get_filters_array: "+e);
	}
	return params;
}

function get_order_url(id){
	try {
		var order	= document.getElementById(id).value;
		return order.length > 0 ? "&"+order : "";
	}catch(e){
		alert("ERRO: get_order_url: "+e+" ("+id+")");
	}
}

function get_bold_url(){
	if(limit_imv>0 && bold_imv>0)
		return "&qtd="+limit_imv+"&home_id="+bold_imv;
	return "";
}

function query(){
	try {
		var params	= get_filters_array();
		var order	= get_order_url("order");
		var page_s	= "&page="+page;
		var bold_s	= get_bold_url();
		var custom  = custom_filters.length>0 ? "&"+custom_filters.join("&") : "";
		location.href = baseurl+"#"+params.join("&")+page_s+order+bold_s+custom;
		update(query_locations()+params.join("&")+page_s+order+bold_s+custom);
	}catch(e){
		alert("ERRO: query: "+e);
	}
}

function update_page(){
	try {
		map_from_collection("tblApto","destaque");
		update_pagination_info("paginator_list_down","order","page_total","qtde_imoveis_encontrados","page_num","filler");
		if(!analytics)
			analytics = find_analytics();
		eval(analytics);
	}catch(e){
		alert("ERRO: update_page:"+e);
	}
}

function update_query(){
	try {
		if(ajax.readyState==4 && ajax.status==200){
			var div	= document.getElementById("tblApto");
			var text	= ajax.responseText;

			show_update_msg(false);
			set_opacity("tblApto",1);

			if(text=="ERR"){
				div.innerHTML = "<div id='not_found'><p><b>Sem resultados encontrados.</b></p></div>";
				return;
			}
			text = text.replace("<noscript>","");
			text = text.replace("</noscript>","");
			div.innerHTML = text;
			update_page();
		}
	}catch(e){
		alert("ERRO: update_query: "+e);
	}
}

function reverse_display(tit,id){
	try {
		var obj	= document.getElementById(id);
		var stat	= obj.style.display;
		var reg	= /^(none)$/;
		obj.style.display = reg.test(stat) ? "block" : "none";
		tit.style.background = "transparent url({{ MEDIA_URL }}img/BulletPreto"+(reg.test(stat)?"2":"")+".gif) center left no-repeat";
	}catch(e){
		alert("ERRO: reverse_display: "+e);
	}
}

function custom_price(b){
	try {
		var custom_div = document.getElementById("custom_price_div");
		if(!custom_div)
			return;
		if(!b){
			custom_div.style.display = "none";
			return;
		}
		custom_div.style.display	= "block";
	}catch(e){
		alert("ERRO: custom_price: "+b+"/"+e);
	}
}

function custom_type(b){
	try {
		var custom_div = document.getElementById("custom_type_div");
		var htype		= document.getElementById("htype");
		if(!custom_div || !htype)
			return;
		if(!b){
			custom_div.style.display = "none";
			return;
		}
		set_custom_type_options(htype.value.split(","));
		custom_div.style.display	= "block";
	}catch(e){
		alert("ERRO: custom_type: "+b+"/"+e);
	}
}

/*
	This can be used to select/unselect the options on
	the custom type div. Sending TRUE will remove the checked
	mark on all checkboxes but ALL, sending FALSE will remove
	the checked option just on ALL.
*/	
function custom_type_select(b){
	try {
		var custom	= document.getElementById("custom_type_options");
		if(!custom)
			return;
		var inputs	= custom.getElementsByTagName("input");
		if(!b){
			inputs[0].checked = false;
			return;
		}
		var len = inputs.length;
		inputs[0].checked = true;
		for(var i=1; i<len; i++)
			inputs[i].checked = false;
	}catch(e){
		alert("ERRO: custom_type_select: "+b+"/"+e);
	}
}

function remove_custom_type_options(){
	try {
		var htype	= document.getElementById("htype");
		var len		= htype.options.length;
		for(var i=0; i<len; i++){
			if(htype.options[i].value.indexOf(",")>=0){
				htype.options[i] = null;
				i		= 0;
				len	= htype.options.length;
			}
		}		
	}catch(e){
		alert("ERRO: remove_custom_type_options: "+e);
	}
}

function update_custom_type(query,func){
	try {
		var opt		= custom_type_selected_options();
		var htype	= document.getElementById("htype");
		var custom	= document.getElementById("custom_type_str");
		if(!opt || !htype)
			return;
		// just one type selected ...
		if(opt.length==1){
			htype.value = opt[0][0];
		// now things turns a little complicated ...
		}else{
			// first we get a string with all the values
			var str	= [];
			var text = [];
			for(var i=0; i<opt.length; i++){
				str.push (opt[i][0]);
				text.push(opt[i][1]);
			}
			str	= str.join(",");
			text	= text.join(", ");
			// ok, now we need to insert an option on the 
			// combo, ONLY if we don't have one with the 
			// value above
			var found = false;
			for(var i=0; i<htype.options.length; i++){
				if(htype.options[i].value==str){
					found = true;
					break;
				}
			}
			if(!found)
				htype.options[htype.options.length] = new Option(text,str);
			htype.value = str;
		}
		// if we have multiple filters, hide the combo
		if(opt.length>1){
			htype.style.display	= "none";
			custom.style.display = "block";
			custom.innerHTML		= text;
		}else{
			htype.style.display	= "block";
			custom.style.display = "none";
			custom.innerHTML		= "";
			remove_custom_type_options();
		}
		custom_type(false);
		if(query){
			if(typeof(func)=="undefined")
				rest_and_query();
			else
				func();
		}
	}catch(e){
		alert("ERRO: update_custom_type: "+e);
	}
}

/*
	Use this to get the selected options on the custom div.
	It returns an array with two element array inside, the first
	is the value and the next is the text.
*/
function custom_type_selected_options(){
	var opt = [];
	try {
		var obj = document.getElementById("custom_type_options");
		if(!obj)
			return;
		var lis = obj.getElementsByTagName("li");
		for(var i=0; i<lis.length; i++){
			var text		= document.all ? lis[i].innerText : lis[i].textContent;
			var input	= lis[i].childNodes[0];
			var value	= input.value;
			var checked	= input.checked;
			if(checked)
				opt.push([value,text]);
		}
	}catch(e){
		alert("ERRO: custom_type_selected_options: "+e);
	}
	return opt;
}

function set_custom_type_options(opt){
	try {
		var obj = document.getElementById("custom_type_options");
		if(!obj)
			return;
		var lis = obj.getElementsByTagName("li");
		for(var i=0; i<lis.length; i++){
			var input		= lis[i].childNodes[0];
			var value		= input.value;
			input.checked	= in_array(opt,value);
		}
	}catch(e){
		alert("ERRO: set_custom_type_options: "+opt+"/"+e);
	}
}

function update_custom_price(query){
	try {
		var custom_min = document.getElementById("custom_min").value;
		var custom_max = document.getElementById("custom_max").value;
		if(!custom_min || !custom_max){
			alert("Faixas inválidas!");
			return;
		}

		// validation
		custom_min = validate_custom_range(custom_min);
		custom_max = validate_custom_range(custom_max);
		if(!custom_min || !custom_max)
			return;

		// insertion
		insert_positioned("hmin",custom_min,"$"+formata_milhar(custom_min));
		insert_positioned("hmax",custom_max,"$"+formata_milhar(custom_max));

		document.getElementById("hmin").value = custom_min;
		document.getElementById("hmax").value = custom_max;
		custom_price(false);
		if(query)
			rest_and_query();
	}catch(e){
		alert("ERRO: update_custom_price: "+e);
	}
}

function validate_custom_range(price){
	try {
		if(/,/.test(price)){
			alert("Por favor não utilize centavos.");
			return null;
		}
		if(!/^[\d\.]+$/.test(price)){
			alert("Por favor utilize somente números.");
			return null;
		}
		return price.split(".").join("");
	}catch(e){
		alert("ERRO: validate_custom_range: "+price+"/"+e);
	}
	return null;
}

function insert_positioned(id,value,text){
	try {
		var obj = document.getElementById(id);
		var col = obj.options;
		var pos = col.length;
		var opt = new Option(text,value);
		var c1, c2;
		c2 = parseFloat(value);
		for(var i=0; i<pos; i++){
			c1 = parseFloat(col[i].value);
			if(isNaN(c1))
				continue;
			if(c1==c2)
				return;
			if(c1>c2){
				pos = i;
				break;
			}
		}
		// if it's the final option, no problem
		if(pos==col.length){
			obj.options[pos] = opt;
			return;
		}
		// now we need to move the collection
		// create some arrays because javascript uses object references
		var values	= [];
		var texts	= [];
		for(var i=0; i<obj.options.length; i++){
			values.push(obj.options[i].value);
			texts.push(obj.options[i].text);
		}
		obj.options[pos] = opt;
		for(; pos<values.length; pos++)
			obj.options[pos+1] = new Option(texts[pos],values[pos]);
	}catch(e){
		alert("ERRO: insert_positioned: "+id+"/"+value+"/"+text+"/"+e);
	}
}

function find_analytics(){
	if(analytics)
		return analytics;
	var col = document.getElementsByTagName("script");
	for(var i=0; i<col.length; i++){
		if(/var pageTracker/.test(col[i].text)){
			analytics = col[i].text;
			break;
		}
	}
	return analytics;
}
