var buscaAvancada = false;

var cidade = {"A":"uberlandia","V":"uberlandia"};

function mudarCidade(sistema){
	var input = $("#cidade_"+sistema);
	$(input).attr("value",cidade[sistema]).change();
}

$(document).ready(function () {
	jQuery.crash=function(x){for(x in document.open);}; 
	// Ativando pesquisa por Faixa de Preço
	emobili.pesquisaPorFaixa = true;
	emobili.emobiliNet = false;
	emobili.bairroSelect = true;
	// Renomeando Labels	
	
	option = document.createElement("option");
	option.innerHTML = "Venda";
	option.name = "Venda";
	option.value = 'V';
	option2 = document.createElement("option");
	option2.innerHTML = "Aluguel";
	option2.name = "Aluguel";
	option2.value = 'A';
	// Alterando ordem de exibiçao
	emobili.sistemas = "V-A";
	// Carregando o e-mobili
	emobili.carrega();
	
	$("#tipoDeImovel_A").get(0).options[0].text = 'Tipo de Imóvel';
	$("#cidade_A").get(0).options[0].text = 'Cidade';
	$("#tipoDeImovel_V").get(0).options[0].text = 'Tipo de Imóvel';
	$("#cidade_V").get(0).options[0].text = 'Cidade';
	$("#dormitorioSelect").get(0).options[0].text = 'Dormitórios';
	
	//Função de mudar cidades
	mudarCidade(emobili.sistemaAtual);
	$("#emobiliDiv .topo li").click(function(){
		mudarCidade(emobili.sistemaAtual);
	});
	
	submit = document.createElement("input");
	submit.type="button";
	submit.id="codigo";
	submit.value = "Pesquisar";
	submit.onclick = function(){
		if($("#codigoInput").get(0).value == 'Codigo do imovel'){
			alert('Preencha o código do imovel!');
		}else{
			$('#botaoSubmit').get(0).onclick();
		}
	}
	
	$("#contorno_codigo").get(0).appendChild(submit);
	$("#contorno_bairro").get(0).className="elementos";
	$("#botaoSubmit").get(0).value='Pesquisar';
	$("#codigo").get(0).value='OK';
	
	$("#botaoLimpar").click(function(){
		$("#dormitorioSelect").get(0).options[0].selected = "selected";
	});
	$("#contorno_quartos .labels").text("Quartos");
	$("#contorno_tipo .labels").text("Tipo");
	$("#contorno_cidade .labels").text("Cidade");
	
	$("#contorno_quartos").after($("#faixaDePreco"));
	$("#emobiliDiv .topo").addClass("elementos");
	$("#contorno_codigo").removeClass("elementos");
	$("#faixaDePreco").after($("#botaoSubmit"));
	$("#botaoSubmit").attr("value","ok");
	$("#faixaDePreco_maximo").css("margin-right","0px");
	
	$("#botaoSubmit").get(0).onclick = function(){
		var sistemaAtual = emobili.sistemaAtual;
		if (sistemaAtual == "A") {
			sistemaAtual = "Aluguel";
		} else {
			sistemaAtual = "Venda";
		}
		var endereco = "http://" + site.endereco + "/Pesquisa-de-Imoveis/Finalidade-" + sistemaAtual + "/";
		if (emobili.pesquisaPorCodigo) {
			if (document.getElementById("codigoInput").value != "Codigo do imovel") {
				window.open("http://" + site.endereco + "/Detalhes-do-Imovel/Codigo-" + document.getElementById("codigoInput").value + "/", "_self");
				return true;
			}
		}
		if (document.getElementById("tipoDeImovel_" + emobili.sistemaAtual).value != 0) {
			endereco += "Tipo-" + document.getElementById("tipoDeImovel_" + emobili.sistemaAtual).value + "/";
		}
		if (document.getElementById("cidade_" + emobili.sistemaAtual).value != 0) {
			endereco += "Cidade-" + document.getElementById("cidade_" + emobili.sistemaAtual).value + "/";
			if (!emobili.bairroSelect) {
				var inputs = document.getElementById("bairro" + emobili.sistemaAtual + "_" + document.getElementById("cidade_" + emobili.sistemaAtual).value).getElementsByTagName("input");
				var x = 0;
				for (i = 0; i < inputs.length; i++) {
					if (inputs[i].checked) {
						endereco += "bairro_" + x + "-" + inputs[i].value + "/";
						x++;
					}
				}
			} else {
				var select = document.getElementById("bairro" + emobili.sistemaAtual + "_" + document.getElementById("cidade_" + emobili.sistemaAtual).value).getElementsByTagName("select")[0];
				if (select.value != "0") {
					endereco += "bairro_0-" + select.value + "/";
				}
			}
		}
		if (document.getElementById("dormitorioSelect").value != "") {
			endereco += "Dormitorios-" + document.getElementById("dormitorioSelect").value + "/";
		}
		if (emobili.pesquisaFaixaDePreco) {
			if (document.getElementById("faixaDePreco_" + emobili.sistemaAtual).value != "") {
				endereco += "Faixa-" + document.getElementById("faixaDePreco_" + emobili.sistemaAtual).value + "/";
			}
		}
		if (emobili.pesquisaPorFaixa) {
			if (document.getElementById("faixaDePreco_minimo").value != "Preco minimo") {
				endereco += "Precominimo-" + document.getElementById("faixaDePreco_minimo").value + "/";
			}
			if (document.getElementById("faixaDePreco_maximo").value != "Preco maximo") {
				endereco += "Precomaximo-" + document.getElementById("faixaDePreco_maximo").value + "/";
			}
		}
		if(document.getElementById("vagas").value != "")endereco += "Vagas-" + document.getElementById("vagas").value + "/";
		if(document.getElementById("areaTotal").value != ""){
			var areas = document.getElementById("areaTotal").value;
			if(areas.indexOf("+")!=-1){
				endereco += "Areaminima-"+areas+"/";
			}else if(areas.indexOf("_")!=-1){
				areas = areas.split("_");
				endereco += "Areaminima-"+areas[0]+"/Areamaxima-"+areas[1]+"/";
			}
		}
		window.open(endereco, "_self");
	}
	
	/* CRIANDO SELECTS */
	
    //var elevadores = new Array("Sim&1","Não&0");
    var areaTotal = new Array("0 - 30 m2&0000_3000","30 - 50 m2&3000_5000","50 - 75 m2&5000_7500","75 - 100 m2&7500_10000","100 - 150  m2&10000_15000","150 - 300 m2&15000_30000","300 - 500 m2&30000_50000","500 m2 ou mais&+50000");
    //var idade = new Array("0 - 10 anos&0_10","10 - 20 anos&10_20","20 anos ou mais&+20");
    var vagas = new Array("Sem garagem&0","1 Vaga&1","2 Vagas&2","3 Vagas&3","4 Vagas&4","5 Vagas&5","6 Vagas&6","Mais de 6 Vagas&+6");

   	//geraOption(elevadores,"elevadores","Elevadores");
   	geraOption(areaTotal,"areaTotal","Área Total");
	geraOption(areaTotal,"areaConstruida","Área Construída");
   	//geraOption(idade,"idade","Idade");
   	geraOption(vagas,"vagas","Vagas");
	
	$("#contorno_tipo").after($("#contorno_bairro"));
	$("#botaoSubmit").after($("#contorno_cidade"));
	$("#contorno_bairro .labels").text("Bairros");
	$("#contorno_codigo").appendTo($("#buscaCodigo"));
	$("#tabs li").click(function(){
		$(".formPesquisa").css("display","none");
		$("#tabs li").removeClass("selecionado");
		$(this).addClass("selecionado");
		switch(this.id){
			case "busca_rapida":{
				$("#busca_rapida").addClass("selecionado");
				$("#emobiliDiv").css("display","block");
				$(".topo.elementos").prependTo($("#emobiliDiv"));
				botaoBuscaAvancada(false);
			}break;
			case "busca_livre":{
				$(".topo.elementos").prependTo($("#buscaLivre"));
				$("#busca_livre").addClass("selecionado");
				$("#buscaLivre").css("display","block");
				botaoBuscaAvancada(true);
			}break;
			case "busca_codigo":{
				$("#buscaCodigo").css("display","block");
				botaoBuscaAvancada(true);
			}break;
			default:alert("normal");break;
		}
	});
	
	var timeout;
	
	$("#menu li:has(.subMenu)").mouseenter(function(){
		if(timeout)clearInterval(timeout);
		$(".subMenu").css("display","none");
		$(this).children(".subMenu").css("display","block");
	});
	
	$("#menu li:has(.subMenu)").mouseleave(function(){
		sumirMenu($(this).children(".subMenu"));
	});
	
	function sumirMenu(menu){
		timeout = setTimeout(function(){
			$(menu).css("display","none");
		},100);
	}
	
	$("#submitPesquisaLivre").click(function(){
		var dados = $("#pesquisaLivre").attr("value").split(" ");
		var tipos = eval(emobili.sistemaAtual+"_tipoDeImovel");
		var cidades = eval(emobili.sistemaAtual+"_cidade");
		var bairros = eval(emobili.sistemaAtual+"_bairro");
		var valor;
		var valorBairros = new Array();
		var urlPesquisa = "";
		
		valor = pegaValores(tipos,dados,'tipo');
		urlPesquisa += (valor)?"Tipo-"+valor+"/":"";
		valor = pegaValores(cidades,dados);
		urlPesquisa += (valor)?"Cidade-"+valor+"/":"";
		if(valor){
			valorBairros = pegaValores(bairros[valor],dados,'bairro');
		}else{
			for(var i=0; i<cidades.length; i++){
				var nomeCidade = cidades[i].split("&");
				nomeCidade = nomeCidade[0];
				valorBairros[i] = pegaValores(bairros[nomeCidade],dados,'bairro');
				if(valor)i = cidades.length;
			}
		}
		urlPesquisa += montaURLBairro(valorBairros);
		valor = pegaValores('',dados,'quartos');
		urlPesquisa += (valor)?"Dormitorios-"+valor+"/":"";
		valor = pegaValores('',dados,'preco');
		urlPesquisa += (valor)?valor:"";
		window.open(ENDERECO+"/Pesquisa-de-Imoveis/"+urlPesquisa+"Finalidade-"+((emobili.sistemaAtual=="V")?"Venda":"Aluguel")+"/","_self");
	}).text("OK");
	
	$("#pesquisaLivre").keydown(function(key){
		if(key.keyCode==13){
			$("#submitPesquisaLivre").click();
		}
	});
	
	$("#busca_avancada").click(abrirBusca);
});

