function ordenarOpcoes(elemento) {
    var opcoes = new Array();
    var valores = new Array();
    for(i=0; i<elemento.options.length-1; i++)  { 
        opcoes[i] = new Array(); 
        opcoes[i][0] = elemento.options[i+1].text; 
        opcoes[i][1] = elemento.options[i+1].value; 
    } 
    opcoes.sort(); 
    for(i=0; i<elemento.options.length-1; i++)  { 
        elemento.options[i+1].text = opcoes[i][0]; 
        elemento.options[i+1].value = opcoes[i][1]; 
    } 
} 
var URL = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
function formataValor(elemento){while(elemento.value.indexOf(".")>=0) elemento.value = elemento.value.replace(".", ""); vteste = elemento.value; while(vteste.indexOf(",")>=0) vteste = vteste.replace(",", ""); if( elemento.value == '' || isNaN(vteste) || parseInt(vteste) == 0 ){ elemento.value = '0,00'; }else{ if(elemento.value.indexOf(',')==-1){ elemento.value = elemento.value+',00'; }else{ var valor = elemento.value.split(','); if(valor[1].length == 0){ elemento.value = valor[0] + ',00'; } else if(valor.length == 2){ if(valor[1].length == 1){ elemento.value = valor[0] + ',' + valor[1] + '0'; }else if(valor[1].length > 2){ elemento.value = valor[0] + valor[1] + ',00'; } }else if(valor.length > 2){ elemento.value = ''; for(x=0; x < (valor.length-1); x++){ elemento.value = elemento.value+valor[x]; } if(valor[(valor.length-1)].length==2){ elemento.value = elemento.value+','+valor[(valor.length-1)]; }else{ elemento.value = elemento.value+valor[(valor.length-1)]+',00'; } } } valor = elemento.value.split(','); var valorTemp = ''; if(valor[0].length>3){ y = 0; for(x=valor[0].length;x!=-1;x--){ if(y==4){ y=1; valorTemp = '.'+valorTemp; } valorTemp = valor[0].substr(x,1)+valorTemp; y++; } elemento.value = valorTemp+","+valor[1]; }else if(valor[0].length==0) elemento.value = "0,00"; }}
(function($) {
 
	$.fn.minMaxSlider = function(settings) {
		var config = {
						'slider'		:			 $(this),           		// the tag of the selected slider
						'min_input'		:			'#min_input',				// the tag of the associated min input
						'max_input'		:			'#max_input',				// the tag of the associate max input
						'min_size'		:			0,							// the min value of the slider
						'max_size'		:			500,						// the max value of the slider
						'sync_inputs'	:			true,						// sets whether input fields are identical to slider fields
						'step' : 1
		};
 
		if (settings) {
			settings = $.extend(config, settings);
		}

		this.each(function() {
			// get input values and set as slider defaults
			var min_value = $(settings.min_input).attr("value");
			var max_value = $(settings.max_input).attr("value");
			// add the slider
			$(this).slider({
				range: true,
				min: settings.min_size,
				max: settings.max_size,
				values: [min_value, max_value],
				step:settings.step,
				slide: function(event, ui) {
					$(settings.min_input).val(ui.values[0]);
					formataValor($(settings.min_input).get(0));
					$(settings.max_input).val(ui.values[1]);
					formataValor($(settings.max_input).get(0));
				}
				
			});
			// add listener to min input
			$(settings.min_input).change(changeSlider);
			// add listener to max input
			$(settings.max_input).change(changeSlider);
			return this;
		});
		
		function changeSlider() {
			// change the slider handles based on value of inputs
            var new_value = parseInt($(this).val().replace(".","").replace(".","").split(",")[0]);
            var index; // which handle to move
			if ($(this).attr('name') == $(settings.min_input).attr('name')) {
				// min slider
				index = 0;
				valor = parseInt($(settings.min_input).val().replace(".","").replace(".","").split(",")[0]);
                new_value = Math.min(new_value, valor);
			}
			else {
				// max slider
				index = 1;
				valor = parseInt($(settings.max_input).val().replace(".","").replace(".","").split(",")[0]);
                new_value = Math.max(new_value, valor);
			}
			if (new_value < settings.min_size) new_value = settings.min_size;
			//else if (new_value > settings.max_size) new_value = settings.max_size;
			// sync if allowed
			if (settings.sync_inputs) $(this).val(new_value);
			// set the slider
			$(settings.slider).slider('values',index,new_value);
			formataValor($(settings.min_input).get(0));
			formataValor($(settings.max_input).get(0));
			return this;
		}
   };
 
})(jQuery);
this.tip = function() {    
    this.xOffset = -10;
    this.yOffset = 10;       
    
    $(".tip").unbind().hover(    
        function(e) {
            this.t = this.title;
            this.title = ''; 
            this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
            
            $('body').append( '<p id="tip"><img id="tipArrow" />' + this.t + '</p>' );
                        
            $('p#tip #tipArrow').attr("src", ENDERECO+'/outros/site/scripts/tip.png');
            $('p#tip').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow");
            
        },
        function() {
            this.title = this.t;
            $("p#tip").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
            this.top = (e.pageY + yOffset);
            this.left = (e.pageX + xOffset);
                         
            $("p#tip").css("top", this.top+"px").css("left", this.left+"px");
        }
    );            
    
};
$(document).ready(function(){
	emobili.bairroSelect = true;
	emobili.carrega();
	var sistemas = emobili.sistemas.split("-");
	var x = 0;
	while(x<sistemas.length){
		if(sistemas[x]=="V") divAtual = "#comprar";
		else divAtual = "#alugar";
		if($("#tipoDeImovel_"+sistemas[x])){
			ordenarOpcoes($("#tipoDeImovel_"+sistemas[x]).get(0));
			var elementoClone = $("#tipoDeImovel_"+sistemas[x]).clone();
			$(elementoClone).attr("multiple","multiple");
			$(elementoClone).attr("id", "mTipo_"+sistemas[x]);
			$(divAtual).find(".tipos").append(elementoClone);
			$(elementoClone).find('option:first').remove();
			$(elementoClone).show();
			$(elementoClone).multiselect({noneSelectedText:"Tipos de Imóvel"});
			
			var elementoClone = $("#cidade_"+sistemas[x]).clone();
			$(divAtual).find(".cidade").append(elementoClone);
			$(elementoClone).attr("multiple","multiple");
			$(elementoClone).find('option:first').remove();
			$(elementoClone).attr("name","cidade"+sistemas[x]);
			$(elementoClone).show();
			$(elementoClone).multiselect({
			   multiple: false,
			   header: false,
			   noneSelectedText: "Cidade",
			   selectedList: 1,
			   header: "selecione a cidade",
			   click: function(event, ui){
				   	if(this.parentNode.parentNode.parentNode.id=="comprar") selec = "V";
					else selec = "A";
					$("div[id^='bairro"+selec+"']").hide();
					$("#bairro"+selec+"_"+ui.value.replace(" ","")).show();
				}
			});
			
			$(divAtual).find(".bairros").append("<div id='bairro"+sistemas[x]+"_vazio'><select></select></div>");
			$(divAtual).find(".bairros").append($("div[id^='bairro"+sistemas[x]+"']"));
			$("div[id^='bairro"+sistemas[x]+"']").each(function(i){
				$(this).find("select").attr("multiple","multiple");	
				$(this).find("select").find('option:first').remove();
				$(this).find("select").multiselect({noneSelectedText:"Bairros"});
				$(this).attr("id",$(this).attr("id").replace(" ",""));
			});
			$("#bairro"+sistemas[x]+"_vazio").find("select").multiselect('disable');
			$("#bairro"+sistemas[x]+"_vazio").find(".ui-multiselect").addClass("tip");
			$("#bairro"+sistemas[x]+"_vazio").find(".ui-multiselect").attr("disabled","");
			$("#bairro"+sistemas[x]+"_vazio").find(".ui-multiselect").attr("title","selecione a cidade primeiro!");
			if(sistemas[x]=="V"){
				$("#sliderV").minMaxSlider({
					'min_input' : '#minimoV',
					'max_input': '#maximoV',
					'min_size': 0,
					'max_size': 2500000,
					'step': 10000
				});
				formataValor($("#minimoV").get(0));
				formataValor($("#maximoV").get(0));
			}else{
				$("#sliderA").minMaxSlider({
					'min_input' : '#minimoA',
					'max_input': '#maximoA',
					'min_size': 0,
					'max_size': 10000,
					'step': 500
				});
				formataValor($("#minimoA").get(0));
				formataValor($("#maximoA").get(0));
			}
			
			$(divAtual).find(".dormitorios").append('<select name="dormitorios" multiple="multiple"><option value="1">1 quarto</option><option value="2a3">2 a 3 quartos</option><option value="3a4">3 a 4 quartos</option><option value="+4">+ de 4 quartos</option>');
			$(divAtual).find(".dormitorios").find("select").multiselect({
			   multiple: false,
			   header: false,
			   noneSelectedText: "Quartos",
			   selectedList: 1,
			   header: "número de quartos",
			   minWidth: 120
			});
			
		}
		x++;
	}
	$("#pesquisa .buscar").click(function(){
		divAtual = $(this.parentNode).attr("id");
		if(divAtual=="comprar"){
			var sistema = "V";
			var finalidade = "Venda";
			var maximo = "2.500.000,00";
		}else{
			var sistema = "A";
			var finalidade = "Aluguel";
			var maximo = "10.000,00";
		}
		var arrayTipo = $("#"+divAtual).find(".tipos select").multiselect("getChecked").map(function(){ return this.value; });
		var novaURL = ENDERECO+"/Pesquisa-de-Imoveis/Finalidade-"+finalidade+"/";
		if(arrayTipo.length>0){
			varTipo = "";
			for(i=0;i<arrayTipo.length;i++){
				if(arrayTipo[i]!="") varTipo += arrayTipo[i]+"|";
			}
			if(varTipo!="") novaURL += "tipoImovel_idTipo-"+varTipo+"/";
		}
		var cidadeAtual = $("#"+divAtual).find(".cidade select").multiselect("getChecked").map(function(){ return this.value; });
		if(cidadeAtual.length>0){
			novaURL += "Cidade-"+cidadeAtual[0]+"/";
			var arrayBairro = $("#bairro"+sistema+"_"+cidadeAtual[0].replace(" ","")).find("select").multiselect("getChecked").map(function(){ return this.value; });
			if(arrayBairro.length>0){
				varBairro = "";
				for(i=0;i<arrayBairro.length;i++){
					if(arrayBairro[i]!="") varBairro += arrayBairro[i]+"|";
				}
				if(varBairro!="") novaURL += "Bairro-"+varBairro+"/";
			}
		}
		var precoMinimo = $("#"+divAtual).find(".minimo").val();
		var precoMaximo = $("#"+divAtual).find(".maximo").val();
		if(precoMinimo!="0,00"){
			novaURL += "Precominimo-"+precoMinimo+"/";
		}
		if(precoMaximo!=maximo){
			novaURL += "Precomaximo-"+precoMaximo+"/";
		}
		var valorDormitorios = $("#"+divAtual).find(".dormitorios select").multiselect("getChecked").map(function(){ return this.value; });
		if(valorDormitorios.length>0){
			novaURL += "Dormitorios-"+valorDormitorios[0]+"/";
		}
		window.open(novaURL,"_self");
	});
	tip();
	$("#tabs").tabs({ fx: { opacity: 'toggle' } });
	$("#pesquisa").show();
	$("#accordion").accordion();
	$("#favoritos .ui-state-default").click(function(){
		if($(this).hasClass('fechado')){
			$("#frameFavoritos").hide();
			if($(this).attr("title")=="aluguel"){
				$("#frameFavoritos").find("iframe").attr("src", ENDERECO+"/Meus-Imoveis-Favoritos/Finalidade-Aluguel/Frame-sim/");
			}else{
				$("#frameFavoritos").find("iframe").attr("src", ENDERECO+"/Meus-Imoveis-Favoritos/Finalidade-Venda/Frame-sim/");
			}
			var aberto = $("#favoritos .aberto").get(0);
			$(aberto).removeClass("aberto");
			$(aberto).addClass("fechado");
			$(this).removeClass("fechado");
			$(this).addClass("aberto");
			$("#frameFavoritos").insertAfter($(this));
			$("#frameFavoritos").show("slide");
		}
	});
	if(location.href.indexOf("Finalidade-Aluguel/")>0){
		$($("#favoritos .ui-state-default").get(1)).click();
		$($("#pesquisa a").get(1)).click();
		$("#frameFavoritos").find("iframe").attr("src", ENDERECO+"/Meus-Imoveis-Favoritos/Finalidade-Aluguel/Frame-sim/");
	}else{
		$("#frameFavoritos").find("iframe").attr("src", ENDERECO+"/Meus-Imoveis-Favoritos/Finalidade-Venda/Frame-sim/");	
	}

});
