var pontosInteresse = new Array(); var enderecosBuscadosRota = new Array(); var enderecosBuscadosDisAte = new Array(); var position; var ponto; var mapa; var mapaRota; var mapaDistanciaAte; var lat; var lon; var tracaRota = false; pontosInteresse[0] = new Object(); pontosInteresse[0].termo = 'gym'; pontosInteresse[0].selecionado = false; pontosInteresse[0].pontos = new Array(); pontosInteresse[1] = new Object(); pontosInteresse[1].termo = 'restaurant'; pontosInteresse[1].selecionado = false; pontosInteresse[1].pontos = new Array(); pontosInteresse[2] = new Object(); pontosInteresse[2].termo = 'school,university'; pontosInteresse[2].selecionado = false; pontosInteresse[2].pontos = new Array(); pontosInteresse[3] = new Object(); pontosInteresse[3].termo = 'airport'; pontosInteresse[3].selecionado = false; pontosInteresse[3].pontos = new Array(); pontosInteresse[4] = new Object(); pontosInteresse[4].termo = 'bank'; pontosInteresse[4].selecionado = false; pontosInteresse[4].pontos = new Array(); pontosInteresse[5] = new Object(); pontosInteresse[5].termo = 'bar,cafe,night_club'; pontosInteresse[5].selecionado = false; pontosInteresse[5].pontos = new Array(); pontosInteresse[6] = new Object(); pontosInteresse[6].termo = 'art_gallery,library,movie_theater,movie_rental,museum'; pontosInteresse[6].selecionado = false; pontosInteresse[6].pontos = new Array(); pontosInteresse[7] = new Object(); pontosInteresse[7].termo = 'stadium'; pontosInteresse[7].selecionado = false; pontosInteresse[7].pontos = new Array(); pontosInteresse[8] = new Object(); pontosInteresse[8].termo = 'parking'; pontosInteresse[8].selecionado = false; pontosInteresse[8].pontos = new Array(); pontosInteresse[9] = new Object(); pontosInteresse[9].termo = 'police'; pontosInteresse[9].selecionado = false; pontosInteresse[9].pontos = new Array(); pontosInteresse[10] = new Object(); pontosInteresse[10].termo = 'gas_station'; pontosInteresse[10].selecionado = false; pontosInteresse[10].pontos = new Array(); pontosInteresse[11] = new Object(); pontosInteresse[11].termo = 'church,hindu_temple,synagogue'; pontosInteresse[11].selecionado = false; pontosInteresse[11].pontos = new Array(); pontosInteresse[12] = new Object(); pontosInteresse[12].termo = 'pharmacy'; pontosInteresse[12].selecionado = false; pontosInteresse[12].pontos = new Array(); pontosInteresse[13] = new Object(); pontosInteresse[13].termo = 'hospital'; pontosInteresse[13].selecionado = false; pontosInteresse[13].pontos = new Array(); pontosInteresse[14] = new Object(); pontosInteresse[14].termo = 'grocery_or_supermarket,bakery,convenience_store'; pontosInteresse[14].selecionado = false; pontosInteresse[14].pontos = new Array(); pontosInteresse[15] = new Object(); pontosInteresse[15].termo = 'bus_station,subway_station,train_station'; pontosInteresse[15].selecionado = false; pontosInteresse[15].pontos = new Array(); pontosInteresse[16] = new Object(); pontosInteresse[16].termo = 'pet_store,veterinary_care'; pontosInteresse[16].selecionado = false; pontosInteresse[16].pontos = new Array(); $(document).ready(function () { $(".click-ver-mapa").click(function() { carregarMapa(); }); fixarContatar(); carregarCarrossel('.lista-imoveis'); // função em geral.js carregarCarrossel('.bloco-informacoes'); // função em geral.js // carregarMaisFotosImovel('.bloco-informacoes'); // função em geral.js carregarCarrossel('.bloco-outros-imoveis'); // função em geral.js // carregarMaisFotosImovel('.bloco-outros-imoveis'); // função em geral.js carregarModalMaximizar(); carregarVerTelefone(); adicionarCliquesImoveis(); voltarParaBusca(); abreModalContatar(); definirPosicaoSetas(); // define posição das setas, imovel anterior e proximo imovel posicaoBotoesImovelAnteriorEProximo(); // console.log(getCookie('aviso')); if(getCookie('aviso') != 1) exibirAviso(); }); function posicaoBotoesImovelAnteriorEProximo(){ $(window).resize(function(){ definirPosicaoSetas(); ajustarAviso(); }); } function definirPosicaoSetas(){ if($('.informacoes').offset().left < 60){ $('.navegacao-imoveis').addClass("mobile"); $('.bloco-aviso').addClass('mobile'); }else{ $('.navegacao-imoveis').removeClass('mobile'); $('.bloco-aviso').removeClass('mobile'); $('.anterior').css({'left':$('.informacoes').offset().left - 50}); $('.seguinte').css({'left':$('.contatar').offset().left + $('.contatar').width()+10}); } } function exibirAviso(){ ajustarAviso(); setTimeout(function(){$('.bloco-aviso').hide('slow')}, 5000); setCookie('aviso', 30, 1); } function ajustarAviso(){ console.log("Aviso"); // if(getCookie('aviso') != 1) // $('.bloco-aviso').css({'display':'block', 'left':$('.seguinte').offset().left-200}); } function fixarContatar() { if(!$(".bloco-salvar-receber-sugestoes").is(':visible')) return false; // verifica se esse bloco é visivel var tamanhoSalvarReceberSugestoes = ($(".bloco-salvar-receber-sugestoes").css('height').split('px')[0]); var tamanhoInformacoes = $(".bloco-informacoes .informacoes").height() - tamanhoSalvarReceberSugestoes; $('.bloco-contatar').css('height', tamanhoInformacoes + 'px'); $(document).scroll(function () { var tamanhoSalvarReceberSugestoes = ($(".bloco-salvar-receber-sugestoes").css('height').split('px')[0]); var posicaoScroll = $(document).scrollTop(); // obtem a quantidade de scroll no momento var tamanhoInformacoes = $(".bloco-informacoes .informacoes").height() - tamanhoSalvarReceberSugestoes; $('.bloco-contatar').css('height', tamanhoInformacoes + 'px'); if (posicaoScroll > 540) { $('.bloco-contatar .b-contatar').removeClass("absoluto-bottom"); $('.bloco-contatar .b-contatar').addClass("fixo"); } else { $('.bloco-contatar .b-contatar').removeClass("absoluto-bottom"); $('.bloco-contatar .b-contatar').removeClass("fixo"); } if (posicaoScroll > (tamanhoInformacoes - 150)) { $('.bloco-contatar .b-contatar').removeClass("fixo"); $('.bloco-contatar .b-contatar').addClass("absoluto-bottom"); } }); $('.b-contatar').find('.form-input').on('blur', function () { $('.' + $(this).attr('class').replace(' ','.')).val($(this).val()); }); $(document).scroll(function () { if($(document).scrollTop() > 265){ $('.navegacao-imoveis').addClass('fixado'); }else{ $('.navegacao-imoveis').removeClass('fixado'); } }); } function carregarMapa() { if(!$('#map').is(':visible')) return false; lat = $("#latitude").val(); lon = $("#longitude").val(); var end = ($("#logradouro").val() != '') ? $("#logradouro").val()+',' : ''; // if (end != '') end += $('#bairro').val()+', '+$('#cidade').val(); // else // end = $('#bairro').val() + ',' + $('#cidade').val(); var htmlPontoMapa = end; if (lat == "" || lon == "" && end != '') { geocoder = new google.maps.Geocoder(); geocoder.geocode({'address': end + ', Brasil', 'region': 'BR'}, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { //encontra local pelo logradouro if (results[0]) { lat = results[0].geometry.location.lat(); lon = results[0].geometry.location.lng(); position = new google.maps.LatLng(lat, lon); carregarPontosProximos(); if ($("#logradouro").val() == ''){ // se não existe logradouro, busca latLng do bairro e o pino não deve aparecer no mapa, o TRUE significa que o mapa é aproximado initMap(lat, lon, 'map', true); } else{ initMap(lat, lon, 'map'); } } }else{ //quando não encontra o local pelo logradouro, busca somente o bairro end = $('#bairro').val()+', '+$('#cidade').val(); geocoder.geocode({'address': end + ' - pr, Brasil', 'region': 'BR'}, function (results, status) { console.log(google.maps.GeocoderStatus); if (status == google.maps.GeocoderStatus.OK) { if (results[0]) { lat = results[0].geometry.location.lat(); lon = results[0].geometry.location.lng(); position = new google.maps.LatLng(lat, lon); carregarPontosProximos(); // se não existe logradouro, busca latLng do bairro e o pino não deve aparecer no mapa, o TRUE significa que o mapa é aproximado initMap(lat, lon, 'map', true); naoMostrarPino(); } } }) } }) } if ($('#mostrarPino').val() == 0 || ($("#logradouro").val() == '' && lat == '' && lon == '')) { naoMostrarPino(); } initMap(lat, lon, 'map'); // necessario para pontos proximos position = new google.maps.LatLng(lat, lon); // mapa.setCenter(position); $('.menu-mapa ul li').on('click', function () { $('.menu-mapa ul li').removeClass('ativo'); $(this).addClass('ativo'); if ($(this).attr('val') == 'map') { $('#map').css('display', 'block'); $('#mapVisaoRua').css('display', 'none'); $('#mapRotas').css('display', 'none'); $('.bloco-endereco-rota .endereco-inicial').hide('slow'); $('#mapDistanciaAte').css('display', 'none'); exibirPontosProximos(); initMap(lat, lon, 'map'); } else if ($(this).attr('val') == 'mapVisaoRua') { $('.bloco-endereco-rota .endereco-inicial').hide('slow'); ocultarPontosProximos(); loadMapStreetView(); } else if ($(this).attr('val') == 'mapRotas') { $('#map').css('display', 'none'); $('#mapVisaoRua').css('display', 'none'); $('#mapRotas').css('display', 'block'); $('#mapDistanciaAte').css('display', 'none'); ocultarPontosProximos(); initMap(lat, lon, 'mapRotas'); $('.bloco-endereco-rota .endereco-inicial').show('slow'); $('.bloco-endereco-rota .endereco-inicial').css('display', 'table'); $('.bloco-endereco-rota .endereco-inicial .info-distancia').css('display', 'none'); $('.bloco-endereco-rota button').attr('acao', 'ver-rota'); } else { $('#map').css('display', 'none'); $('#mapVisaoRua').css('display', 'none'); $('#mapRotas').css('display', 'none'); $('#mapDistanciaAte').css('display', 'block'); ocultarPontosProximos(); initMap(lat, lon, 'mapDistanciaAte'); $('.bloco-endereco-rota .endereco-inicial').show('slow'); $('.bloco-endereco-rota .endereco-inicial').css('display', 'table'); $('.bloco-endereco-rota button').attr('acao', 'ver-distancia-ate'); $('.bloco-endereco-rota .endereco-inicial .info-distancia').css('display', 'block'); } }); carregarPontosProximos(); $('.bloco-endereco-rota button').on('click', function () { if ($("#logradouro").val() == '') { var enderecoImovel = new google.maps.LatLng(parseFloat(lat), parseFloat(lon)); } else { var enderecoImovel = $("#endereco").val(); } if ($(this).attr('acao') == 'ver-rota') { comoChegar_DistanciaAte($('.endereco-inicial-internauta').val(), enderecoImovel, position, 'como-chegar'); } else { comoChegar_DistanciaAte($('.endereco-inicial-internauta').val(), enderecoImovel, position, 'distancia-ate'); } }); $(".mapa").css("position", "relative"); $(".mapa").css("z-index", 100); } /* * Parametro semPino_MapaAproximado: * Quando o mapa não possui latitude, longitude e nem logradouro * essa variavel recebe true, o pino não será mostrado. */ function initMap(latitude, longitude, componente, semPino_MapaAproximado) { var semPino_MapaAproximado = semPino_MapaAproximado ? true : false; if (latitude == '' || longitude == "") return false; var position = new google.maps.LatLng(latitude, longitude); if (componente == 'map') { if (mapa == null) { mapa = new google.maps.Map(document.getElementById(componente), { zoom: 14, center: position, scrollwheel: false }); if ($('#mostrarPino').val() == 1 && semPino_MapaAproximado == false) { marker = new google.maps.Marker({ map: mapa, draggable: false, animation: google.maps.Animation.DROP, position: position }); } else { marker = null; } google.maps.event.trigger(mapa, 'resize'); } } else if (componente == 'mapRotas') { if (mapaRota == null) { mapaRota = new google.maps.Map(document.getElementById(componente), { zoom: 14, center: position, scrollwheel: false }); if ($('#mostrarPino').val() == 1) { marker = new google.maps.Marker({ map: mapaRota, draggable: false, animation: google.maps.Animation.DROP, position: position }); } else { marker = null; } google.maps.event.trigger(mapaRota, 'resize'); } } else { if (mapaDistanciaAte == null) { mapaDistanciaAte = new google.maps.Map(document.getElementById(componente), { zoom: 14, center: position, scrollwheel: false }); if ($('#mostrarPino').val() == 1) { marker = new google.maps.Marker({ map: mapaDistanciaAte, draggable: false, animation: google.maps.Animation.DROP, position: position }); } else { marker = null; } google.maps.event.trigger(mapaDistanciaAte, 'resize'); } } } function naoMostrarPino(){ $('.modo-mapa').css('width', '100%'); $('.observacao').css('display', 'block'); $('.menu-mapa ul li').css('paddingTop', '9px'); $('.modo-visao-rua').hide(); $('.modo-como-chegar').hide(); $('.modo-distancia-ate').hide(); } function desmarcarPontos(obj) { if (obj.selecionado == true) { for (var x = 0; x < obj.pontos.length; x++) { obj.pontos[x].setMap(null); } } } function marcarPontos(obj) { if (obj.selecionado == true) { for (var x = 0; x < obj.pontos.length; x++) { obj.pontos[x].setMap(mapa); } } else { var request = { location: position, radius: 1000, types: obj.termo.split(',') } infowindow = new google.maps.InfoWindow({maxWidth: 300}); var service = new google.maps.places.PlacesService(mapa); service.nearbySearch(request, function (results, status) { obj.selecionado = true; if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { var p = createMarker(results[i]); obj.pontos.push(p); } } }); } } function createMarker(place) { var placeLoc = place.geometry.location; var infoMapa = '
' + place.name + '
' + place.vicinity + '
'; var pathImagePlace = "/site/imagens/mapa/icones-mapa/"; var placeIcons; var scaleSize = new google.maps.Size(43, 43); switch (place.types[0]) { case "gym": case "beauty_salon": placeIcons = pathImagePlace + 'academia.fw.png'; break; case "airport": placeIcons = pathImagePlace + 'aeroporto.fw.png'; break; case "bank": case "finance": placeIcons = pathImagePlace + 'banco.fw.png'; break; case "night_club": case "cafe": case "bar": placeIcons = pathImagePlace + 'bares-casas-noturnas.fw.png'; break; case "movie_rental": case "movie_theater": case "library": case "art_gallery": case "museum": placeIcons = pathImagePlace + 'cultura.fw.png'; break; case "school": case "university": placeIcons = pathImagePlace + 'escola.fw.png'; break; case "stadium": placeIcons = pathImagePlace + 'esportes.fw.png'; break; case "parking": placeIcons = pathImagePlace + 'estacionamentos.fw.png'; break; case "gas_station": placeIcons = pathImagePlace + 'posto-gasolina.fw.png'; break; case "cemetery": case "hindu_temple": case "synagogue": placeIcons = pathImagePlace + 'igreja.fw.png'; break; case "restaurant": case "food": case "store": placeIcons = pathImagePlace + 'restaurante.fw.png'; break; case "police": placeIcons = pathImagePlace + 'policia.fw.png'; break; case "pharmacy": placeIcons = pathImagePlace + 'farmacia.fw.png'; break; case "hospital": placeIcons = pathImagePlace + 'hospital.fw.png'; break; case "church": placeIcons = pathImagePlace + 'igreja.fw.png'; break; case "grocery_or_supermarket": case "bakery": case "convenience_store": placeIcons = pathImagePlace + 'mercado.fw.png'; break; case "bus_station": case "subway_station": case "train_station": placeIcons = pathImagePlace + 'transporte_publico.fw.png'; break; case "pet_store": case "veterinary_care": placeIcons = pathImagePlace + 'petshop.fw.png'; break; default: // placeIcons = place.icon; // placeIcons = pathImagePlace + 'petshop.fw.png'; break; } var image = { url: placeIcons, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: scaleSize }; var marker = new google.maps.Marker({ map: mapa, icon: image, title: place.vicinity, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function () { infowindow.setContent(infoMapa); infowindow.open(mapa, this); }); return marker; } function initStreetView(IDComponente, lat, lon, heading, pitch, zoom) { var position = new google.maps.LatLng(lat, lon); var panoramaOptions = { position: position, pov: { heading: heading, pitch: pitch, zoom: zoom } }; var panoramic = new google.maps.StreetViewPanorama(document.getElementById(IDComponente), panoramaOptions); panoramic.setVisible(true); var fenway = position; var map = new google.maps.Map(document.getElementById('mapVisaoRua'), { center: fenway, zoom: 14 }); var panorama = new google.maps.StreetViewPanorama( document.getElementById(IDComponente), { position: fenway, pov: { heading: 34, pitch: 10 } }); map.setStreetView(panorama); } function carregarPontosProximos() { $('.pontos-proximos input[type="checkbox"]').on('change', function () { if ($(this).prop('checked') == true) { for (var i = 0; i < pontosInteresse.length; i++) { if ($(this).val() == pontosInteresse[i].termo) { marcarPontos(pontosInteresse[i]); } } } else { for (var i = 0; i < pontosInteresse.length; i++) { if ($(this).val() == pontosInteresse[i].termo) { desmarcarPontos(pontosInteresse[i]); } } } }); } function loadMapStreetView() { $('#map').css('display', 'none'); $('#mapVisaoRua').css('display', ''); $('#mapRotas').css('display', 'none'); initStreetView("mapVisaoRua", lat, lon, 165, 0, 1); } function ocultarPontosProximos() { $('.pontos-proximos').hide('slow'); $('.bloco-mapa').removeClass('col-md-9').addClass('col-md-12'); $('.menu-mapa').css('borderTopRightRadius', '10px'); } function exibirPontosProximos() { $('.pontos-proximos').show('slow'); $('.bloco-mapa').removeClass('col-md-12').addClass('col-md-9'); $('.menu-mapa').css('borderTopRightRadius', '0px'); } function carregarModalMaximizar(){ $('.maximizar').on('click', function(){ $('.modal-imagens').modal(); carregarCarrossel('.modal-imagens'); // função em geral.js carregarMaisFotosImovel('.modal-imagens'); // função em geral.js }) } function comoChegar_DistanciaAte(ponto1, ponto2, centro, tipo) { var idMap = ''; var origem = ''; var destino = ''; if (tipo == 'como-chegar') { idMap = 'mapRotas'; origem = ponto1; destino = ponto2; var map = new google.maps.Map(document.getElementById('mapRotas'), { center: centro, scrollwheel: false, zoom: 13 }); } else if (tipo == 'distancia-ate') { idMap = 'mapDistanciaAte'; origem = ponto2; destino = ponto1; var map = new google.maps.Map(document.getElementById('mapDistanciaAte'), { center: centro, scrollwheel: false, zoom: 13 }); } var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var request = { origin: origem, destination: destino, travelMode: google.maps.DirectionsTravelMode.DRIVING, }; directionsDisplay = new google.maps.DirectionsRenderer({ 'map': map, }); directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { if (tipo == 'distancia-ate') { var distanciaKm = (response.routes[0].legs[0].distance.value / 1000).toFixed(1); //response.routes[0].legs[0].distance.value; var duracaoMin = (response.routes[0].legs[0].duration.value / 60).toFixed(0); $('.info-distancia').text(distanciaKm + " km - Aproximadamente " + duracaoMin + " min de carro"); } directionsDisplay.setDirections(response); $('.bloco-endereco-rota .endereco-inicial .erro').hide('slow'); } else if (status == google.maps.DirectionsStatus.NOT_FOUND) { $('.bloco-endereco-rota .endereco-inicial .erro').show('slow'); } }); } function voltarParaBusca(){ $('.voltar-resultado-busca span').on('click', function(){ window.history.back(); }); } /* Compartilhamento */ function compartilhe() { $(document).on("click", '.compartilhe', function () { switch ($(this).data("app")) { case "email": $("#compartilhar_modal").modal('show'); break; case "facebook": FB.ui({ display: !(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ? 'popup' : 'touch', method: 'share_open_graph', action_type: 'og.likes', mobile_iframe: true, action_properties: JSON.stringify({ object: window.location.href }) }, function (response) { if (response && !response.error_message) { // alert('Posting completed.'); } else { // alert('Error while posting.'); } }); break; case "whatsapp": if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { var text = $(this).data("text"); var message = encodeURIComponent(text) + " - " + encodeURIComponent(window.location.href); var whatsapp_url = "whatsapp://send?text=" + message; irPara(whatsapp_url); } else { $("#erro_whatsapp").modal('show'); } break; } }); } $(function () { function reposition() { var modal = $(this), dialog = modal.find('.compartilhe_modal'); modal.css('display', 'block'); dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2)); } $('.modal').on('show.bs.modal', reposition); $(window).on('resize', function () { $('.modal:visible').each(reposition); }); function compartilha_email_submit() { $("#env_form_email").on("click", function () { //alert('teste') $("#form_compartilhe_email").validate({ debug: true, rules: { email: { email: true } }, messages: { email: { email: "Informe um Email válido!" } }, submitHandler: function (form) { $.ajax({ url: 'ajax-gravar-fila-email', type: form.method, data: {'tipo_email':$(form).find('#local').val(), 'id_imovel':$(form).find('#id_imovel').val(), 'nome':$(form).find('#nome').val(), 'email':$(form).find('#email').val(), 'emails_destinatarios':$(form).find('#emails_destinatarios').val(), 'telefone':$(form).find('#telefone').val(), 'mensagem':$(form).find('#mensagem').val(), 'id_transacao': $('#id_transacao').val(), 'url': window.location.href}, success: function (response) { console.log(response); if ($("#form_compartilhe_email").valid()) { //console.log(response); form.reset(); $("#compartilhar_modal").modal('hide'); // alert("Compartilhamento realizado com sucesso!"); } } }); } }); }); } compartilhe(); compartilha_email_submit(); }); function abreModalContatar() { $(document).on('click','.falar-agora', function () { var telefones = ''; var idImovel = pegarIdImovel($(this)); // funcao em buscador.js $.post("ajax-modal-falar-agora", {'id-imovel': idImovel, 'transacao': $("#transacao").val()}, function (retorno) { ocultarTelefone(); $('.enviar').removeAttr('disabled'); $('.modal-falar-agora .nome-imobiliaria').text(retorno.nome_imobiliaria); $('.modal-falar-agora .mensagem').val(retorno.mensagem); $('.modal-falar-agora #id_imovel').val(idImovel); $('.modal-falar-agora #id_transacao').val(retorno.id_transacao); telefones += 'Telefone: ' + retorno.telefone.split(',')[0] + '
'; if (retorno.telefone.split(',')[1] != undefined && retorno.telefone.split(',')[1] != '') { telefones += 'Whatsapp: ' + retorno.telefone.split(',')[1].replace('*', ''); } $('.modal-falar-agora .ver-telefone .telefones').html(telefones); if (retorno.logo != '') { $('.modal-falar-agora .logo-imobiliaria img').attr('src', "http://chavefacil.com.br/imagem?imagem=http://chavefacil.com.br/site/imagens/logos/imobiliarias/" + retorno.id_imobiliaria + ".jpg,w=123"); $('.modal-falar-agora .logo-imobiliaria').removeClass('dNone'); } else { $('.modal-falar-agora .logo-imobiliaria').addClass('dNone'); } $('#modal-falar-agora').modal(); } ); }); } function carregarVerTelefone() { $('.b-contatar').find('#ver-telefone').on('click', function () { $(this).addClass("ativo"); $(this).find('.texto').hide('slow'); $(this).find('.telefones').show('slow'); }); } function ocultarTelefone() { $('.contatar #ver-telefone').removeClass("ativo"); $('.contatar #ver-telefone').find('.texto').show(); $('.contatar #ver-telefone').find('.telefones').hide(); }var buscaAjaxEmAndamento = null; var localidadesAjax = null; $(document).ready(function () { // $('#preco-min, #preco-max, #area-max, #area-min').selectpicker('destroy').editableSelect({ effects: 'default', filter: false }); var cmd = $("#cmd").val(); $('#transacao').change(function () { trocarTiposImoveis(); trocarFaixaValores(); if (cmd == "imoveis" || cmd == "imovel") { // se página de resultado ou ficha do imóvel, já refazer a busca buscarImoveis(1); // REFAZ A BUSCA, SEM PEDIR CLIQUE NO BOTÃO DE BUSCA } }); $("#tipo-imovel").change(function () { if (!$("#tipo-imovel").val()) { $(".buscador").find('.buscar-imoveis').find("button").addClass("erro"); } else { $(".buscador").find('.buscar-imoveis').find("button").removeClass("erro"); } if (cmd == "imoveis" || cmd == "imovel") { // se página de resultado ou ficha do imóvel, já refazer a busca buscarImoveis(2); // REFAZ A BUSCA, SEM PEDIR CLIQUE NO BOTÃO DE BUSCA } }); $('.precoMinimo,.precoMaximo').maskedInput("000.000.000.000.000,00", {reverse: true}); var xhr; $('#localidade').autoComplete({ minChars: 3, source: function (term, response) { try { xhr.abort(); } catch (e) { console.log("error ajax auto complete", e.message); } xhr = $.post('/ajax-pegar-localidades', {localidade: term}, function (data) { response(data); }); }, renderItem: function (item, search) { search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); response = null; if (item.bairros !== "" && item.bairros !== undefined && (item.bairros.length > 0)) { response = "
Bairros
"; zebrado_0 = null; zn_0 = 0; for (var i = 0; i < item.bairros.length; i++) { if (zn_0 % 2 === 0) { zebrado_0 = 'par'; } else { zebrado_0 = 'impar'; } response += '
' + item.bairros[i].localidade.replace(re, "$1") + '
'; zn_0++; } } if (item.cidades !== "" && item.cidades !== undefined && (item.cidades.length > 0)) { response = "
Cidades
"; zebrado_1 = null; zn_1 = 0; for (var i = 0; i < item.cidades.length; i++) { if (zn_1 % 2 === 0) { zebrado_1 = 'par'; } else { zebrado_1 = 'impar'; } response += '
' + item.cidades[i].localidade.replace(re, "$1") + '
'; zn_1++; } } return response; }, onSelect: function (e, term, item) { buscarImoveis(3); } }); $(".buscar-imoveis").change(function () { var cmd = $("#cmd").val(); if (cmd == "imoveis" || cmd == "imovel") { // se página de resultado ou ficha do imóvel, já refazer a busca buscarImoveis(4); } }); $("body").on('click', '#buscar', function(){ buscarImoveis("b"); }); $("#localidade").keyup(function () { if ($(this).val().length > 3) { $("#localidade").removeClass("erro"); } }); $(".buscar").click(function () { buscarImoveis(6); }); $("#pesquisar-codigo").click(function () { var obj = $("#codigo-buscar"); if (obj.val() == "") { obj.addClass("erro"); } else { obj.removeClass("erro"); buscarImoveis("c"); } }); $(".banner").click(function() { var local = $(this).attr("local"); $.post("ajax-registrar-clique-banner", {'id': $(this).attr("id"), 'local': $(this).attr("local"), 'url': document.location.href}, function (url) { // direcionar para a página do banner if(url != ""){ if(local == "1") { window.location = url; } else { window.open(url, '_blank'); } } } ); ; }); $(".registrar-clique").click(function() { $.post("ajax-registrar-clique-resultado-busca", {'pag': 'res', 'id-imovel': $("#id_imovel").val(), 'id': $(this).attr("id")}, function() { }); }); }); function carregarVerTelefone() { $('.b-contatar').find('#ver-telefone').on('click', function () { $(this).addClass("ativo"); $(this).find('.texto').hide('slow'); $(this).find('.telefones').show('slow'); }); } function maisFiltros() { $('#mais-filtros').on('click', function () { $('.mais-filtros').toggle('slow'); if ($(this).text() == 'MAIS FILTROS') { $(this).text('MENOS FILTROS'); $(".buscador").addClass("area-mais-filtros"); } else { $(this).text('MAIS FILTROS'); $(".buscador").removeClass("area-mais-filtros"); } }); } function buscarImoveis(controle, parametro) { $(".buscar").attr('disabled', 'disabled'); var cmd = $("#cmd").val(); var erros = ""; if (!$("#transacao").val()) { $("#transacao").addClass("erro"); erros += ",transação"; } else { $("#transacao").removeClass("erro"); } if ( ($("#tipo-imovel").val() == "" || $("#tipo-imovel").val() == "0") && cmd != "imobiliaria" ) { $(".buscador").find('.buscar-imoveis').find("button").addClass("erro"); erros += ",localidade"; } else { $(".buscador").find('.buscar-imoveis').find("button").removeClass("erro"); } if (!$("#localidade").val()) { $("#localidade").addClass("erro"); erros += ",localidade"; } else { if($("#localidade").val().split(',')[1] != undefined && $("#localidade").val().split(',')[1].trim() != ''){ $("#localidade").removeClass("erro"); }else{ $("#localidade").addClass("erro"); erros += ",localidade"; } } if (erros != "") { $("#msg-erro").html("Por favor, preencha os dados faltantes: " + erros.substr(1)); $("#erro-falta-de-dados").fadeTo(2000, 500).slideUp(500, function () { $("#erro-falta-de-dados").slideUp(500); }); } else { if (controle == undefined) { controle = (cmd == "imoveis" ? "" : "h"); // clique no botão 'BUSCAR' da página principal OU no imóvel } fazerBuscaImoveis(controle, parametro); } $(".buscar").removeAttr('disabled'); } function removerFiltroBuscador(filtro, naoRefazerBusca) { naoRefazerBusca = naoRefazerBusca ? true : false; ajustarFiltroEliminadoNaTela(filtro); var filtros = ""; var idsTiposImoveis = ""; var idsBairros = ""; var idsImobiliarias = ""; var quartos = ""; var vagasGaragem = ""; var banheiros = ""; var outrasOpcoes = ""; $(".filtro-aplicado").each(function () { var valor = $(this).attr("value"); if (!valor || (valor && valor != filtro)) { if (valor.substr(0, 4) == "tip-") { idsTiposImoveis += ";" + valor.substr(4); } else if (valor.substr(0, 4) == "bai-") { idsBairros += ";" + valor.substr(4); } else if (valor.substr(0, 4) == "imb-") { idsImobiliarias += ";" + valor.substr(4); } else if (valor.substr(0, 4) == "qto-") { quartos += ";" + valor.substr(4); } else if (valor.substr(0, 4) == "vag-") { vagasGaragem += ";" + valor.substr(4); } else if (valor.substr(0, 4) == "bnh-") { banheiros += ";" + valor.substr(4); } else if (valor.substr(0, 4) == "out-") { outrasOpcoes += ";" + valor.substr(4); } else if (valor.substr(0, 4) == "vli-" || valor.substr(0, 4) == "vls-" || valor.substr(0, 4) == "ari-" || valor.substr(0, 4) == "ars-") { filtros += "," + valor.substr(0, 3) + "=" + valor.substr(4); } else { filtros += "," + valor + "=" + $(this).html().trim(); } } }); if (idsTiposImoveis != "") { filtros += ",idtip=" + idsTiposImoveis.substr(1); } if (idsBairros != "") { filtros += ",idbai=" + idsBairros.substr(1); } if (idsImobiliarias != "") { filtros += ",idimb=" + idsImobiliarias.substr(1); } if (quartos != "") { filtros += ",qto=" + quartos.substr(1); } if (vagasGaragem != "") { filtros += ",vag=" + vagasGaragem.substr(1); } if (banheiros != "") { filtros += ",bnh=" + banheiros.substr(1); } if (outrasOpcoes != "") { filtros += ",out=" + outrasOpcoes.substr(1); } if (!naoRefazerBusca) { fazerBuscaImoveis("f", filtros.substr(1)); } } function ajustarFiltroEliminadoNaTela(filtro) { if (filtro.substr(0, 4) == "vli-") { $("#preco-min").val($("#preco-min option:first").val()); } else if (filtro.substr(0, 4) == "vls-") { $("#preco-max").val($("#preco-max option:first").val()); } else if (filtro.substr(0, 4) == "ari-") { $("#area-min").val($("#area-min option:first").val()); } else if (filtro.substr(0, 4) == "ars-") { $("#area-max").val($("#area-max option:first").val()); } else if (filtro.substr(0, 4) == "qto-") { ajustarFiltroSelectNaTela("quartos", filtro); } else if (filtro.substr(0, 4) == "vag-") { ajustarFiltroSelectNaTela("vagas", filtro); } else if (filtro.substr(0, 4) == "bnh-") { ajustarFiltroSelectNaTela("banheiros", filtro); } else if (filtro.substr(0, 4) == "out-") { $("#" + filtro).prop("checked", false); } } function ajustarFiltroSelectNaTela(id, filtro) { $(('#' + id) + ' :selected').each(function () { if ($(this).attr("id") == filtro) { $(this).prop("selected", false); } }); $(('#' + id)).selectpicker("refresh"); } function buscaImoveisDeCoordenadas(coordenadas) { buscarImoveis("a", coordenadas); } function buscarImoveisMapa() { buscarImoveis("m"); } function adicionarCliqueOrdenacao() { $('#ordenacao').change(function () { buscarImoveis("o"); }); } function adicionarCliquesImoveis() { $(document).find(".imovel").each( function (i) { $(this).find('.ir-ficha-imovel').each( function () { $(this).on('mouseup', function () { var idImovel = pegarIdImovel($(this)); var url = pegarUrlImovel($(this)); $.post("ajax-registrar-clique-resultado-busca", {'pag': 'res', 'id-imovel': idImovel, 'id': $(this).attr("id")}, function () { } ); }); } ); } ); } $(function () { $('#refinar-busca').click(function () { var btn = $(this); btn.html("Esconder Refinar Busca").css({ cursor: "wait" }); $(".refinar").slideToggle("slow", function () { btn.css({ cursor: "pointer" }); if ($(this).is(":hidden")) { btn.html("Refinar Busca"); } }); }); /* End Refina Busca*/ $(window).on('resize', function () { if (!$(".toggle").is(":visible") && !$(".refinar").is(':visible')) { $(".refinar").css({'display': ''}); } }); var tfocus = false; var localidadeAnterior = $('#localidade').val(); $('#localidade').on("focus, click", function (e) { if ($(this).val().length > 0 && tfocus || tfocus === false) { localidadeAnterior = $('#localidade').val(); $(this).val(""); } e.stopPropagation(); $(this).popover({ trigger: 'manual', container: '.input-group-icon', template: '', html: true, content: function () { return $('#busca_popover').html(); } }); if ($(this).val().length <= 0) { $(this).popover('show'); } }).keyup(function (e) { e.stopPropagation(); if ($(this).val().length >= 1) { $(this).popover('hide'); } }).blur(function (e) { e.stopPropagation(); tfocus = true; // $('#localidade').popover("destroy"); $(this).popover('hide'); if ($(this).val().length == 0) { $(this).val(localidadeAnterior); } }), $(".ir-para-busca").click(function () { irPara(SITE + "/imoveis/" + $(this).attr("alvo")); }), $(".ir-para-topo").click(function () { irParaTopo(); }), $(".posicionar-buscador").click(function () { var link_text = $(this).text(); $("#localidade").popover({ trigger: 'manual', container: '.input-group-icon', template: '', html: true, content: function () { $('#busca_popover_rodape').find("p strong").text(link_text); return $('#busca_popover_rodape').html(); } }).keyup(function (e) { e.stopPropagation(); if ($(this).val().length >= 1) { $(this).popover('hide'); } }).blur(function (e) { e.stopPropagation(); $(this).popover('destroy'); }); $("#localidade").popover('show'); posicionarBuscador($(this).attr("id-transacao"), "#menu-cabecalho"); }); }); function posicionarBuscador(idTransacao, posicao) { $('#transacao option[value=' + idTransacao + ']').attr('selected', 'selected'); $('#transacao').selectpicker("refresh"); trocarTiposImoveis(); irParaTopo(posicao); $("#localidade").focus(); } function trocarTiposImoveis() { // $.ajaxSetup({async: false}); $.post("ajax-pegar-tipos-imoveis", {'transacao': $("#transacao").val(), 'tipo-imovel': $("#tipo-imovel").val(), 'tipo': $("#tipo-imovel").attr("tipo")}, function (html) { $("#tipo-imovel").html(html); } ); } function trocarFaixaValores() { $.post("ajax-pegar-faixa-valores", {'transacao': $("#transacao").val()}, function (html) { // $("#preco-min, #preco-max").editableSelect('destroy'); // $("#preco-min, #preco-max").html(html); // $("#preco-min, #preco-max").editableSelect({ effects: 'default', filter: false }); $("#preco-min").html(html).selectpicker('refresh'); $("#preco-max").html(html).selectpicker('refresh'); } ); } function pegarIdImovel(obj) { while (($(obj) && $(obj).attr("id-imovel")) == undefined) { obj = $(obj).parent(); } return $(obj).attr("id-imovel"); } function pegarUrlImovel(obj) { while (!$(obj).hasClass("imovel")) { obj = $(obj).parent(); } var url = $(obj).find(".url").attr("url-imovel"); if (url != undefined && url != "/?") { return url; } else { return ""; } } function fazerBuscaImoveis(controle, parametro) { controle = (controle != undefined ? controle : ""); $('.bloco-aguarde').show(); /* * controle: * nada: faz a busca na página 1 e atualiza toda a página de resultado * a: busca imóveis nas coordenadas passadas em 'parametro' * b: busca vinda do botão 'buscar imóvel' * c: busca imóveis com código(imobiliária) passado em 'parametro' * f: busca imóveis com os filtros passados em 'parametro' * h: busca vinda da home * l: busca vinda do 'limpar filtros' * m: busca do mapa * 2: quando trocou o select do tipo de imóvel */ if (controle != "+" || (controle == "+" && !buscaAjaxEmAndamento)) { if (buscaAjaxEmAndamento) { buscaAjaxEmAndamento.abort(); buscaAjaxEmAndamento = null; } var filtrosAplicar = ""; if (controle == "a") { coordenadasMapa = parametro; } else { coordenadasMapa = $("#coordenadasMapa").val(); } var tipoImovel = ""; $('#tipo-imovel :selected').each(function () { if ($(this).val().trim() != "") { tipoImovel += "," + ($(this).val().trim()); } }); tipoImovel = tipoImovel.substr(1); var tipo = $('#tipo-imovel').attr("tipo"); var idsTiposImoveis = ""; // NÃO FUNCIONOU // if(controle != "b") { // clicado no botão 'buscar'... pegar os tipos de imóveis do grupo // $(".filtro-aplicado").each(function () { // pegar dos filtros aplicados // var valor = $(this).attr("value"); // if (valor.substr(0, 4) == "tip-") { // idsTiposImoveis += ";" + valor.substr(4); // } // }); // } idsTiposImoveis = idsTiposImoveis.substr(1); if (controle == "f") { // aplicar na busca somente os filtros da sessão 'filtros aplicados' filtrosAplicar = parametro + ",tip=" + tipoImovel + ",tipi=" + tipo; } else { var cmd = $('#cmd').val(); var transacao = $('#transacao').val(); var localidade = $('#localidade').val(); var idImobiliaria = $('#id-imobiliaria').val(); // página de imobiliárias idImobiliaria = idImobiliaria == undefined ? "" : idImobiliaria; if (controle == "b" || controle == "h") { // vindo da home ou da página de imobiliárias //$("#lista-imoveis").html("Aguarde o carregamento dos imóveis..."); $.post("ajax-montar-url-busca", {'transacao': transacao, 'tipo-imovel': tipoImovel, 'localidade': localidade, 'tipo': tipo, 'cmd': cmd, 'id-imobiliaria': idImobiliaria}, function (url) { irPara(SITE + "/" + url); } ); } else { var valorMinimo = (null != $("#preco-min").val()) ? $("#preco-min").val().replaceAll(".", "").replaceAll(",",".") : ''; console.log('VM: '+ valorMinimo); var valorMaximo = (null != $("#preco-max").val()) ? $("#preco-max").val().replaceAll(".", "").replaceAll(",",".") : ''; var areaMinima = (null != $("#area-min").val()) ? $("#area-min").val().replaceAll(".", "").replaceAll(",",".") : ''; var areaMaxima = (null != $("#area-max").val()) ? $("#area-max").val().replaceAll(".", "").replaceAll(",",".") : ''; var dormitorios = ""; $('#quartos :selected').each(function () { if ($(this).val().trim() != "") { dormitorios += (dormitorios == "" ? "" : ";") + ($(this).val().trim()); } }); var vagasGaragem = ""; $('#vagas :selected').each(function () { if ($(this).val().trim() != "") { vagasGaragem += (vagasGaragem == "" ? "" : ";") + ($(this).val().trim()); } }); var banheiros = ""; $('#banheiros :selected').each(function () { if ($(this).val().trim() != "") { banheiros += (banheiros == "" ? "" : ";") + ($(this).val().trim()); } }); var somenteCodigo = ""; var codigoBuscar = ""; if (controle == "c") { somenteCodigo = $("#somente-codigo").prop("checked"); codigoBuscar = $("#codigo-buscar").val(); } var outrasCaracteristicas = ""; $(".buscar").each( function () { outrasCaracteristicas += $(this).prop("checked") ? "1" : "0"; } ); } } if (controle == "+") { var pagina = $("#pagina").val(); pagina++; } else { pagina = 1; } $("#pagina").val(pagina); $("#pag").html(pagina); var ordenacao = $("#ordenacao").val(); var idLogBusca = $("#idLogBusca").val(); var visualizacao = $(".visualizacao.visualizacao-ativa").attr("id"); if (visualizacao == 'mapa' && coordenadasMapa == '') controle = 'm'; // //----------------------- if(controle != "f") { var idsBairros = ""; var idsImobiliarias = ""; var outrasOpcoes = ""; var filtrosAplicar = ",ord=" + ordenacao; if(valorMinimo != "") { filtrosAplicar += ",vli=" + valorMinimo; } if(valorMaximo != "") { filtrosAplicar += ",vls=" + valorMaximo; } if(areaMinima != "") { filtrosAplicar += ",ari=" + areaMinima; } if(areaMaxima != "") { filtrosAplicar += ",ars=" + areaMaxima; } if(transacao != "") { filtrosAplicar += ",trs=" + transacao; } if(outrasCaracteristicas != "") { filtrosAplicar += ",out1=" + outrasCaracteristicas; } if(tipo.toLowerCase() == "grupo") { filtrosAplicar += ",idgrp=" + tipoImovel; } if(idImobiliaria != "") { filtrosAplicar += ",idimb=" + idImobiliaria; } if(idLogBusca != "") { filtrosAplicar += ",idbus=" + idLogBusca; } if(localidade != "") { filtrosAplicar += ",loc=" + localidade.replace(",",";"); } $(".filtro-aplicado").each(function () { var valor = $(this).attr("value"); if (valor.substr(0, 4) == "tip-") { idsTiposImoveis += (idsTiposImoveis == "" ? "" : ";") + valor.substr(4); } else if (valor.substr(0, 4) == "bai-") { idsBairros += (idsBairros == "" ? "" : ";") + valor.substr(4); } else if (valor.substr(0, 4) == "imb-") { idsImobiliarias += (idsImobiliarias == "" ? "" : ";") + valor.substr(4); } else if (valor.substr(0, 4) == "vli-" || valor.substr(0, 4) == "vls-" || valor.substr(0, 4) == "ari-" || valor.substr(0, 4) == "ars-") { filtrosAplicar += (filtrosAplicar == ""? "" : ",") + valor.substr(0, 3) + "=" + valor.substr(4); } else if (localidade == "" && (valor == "cid" || valor == "uf")) { // pegar cidade e uf se não encontrou na caixa de texto filtrosAplicar += (filtrosAplicar == ""? "" : ",") + valor + "=" + $(this).html().trim(); } }); if (idsTiposImoveis != "" && controle != "2") { // ao trocar o tipo de imóvel, não considerar o que tinha nos filtros filtrosAplicar += ",idtip=" + idsTiposImoveis; } if (idsBairros != "") { filtrosAplicar += ",idbai=" + idsBairros; } if (idsImobiliarias != "") { filtrosAplicar += ",idimb=" + idsImobiliarias; } if (dormitorios != "") { filtrosAplicar += ",qto=" + dormitorios; } if (vagasGaragem != "") { filtrosAplicar += ",vag=" + vagasGaragem; } if (banheiros != "") { filtrosAplicar += ",bnh=" + banheiros; } if (outrasOpcoes != "") { filtrosAplicar += ",out=" + outrasOpcoes; } if(codigoBuscar != "") { filtrosAplicar += ",cod=" + codigoBuscar; if(somenteCodigo === true) { filtrosAplicar += ",scod=true"; } } } // //----------------------- if (controle != "m") { // $("#lista-imoveis").html("Aguarde o carregamento dos imóveis..."); } buscaAjaxEmAndamento = $.post("ajax-buscar-imoveis", // {'url': document.location.href, 'transacao': transacao, 'tipo-imovel': tipoImovel, 'ids-tipos-imoveis': idsTiposImoveis, 'tipo': tipo, 'localidade': localidade, 'valor-minimo': valorMinimo, 'valor-maximo': valorMaximo, 'area-minima': areaMinima, 'area-maxima': areaMaxima, 'dormitorios': dormitorios, 'vagas-garagem': vagasGaragem, 'banheiros': banheiros, 'pagina': pagina, 'outras-caracteristicas': outrasCaracteristicas, 'codigo-buscar': codigoBuscar, 'somente-codigo': somenteCodigo, 'controle': controle, 'filtros': filtrosAplicar, 'coordenadas-mapa': coordenadasMapa, 'ordenacao': ordenacao, 'visualizacao': visualizacao, 'id-log-busca': idLogBusca, 'id-imobiliaria': idImobiliaria}, {'url': document.location.href, 'pagina': pagina, 'controle': controle, 'filtros': filtrosAplicar, 'coordenadas-mapa': coordenadasMapa, 'ordenacao': ordenacao, 'visualizacao': visualizacao}, function (html) { if (controle == "m") { // mapa mapa = null; initMap(html.imoveis); // função está no arquivo resultado-busca.js $('.lista-filtros-aplicados').html(html.filtros); var imoveis_encontrados = ''; if (html.qtImoveisEncontrados == 0) imoveis_encontrados = 'Nenhum imóvel encontrado'; else if (html.qtImoveisEncontrados == 1) imoveis_encontrados = '1 imóvel encontrado'; else imoveis_encontrados = html.qtImoveisEncontrados + ' imóveis encontrados'; $('.imoveis-encontrados').html(imoveis_encontrados); } else if (controle == "+") { // paginação ou ordenação $("#lista-imoveis").append(html); $(document).find('.super-destaque').find('.left').click(); // dispara click para carregar todas as imagens do super destaque } else { $("#resultado-busca").html(html); $(document).find('.super-destaque').find('.left').click(); // dispara click para carregar todas as imagens do super destaque var url = document.location.href; var novaURL = $("#novaURL").val(); if (url != SITE + "/" +novaURL) { $(document).prop("title",$("#tituloPagina").val()); if(novaURL != undefined && novaURL.trim() != ''){ window.history.pushState("", "", SITE + "/" +novaURL); } } } buscaAjaxEmAndamento = null; $('select:not(.no-select2)').selectpicker("refresh"); loadImoveis.hide(); } ); } }