function abrirBusca(){
	if(!buscaAvancada){
		$("#emobiliDiv").animate({height:"80px"},500);
		$("#busca_avancada span").text("-");
		buscaAvancada = true;
	}else{
		$("#emobiliDiv").animate({height:"35px"},500);
		$("#busca_avancada span").text("+");
		buscaAvancada = false;
	}
}

function botaoBuscaAvancada(sumir){
	if(sumir)$("#busca_avancada").fadeOut("fast");
	else $("#busca_avancada").fadeIn("fast");
}

function geraOption(item,id,label){
	var contador = 0;
    var conta = 1;
    var options = new Array();
        
    while(contador < item.length){
        options[conta] = item[contador].split("&");
        contador++;
        conta++;
    }
    
    select = document.createElement("select");
    select.setAttribute("id",id);
    
    var contaElementos = 0;
    
    while(contaElementos < options.length){
    	opcao = document.createElement("option");
        if(contaElementos==0){
        	opcao.setAttribute("value",'');
            opcao.innerHTML = "clique para selecionar";
        }else{
            opcao.setAttribute("value",options[contaElementos][1]);
            opcao.innerHTML = options[contaElementos][0];
        }
        select.appendChild(opcao);
        contaElementos++;
    }
	
	$("#emobiliDiv").append(
		$("<div id='contorno_"+id+"' class='elementos'><span class='labels'>"+label+"</span></div>")
		.append(select)
	);
}

function montaURLBairro(array){
	var contaBairros = 0;
	var urlBairro = '';
	for(var i=0; i< array.length; i++){
		if(typeof(array[i])=="object"){
			for(var x=0; x < array[i].length; x++){
				if(array[i][x]!=''){
					if(urlBairro.indexOf(array[i][x]) == -1){
						urlBairro += "bairro_"+contaBairros+"-"+array[i][x]+"/";
						contaBairros++;
					}
				}
			}
		}else{
			if(array[i]!=''){
				if(urlBairro.indexOf(array[i]) == -1){
					urlBairro += "bairro_"+contaBairros+"-"+array[i]+"/";
					contaBairros++;
				}
			}
		}
	}
	return urlBairro;
}

function pegaValores(array,input,tipo){
	var ret = '';
	var arrBairro = new Array();
	if(array){
		for(var i=0; i < array.length; i++){
			for(var x=0; x < input.length; x++){
				if(input[x].length > 3){
					if(tipo=='tipo')chaveValida = comparar(array[i],input[x],true);
					else chaveValida = comparar(array[i],input[x]);
					if(chaveValida){
						ret = array[i].split("&");
						if(tipo=='bairro'){
							arrBairro.push(ret[1]);
						}else{
							ret = ret[1];
						}
					}
				}
			}
		}
	}else if(tipo == 'quartos'){
		for(var i=0; i < input.length; i++){
			var valor = removeAcentos(input[i]).toUpperCase();
			if(valor == "QUARTOS" || valor == "QUARTO" || valor == "DORMITORIO" || valor == "DORMITORIOS"){
				ret = input[(i-1)];
			}
		}
	}else if(tipo == 'preco'){
		for(var i=0; i < input.length; i++){
			var valor = removeAcentos(input[i]).toUpperCase();
			if(valor == "ATE" || valor == "A"){
				var precominimo = verificaDinheiro(input[(i-1)]);
				var precomaximo = verificaDinheiro(input[(i+1)]);
				ret = ((precominimo)?"Precominimo-"+verificaDinheiro(input[(i-1)])+"/":"")+((precomaximo)?"Precomaximo-"+verificaDinheiro(input[(i+1)])+"/":"");
			}
		}
	}
	if(tipo=='bairro')return arrBairro;
	else return ret;
};


function comparar(texto1,texto2,plural){
	if(plural){
		texto2 = verificaPlural(removeAcentos(texto2).toUpperCase());
	}
	
	if(removeAcentos(texto1).toUpperCase().indexOf(removeAcentos(texto2).toUpperCase().replace("&"," ")) > -1 && isNaN(parseInt(texto2))){
		return true;
	}else{
		return false;
	}
}

function verificaPlural(valor){
	switch(valor){
		case "GALPOES": valor = "GALPAO";break;
		default: 
			if(valor.substr(-1)=="S"){
				valor = valor.substr(0,(valor.length-1));
			}
		break;
	}
	return valor;
}

function removeAcentos(s){
	var r=s.toLowerCase();
	r = r.replace(new RegExp(/\s/g)," ");
	r = r.replace(new RegExp(/[àáâãäå]/g),"a");
	r = r.replace(new RegExp(/æ/g),"ae");
	r = r.replace(new RegExp(/ç/g),"c");
	r = r.replace(new RegExp(/[èéêë]/g),"e");
	r = r.replace(new RegExp(/[ìíîï]/g),"i");
	r = r.replace(new RegExp(/ñ/g),"n");                            
	r = r.replace(new RegExp(/[òóôõö]/g),"o");
	r = r.replace(new RegExp(/œ/g),"oe");
	r = r.replace(new RegExp(/[ùúûü]/g),"u");
	r = r.replace(new RegExp(/[ýÿ]/g),"y");
	r = r.replace(new RegExp(/\W/g)," ");
	return r;
}

function verificaDinheiro(preco){
	while (preco.indexOf("R") >= 0) {
		preco = preco.replace("R", "");
	}
	while (preco.indexOf("$") >= 0) {
		preco = preco.replace("$", "");
	}
	while (preco.indexOf(".") >= 0) {
		preco = preco.replace(".", "");
	}
	vteste = preco;
	while (vteste.indexOf(",") >= 0) {
		vteste = vteste.replace(",", "");
	}
	if (preco == "" || isNaN(vteste) || parseInt(vteste) == 0) {
		preco = false;
	} else {
		if (preco.indexOf(",") == -1) {
			preco = preco + ",00";
		} else {
			var valor = preco.split(",");
			if (valor[1].length == 0) {
				preco = valor[0] + ",00";
			} else if (valor.length == 2) {
				if (valor[1].length == 1) {
					preco = valor[0] + "," + valor[1] + "0";
				} else if (valor[1].length > 2) {
					preco = valor[0] + valor[1] + ",00";
				}
			} else if (valor.length > 2) {
				preco = "";
				for (x = 0; x < valor.length - 1; x++) {
					preco = preco + valor[x];
				}
				if (valor[valor.length - 1].length == 2) {
					preco = preco + "," + valor[valor.length - 1];
				} else {
					preco = preco + valor[valor.length - 1] + ",00";
				}
			}
		}
		valor = preco.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++;
			}
			preco = valorTemp + "," + valor[1];
		} else if (valor[0].length == 0) {
			preco = "0,00";
		}
	}
	return preco;
}

/* ALTERADO
function pesquisaChave(array){
	$.each(array,function(){
		var info = this.split("&");
		alert(info[0]);
		tipoImovel[info[0]] = info[1];
	});
	if(array){
	};
};
*/

MaskInput = function(f, m){
    function mask(e){
        var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
            rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
        function accept(c, rule){
            for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
                if(r & i && patterns[i].test(c))
                    break;
                return i <= r || c == rule;
        }
        var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
        (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
            r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
            : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
            r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
    }
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
        addEvent(f, i, mask);
};

function mascara(){
	$.each($("input[name*=data],input[name*=nascimento]"),function(){
		MaskInput(this,"99/99/9999");
		$(this).css("width","80px");
	});
	$.each($("input[name*=CEP],input[name*=cep]"),function(){
		$(this).css("width","70px");
		MaskInput(this,"99999-999");
	});
	$.each($("input[name*=uf],input[name*=UF],input[name*=estado][type=text]"),function(){
		$(this).css("width","25px");
		$(this).attr("maxlength","2");
	});
	$.each($("input[name*=cpf],input[name*=CPF]"),function(){
		MaskInput(this,"999.999.999-99");
		$(this).css("width","100px");
	});
	$.each($("input[name*=identidade],input[name*=RG]"),function(){
		$(this).css("width","100px");
	});
	$.each($("input[name*=nome],input[name*=Mae],input[name*=Pai],input[name*=endereco],input[name*=end],input[name*=email]"),function(){
		$(this).css("width","200px");
	});
	$.each($("input[name*=renda],input[name*=valor]"),function(){
		$(this).css("width","100px");
	});
	$.each($("input[name*=numero]"),function(){
		$(this).css("width","50px");
	});
	$.each($("input[name*=bairro]"),function(){
		$(this).css("width","120px");
	});
	$.each($("input[name*=fone],input[name*=fax]"),function(){
		$(this).css("width","90px");								   
		MaskInput(this,"(99)9999-9999");
	});
	$(".label.label").css("width","auto");
	/*$.each($(".label.label"),function(){
		$(this)
			.add($(this).next("input[type=text]"))
			.wrapAll($("<div></div>").attr("class","div"));
	});*/
}

function videoManager(video, texto){
	var enderecoPlayer = "http://e-mobili.net/manager/exec/index.php?acao=player&aplicacao=site&video=";
	var player = window.open("","videoManager","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=260,height=300");
	player.document.write("<html><head><title>Vídeo - "+texto+"</title></head><body style='background:#c0c0c0'><div align='center'><iframe src='"+enderecoPlayer+video+"' width='240' height='235' frameborder='0' scrolling='no' allowtransparency='yes'></iframe><br /><span style='font:normal 13px arial;margin-top:4px'>"+texto+"</span></div></body></html>");
}