$(".input-header").focus();

var imoveis = $("#inputImoveis").data("imoveis");
var countBairro = $("#inputImoveis").data("count_bairro");
var countQuadra = $("#inputImoveis").data("count_quadra");
var countConjunto = $("#inputImoveis").data("count_conjunto");
var countImoveis = $("#inputImoveis").data("count_imoveis");
var intencao = {'para_morar':0,'para_trabalhar':0}; // variavel de controle do switch "para morar" (param 1) e "para trabalhar" (param 2)
var validFormBuscar = false;
var deferredLocation = $.Deferred();

var clique = 0;
//Configurações iniciais

var $niveis = {
  1: [18, 19, 20],
  2: [17],
  3: [14, 15, 16],
  4: [12, 13],
  5: [10, 11]
};

var countMarker = 4; //quantidade de camadas de zooom
var nMarkerIni = 4; //numero da camada que inicia o mapa
var centerMap = { lat: -15.7875374, lng: -47.9202016 };
//var zoomMap     = 12;

//variaveis do mapa
var map,
  popup,
  popups = [],
  Popup;
var latid;
var longid;

//variaveis da busca
var $pesquisa = "";
var $tipo = "";
var $quartos = "";
var $valor = "";
var $bairro = "";
var $metro_quadrado = "";
var $tipo_busca = "";

//scrollHeight
var container_lista = $(".container-lista").height();
var bloco_imoveis = $(".blocoImoveis").height();
var container_filtro = $(".container-filtro").height();
var container_filtro_fixed = $(".container-filtro-fixed").height();
var sidebar_left = $(".sidebar-left").height();
var container_header = $(".container-header").height();
var sidebar_sem_header = sidebar_left - (container_header + container_filtro_fixed + 10);
var h = $(this).height();
var w = $(this).width();
var header = $(".bg-theme").height();
var footer = $(".footer").height();
var fixed = false;
var scrollHandler = true;
var pathname = window.location.pathname;
var total = h - divs;

$(".collapse-icon").click(function() {
  $(".collapse-icon").find("i.material-icons.arrow").html("arrow_drop_down");
  $(".collapse-icon").attr("title", "Visualizar Filtro");
});

$("#filtro").on("shown.bs.collapse", function() {
  if (w <= 768) {
    $('.sidebar-left').css('height',"auto");
    $('.container-filtro').show();
  }else{
    $('.sidebar-left').css('height',total);
    
    $('.container-lista').hide();
    $('.container-form-filtro').addClass('height-container-filtro');
      
    ajusta_container_lista(1);
    if(h <= 768){
         $('.container-form-filtro').addClass("height100vh");
    }
  }
});

$('.btn-reset').click(function(){
    $(".content-finalidade").removeClass("active")
    set_switch('para_morar');
    set_switch('para_trabalhar');
    $('input[name=pesquisa]').val('');
});


$("#filtro").on("hidden.bs.collapse", function() {
    if (w <= 768) {
        $('.container-filtro').hide();
    }else{
        $('#filtro-list').show();
        
        $('.container-lista').show();
        $('.container-form-filtro').removeClass('height-container-filtro');
        ajusta_container_lista(0);
        
        if(h <= 768){
            $('.container-form-filtro').removeClass("height100vh");
        }
    }
});

$("body").on("click", ".collapse-icon.collapsed", function() {
  $(".collapse-icon.collapsed").find("i.material-icons.arrow").html("arrow_drop_up");
  $(".collapse-icon.collapsed").attr("title", "Esconder Filtro");
});

$('.box-icons-filter').on('click',function(e){
    
    if (w <= 768) {
    
        target = $(this).data("icon");
        active = $(".box-icons-filter.active").data("icon");
        
        if(target == active)
        {
            e.stopPropagation();
        }
        else
        {
            $(".box-icons-filter").removeClass("active");
            $(this).addClass("active");
            
            icon = $(this).data("icon");
            
            if(icon !== "filtro-maps"){
            $(".container-page-busca").find("#filtro-maps.collapse").removeClass("show");
            }
            if(icon == "filtro"){
                $(".container-filtro-fixed").show();
                $('.container-form-filtro').addClass('height-container-filtro');
            }
            else{
                $('.container-form-filtro').removeClass('height-container-filtro');
                $(".container-filtro-fixed").hide();
            }
            /*if(icon == "filtro-list"){
                $('.container-page-busca .container-filter-sidebar-left').css('height',"100vh");
            }
            else{
                $('.container-page-busca .container-filter-sidebar-left').css('height',"auto");
            }*/
        }
    }
    
    
});

$(document).on("click", ".ui-menu-item", function() {
    /*if(w <=1024){
     $(".container-page-home.height100vh").removeClass("height100vh");
    }*/
    
    if(w <=991){
        $(".stretched").addClass("autocomplete-responsive");
        $(".stretched").addClass("autocomplete-responsive");
        
        $(".box-caret.box-navbar-nav").hide();
        $(".autocomplete-responsive .ui-widget.ui-widget-content").removeClass("d-block");
    }
    
    if(w <=768){
        $(".filter-list").trigger("click");
    }
});

function scrollHeightAuto() {
  if (w <= 768) {
    $(".container-lista").css("height", "auto");
    $(".container-lista").removeClass("scroll-height");
  }
}

function ajusta_container_lista(e) {
  var area_visivel = e == 1 ? sidebar_sem_header : sidebar_sem_header;
  
  bloco_imoveis = $(".blocoImoveis").height();
  
  if (bloco_imoveis > area_visivel) 
  {
        if(w > 768)
        {
            $(".container-lista").css({ height: area_visivel }).addClass("scroll-height");
        
            if(h <= 768){
                $('.container-lista').addClass("height100vh");
            }
        }
        else
        {
           $(".container-lista").css("height","100%");
        }
  } 
  else 
  {
        if(w > 768){
            $(".container-lista").css("height", "auto");
            $(".container-lista").removeClass("scroll-height");
        }
  }
  //responsiveHeightAuto();
}

$(window).scroll(function() {
  if (scrollHandler == true) {
    /*if ($(this).scrollTop() > header && w <= 767 && fixed == false) {
      fixed = true;
      $(".container-header").addClass("fixed");
      $(".container-filtro").addClass("fixed");
    } else if ($(this).scrollTop() < header && w <= 767 && fixed == true) {
      fixed = false;
      $(".container-header").removeClass("fixed");
      $(".container-filtro").removeClass("fixed");
    }*/
  }
});

var btnSwitch = []

//set_switch('para_morar',true); mostrando apenas para morar
set_switch('para_morar');
set_switch('para_trabalhar');


function set_switch($input,$trigS = false)
{
    state = $trigS == false ? 'Off' : 'On';
    $('.'+$input).btnSwitch({
        Theme: 'Light',
        OnValue: 'On',
        ToggleState: state,
        OnCallback: function(val) 
        {
            switch_trigger($input,1);
            $('.'+$input).parents('.content-finalidade').addClass('active');
        },
        OffValue: 'Off',
        OffCallback: function (val) {
            switch_trigger($input,0);
            $('.'+$input).parents('.content-finalidade').removeClass('active');
        }
    });
}

function switch_trigger($input,$val)
{
    var $outro = ($input == 'para_morar') ? 'para_trabalhar' : 'para_morar';
    intencao[$input] = $val;

    if(intencao[$outro] == 1)
    {
        set_switch($outro);
        $('.'+$outro).parents('.content-finalidade').removeClass('active');
        intencao[$outro] = 0;    
    }
    
    buscar();
}

$(".act-finalidade").click(function(e,parm1) {
    
    var finalidade = $(this).data("switch");
    
    $('body').find('.'+finalidade).find('.btn-switch').trigger('click',parm1);
});



$(window).on("load", function() {
    
    //console.log('buscaHidden',$('#hiddenPesquisa').val());
    
    //$("#bsh-para_morar").trigger("#light-para_morar");
    
    if($('#hiddenPesquisa').val() != undefined){
        $('.act-busca').val($('#hiddenPesquisa').val());
    }
    if($('.homeTransition').length != 0)
    {
        $('.divTransition').hide();
        $(".sidebar-left").hide();
        $(".content-maps").hide();
    }
    /*loadButton($(".btnBuscar"));
    loadButton(null, false);*/
    initMap();
    navCarousel();
    
    /*deferredLocation = $.Deferred();
	initMap();
	deferredLocation.done(function(){
	    resizeWidth();
	});*/
	
    
    if (w <= 768) {
        $(".container-filtro-fixed").hide();
        $("#filtro-maps.collapse").removeClass("show");
        $(".container-lista").css("height", "auto");
        $(".container-lista").removeClass("scroll-height");
        $('.sidebar-left').css('height',"auto");
        resizeWidth();
    }else{
        $(".container-filtro-fixed").show();
        $("#filtro-maps.collapse").addClass("show");
        $('.sidebar-left').css('height',total);
        if (bloco_imoveis > sidebar_sem_header) {
            $(".container-lista")
              .css({ height: sidebar_sem_header })
              .addClass("scroll-height");
        } 
        if(h <= 768){
            $('.sidebar-left').addClass("height100vh");
            $('.container-lista').addClass("height100vh");
            $('.container-marker').addClass("height100vh");
        }
        resizeWidth();
    }
    
});


/*$(document).on("click", ".ui-menu-item", function() {
    if(w <= 768){
        $(".stretched").addClass("autocomplete-responsive");
    }
});*/

function resizeWidth(){
    
    var container_filter_sidebar_left = $(".container-filter-sidebar-left").width();
    var win = $(".container-page-busca").width();
    var container_marker_responsive = (win - container_filter_sidebar_left);
    
    //console.log("container_filter_sidebar_left "+container_filter_sidebar_left+" win "+win+" container_marker_responsive "+container_marker_responsive); 
    
    $(".container-marker").css({"max-width": container_marker_responsive});
    $(".container-marker").css({"flex": container_marker_responsive});
}

$(window).on('resize', function(){
    resizeWidth();
});

//entendi
$('body').on("click", ".act_entendi", function() {
  //$(".popup-info-favoritos").hide("drop",{direction: "down"},"slow");
  $(".popup-info-favoritos").hide();
  $.ajax({
    url: base_url + "comdono/ajax/busca_ajax/limpaPpFavorito",
    dataType: "json",
    type: "POST",
    success: function(retorno) {},
    error: function(error) {}
  });
  
});

//click ofertas
$(".act_ofertas").click(function() {
  $('.formPesquisa').trigger('submit');
});

var $restBuscaZoomm = false;

function initMapTeste(center = centerMap, marker = nMarkerIni, zoom = false) {

        var map = new google.maps.Map(document.getElementById('map'), {
            center: center,
            zoom: $niveis[marker][0],
            //mapTypeId: "satellite"
            mapTypeId: "roadmap"
        });
        // Create an array of alphabetical characters used to label the markers.
        var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var locations = [];
        i = 0;
        $.each(countImoveis, function(id, value) {
            position = new google.maps.LatLng(value.lat, value.long);
            locations[i] = position; i++;
        });
        var markers = locations.map(function(location, i) {
          return new google.maps.Marker({
            position: location,
            label: labels[i % labels.length]
          });
        });

        // Add a marker clusterer to manage the markers.
        var markerCluster = new MarkerClusterer(
                map, 
                markers,
                {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'}
            );
}

/** Initializes the map and the custom popup. */
function initMap(center = centerMap, marker = nMarkerIni, zoom = false) {
  /*console.log("ini", nMarkerIni, centerMap);
  console.log("new", center, marker);*/

  definePopupClass();
  definePopupImovel();

  // set map defaul with lat/long = Brasilia and zoom = 12
  map = new google.maps.Map(document.getElementById("map"), {
    center: center,
    zoom: $niveis[marker][0],
    //mapTypeId: "satellite"
    mapTypeId: "roadmap",
    styles: [
        {
              elementType: 'labels.icon',
              stylers: [
                  { lightness: 50 },
                  { saturation: -90 }
              ]
        },
        {featureType: 'poi', elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
    ]
  });
  
  map.addListener('click', function(event) {
    // If the event is a POI
    if (event.placeId) {
        // Call event.stop() on the event to prevent the default info window from showing.
        event.stop();
    }
    
  });
    
  $.each(countBairro, function(id, value) {
    if (value.bairroLat != "" && value.bairroLong != "") {
      lat = value.lat;
      long = value.long;

      var content = document
        .getElementsByClassName("marker_4")[0]
        .cloneNode(true);
      content.querySelector(".marker-title").innerHTML = value.bairro;
      content.querySelector(".marker-count").innerHTML = value.count;

      content.dataset.info = JSON.stringify(value); //value;//JSON.parse(value);
      content.dataset.marker = 4;

      position = new google.maps.LatLng(lat, long);
      popup = new Popup(position, content);
      popup.setMap(map);

      setMarker(marker, zoom);
    } else {
      console.log("Bairro, Lat e Long vazio", id, value);
    }
  });

//countQuadra
  $.each(countImoveis, function(id, value) {
    if (value.quadraLat != "" && value.quadraLong != "") {
      lat = value.lat;
      long = value.long;

      var content = document
        .getElementsByClassName("marker_3")[0]
        .cloneNode(true);
      content.querySelector(".marker-title").innerHTML = "";
      content.querySelector(".marker-count").innerHTML = value.count;

      content.dataset.info = JSON.stringify(value); //value;//JSON.parse(value);
      content.dataset.marker = 3;

      //position = new google.maps.LatLng(lat, long);
 position = new google.maps.LatLng(value.lat, value.long);
      popup = new Popup(position, content);
      popup.setMap(map);
      //popups.push(popup);

      setMarker(marker, zoom);
    } else {
      console.log("Quadra, Lat e Long vazio", id, value);
    }
  });


    //countConjunto
  $.each(countImoveis, function(id, value) {
    if (value.conjuntoLat != "" && value.conjuntoLong != "") {
      lat = value.lat;
      long = value.long;

      var content = document
        .getElementsByClassName("marker_2")[0]
        .cloneNode(true);
      content.querySelector(".marker-title").innerHTML = "";
      content.querySelector(".marker-count").innerHTML = value.count;

      content.dataset.info = JSON.stringify(value); //value;//JSON.parse(value);
      content.dataset.marker = 2;

      //position = new google.maps.LatLng(lat, long);
      position = new google.maps.LatLng(value.lat, value.long);
      popup = new Popup(position, content);
      popup.setMap(map);
      //popups.push(popup);

      setMarker(marker, zoom);
    } else {
      console.log("endereco, Lat e Long vazio", id, value);
    }
  }); 

  $.each(countImoveis, function(id, value) {
    position = new google.maps.LatLng(value.lat, value.long);
    var contentImovel;
    var content = document
      .getElementsByClassName("marker_1")[0]
      .cloneNode(true);
    content.querySelector(".marker-title").innerHTML = "";
    content.querySelector(".marker-count").innerHTML = value.count;

    content.dataset.info = JSON.stringify(value); //value;//JSON.parse(value);
    content.dataset.marker = 1;

    if (value.lancamento == "Sim") {
        content.classList.add("green");
        contentImovel = montaPpImovelLancamento(value);
    }else{
        contentImovel = montaPpImovel(value);
    }
    
    popup = new Popup(position, content);
    popup.setMap(map);

    popupImovel = new PpImovel(position, contentImovel);
    popupImovel.setMap(map);

    setMarker(marker, zoom);
    
    
  });
  
    /*var locations = [];
    i = 0;
    $.each(countImoveis, function(id, value) {
        position = new google.maps.LatLng(value.lat, value.long);
        locations[i] = position; i++;
    });
    var markers = locations.map(function(location, i) {
      return new google.maps.Marker({
        position: location,
        label: '1',
      });
    });
    console.log(markers[0]);
    // Add a marker clusterer to manage the markers.
    /**
     * A Marker Clusterer that clusters markers.
     *
     * @param {google.maps.Map} map The Google map to attach to.
     * @param {Array.<google.maps.Marker>=} opt_markers Optional markers to add to
     *   the cluster.
     * @param {Object=} opt_options support the following options:
     *     'gridSize': (number) The grid size of a cluster in pixels.
     *     'maxZoom': (number) The maximum zoom level that a marker can be part of a
     *                cluster.
     *     'zoomOnClick': (boolean) Whether the default behaviour of clicking on a
     *                    cluster is to zoom into it.
     *     'averageCenter': (boolean) Whether the center of each cluster should be the average of all markers in the cluster.
     *     'minimumClusterSize': (number) The minimum number of markers to be in a cluster before the markers are hidden and a count is shown.
     *     'styles': (object) An object that has style properties:
     *       'url': (string) The image url.
     *       'height': (number) The image height.
     *       'width': (number) The image width.
     *       'anchor': (Array) The anchor position of the label text.
     *       'textColor': (string) The text color.
     *       'textSize': (number) The text size.
     *       'backgroundPosition': (string) The position of the backgound x, y.
     * @constructor
     * @extends google.maps.OverlayView
     */
    /*var markerCluster = new MarkerClusterer(
            map, 
            markers,
            {
                imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
                zoomOnClick: true,
                maxZoom: 18
            }
        );
  
    console.log(markerCluster);*/
    
    
  google.maps.event.addListener(map, "zoom_changed", function() {
    zoomMarker(map.getZoom());
    if($niveis[nMarkerIni][0]+1 >= map.getZoom())
    {
        if($restBuscaZoomm){
            $bairro = '';
            pesquisaAjax(null,null);
        }
        $restBuscaZoomm = false;
        
    }else
    {
        $restBuscaZoomm = true;
    }
  });
}

function montaPpImovel(value){
    var contentImovel = document
      .getElementsByClassName("container-detalhes-imovel")[0]
      .cloneNode(true);
    
    contentImovel.setAttribute("id", "ppImovel_" + value.idImovel);
    contentImovel.querySelector(".divFavorito").innerHTML = value.divCore;
    img =  value.baseImg +"thumbnail/"+ value.img;
    if(value.img == 'no-image-gallery.png')
    {
        img = value.baseImg + value.img;
    }
    contentImovel.querySelector(".img").style.backgroundImage = "url(" + img + ")";
    contentImovel.querySelector(".valor").innerHTML = value.valor;
    contentImovel.querySelector(".bairro").innerHTML = value.bairro;
    contentImovel.querySelector(".endereco").innerHTML = value.endereco;
    /*contentImovel.querySelector(".cidade").innerHTML = value.cidade;
    contentImovel.querySelector(".estado").innerHTML = value.estado;*/
    
    if (value.tipo_imovel != null){
    contentImovel.querySelector(".tipo").innerHTML = value.tipo_imovel;
    }
    contentImovel.querySelector(".metros").innerHTML = value.metros+" m² |";
    if (value.quartos >=1){
        contentImovel.querySelector(".quartos").innerHTML = value.quartos+" Quarto(s)";
    }
    if (value.suites >=1){
        contentImovel.querySelector(".suites").innerHTML = " | "+value.suites+" Suite(s)";
    }
    
    //contentImovel.querySelector(".link").innerHTML = '<a href="'+base_url+"imovel/"+value.idImovel+'" target="_blank">Veja mais</a>';
    contentImovel.querySelector(".link").innerHTML = 'Veja mais';
    contentImovel.querySelector(".ppImovel").dataset.info = JSON.stringify(value); 
    
    return contentImovel;
}

function montaPpImovelLancamento(value){
    var contentImovel = document
      .getElementsByClassName("container-detalhes-lancamento")[0]
      .cloneNode(true);
      
    var idLancamento;
        if (value.idImovelRel != 0){
            idLancamento = value.idImovelRel; 
        }else{
            idLancamento = value.idImovel;
        }
        
    contentImovel.setAttribute("id", "ppImovel_" + value.idImovel);
    contentImovel.querySelector(".divFavorito").innerHTML = value.divCore;
    
    img = value.baseImg +"thumbnail/"+ value.img;
    
    if(value.img == 'no-image-gallery.png')
    {
        img = base_url + value.baseImg + value.img;
    }
    contentImovel.querySelector(".img").style.backgroundImage = "url(" + img + ")";
    
    contentImovel.querySelector(".bairro").innerHTML = value.dn_nome_nomefantasia;
    if (value.tipo_imovel != null){
    contentImovel.querySelector(".tipo").innerHTML = value.tipo_imovel;
    }
    contentImovel.querySelector(".content-subtitle").innerHTML = "A partir de";
    contentImovel.querySelector(".valor").innerHTML = value.valor;
    
    //contentImovel.querySelector(".img").style.backgroundImage = "url(" + base_url+value.baseImg +"thumbnail/"+ value.img + ")";
    //contentImovel.querySelector(".content-title").innerHTML = "lançamentos";
    //contentImovel.querySelector(".content-subtitle").innerHTML = "Para mais detalhes<br/>clique no link abaixo";
    //contentImovel.querySelector(".link").innerHTML = '<a href="'+base_url+"lancamento/"+idLancamento+'" target="_blank">Veja mais</a>';
    contentImovel.querySelector(".link").innerHTML = 'Veja mais';
    contentImovel.querySelector(".ppImovel").dataset.info = JSON.stringify(value); 
    
    return contentImovel;
}

function buscar() {
    
  $pesquisa = $('.act-busca').val();//$(".inputPesquisa").val();
  $tipo = $("#tipo_imovel option:selected").val();
  $quartos = $("#qtd_quartos").val();
  $valor = $("#valor").val();
  $bairro = $("#bairro_imovel").val();
  $metro_quadrado = $("#metro_quadrado").val();
  $tipo_busca = $("input[name=tipo_busca]:checked").val();
  
  if ($pesquisa != "") {
    localiza = false;
    geocode = centerMap;
    marker = nMarkerIni;

    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: $pesquisa }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          //console.log(results[0]);
          $.each(results[0].address_components, function(id, data) {
            if (data.long_name === "Distrito Federal") localiza = true;
          });
          if (localiza === true) {
            resTypesZoom = results[0].address_components[0].types;
            latid = results[0].geometry.location.lat();
            longid = results[0].geometry.location.lng();
            geocode = { lat: latid, lng: longid };
            marker = getZoomMark(resTypesZoom);
          }
        }
      } else {
        console.log(results, status);
      }

      //nMarkerIni = marker;
      //centerMap = geocode;
      //map.panTo(geocode);
      //setMarker(marker,true);
      pesquisaAjax(geocode, marker);
    });
  } else {
    //centerMap   = {lat: -15.7875374, lng: -47.9202016};
    //map.setZoom(12);
    //map.panTo(centerMap);
    pesquisaAjax();
  }
}

function navCarousel(){
    $(".owl-nav").find(".owl-prev").html("<i class='material-icons'>arrow_left</i>");
    $(".owl-nav").find(".owl-next").html("<i class='material-icons'>arrow_right</i>");
}

function pesquisaAjax(center = centerMap, marker = nMarkerIni, data = null) {
  
  //$(".container-sidebar-home").animate({left: '0',width: '0'}); 
  $(".container-sidebar-home").hide("slide", { direction: "left" }, 1000);
  $(".container-sidebar-home").fadeOut(1000);
  //$(".container-slider .cb-slideshow").hide("slide", { direction: "right" }, 1000);
  $(".container-slider .cb-slideshow").fadeOut(2000);
  $('.divTransition').fadeIn(1000);
  $(".sidebar-left").show("slide", { direction: "left" }, 1500);
  //$(".content-maps").delay(2500).fadeIn(2000);
  $(".content-maps").fadeIn(2000);
  //$('.homeTransition').delay(2200).fadeOut("slow");
  
  //$('.container-page-busca').delay(2500).fadeIn(2000);
  $('.container-page-busca').show();
    
    
    
  if(data == null)
  {
      data = {
      pesquisa: $pesquisa,
      tipo: $tipo,
      quartos: $quartos,
      valor: $valor,
      bairro: $bairro,
      metro_quadrado: $metro_quadrado,
      tipo_busca: $tipo_busca,
      intencao: JSON.stringify(intencao)
    }
  }
  
  data['clique'] = clique;
  clique = 0;
  $.ajax({
    url: base_url + "comdono/ajax/busca_ajax/get_imoveis",
    dataType: "json",
    type: "POST",
    data: data,
    success: function(retorno) {
      imoveis = retorno.imoveis;
      countBairro = retorno.countBairro;
      countQuadra = retorno.countQuadra;
      countConjunto = retorno.countConjunto;
      countImoveis = retorno.countImoveis;

      if(center != null && marker != null)
        initMap(center, marker, true);

      $(".blocoImoveis").html("");
      $.each(countImoveis, function(id, value) {
        $(".blocoImoveis").prepend(value.blocoView);
      });
      loadImg();
      $("#partial").trigger("destroy.owl.carousel");
      loadCarousel();
        navCarousel();
      collapse = $(".collapse-icon.collapsed").length ? 0 : 1;
      
      ajusta_container_lista(collapse);
      
      //muda a aba no mobile
      if(w <= 768 && validFormBuscar){
          validFormBuscar = false;
          $(".filter-list").trigger("click");
      }

      if (retorno.imoveis.length === 0) {
        scrollHeightAuto();

        boxHtml = '<div class="box-item"><div class="row"><div class="col">';
        boxHtml += '<div class="title-erro">Ops! Imóvel não encontrado.</div>';
        boxHtml +=
          '<div class="descricao-erro">Infelizmente, ainda não temos ofertas disponíveis com os filtros selecionados. Por favor, tente novamente com outros dados.</div>';
        boxHtml += "</div></div></div>";

        $(".blocoImoveis").append(boxHtml);
      }
      
      $('.divSelectTipo').html(retorno.tiposImovel);
      
      resizeWidth();
      
      loadButton(null, false);
    },
    error: function(error) {
      loadButton(null, false);
    }
  });
}

$(".formPesquisa").submit(function(event) {
  event.preventDefault();
  event.stopPropagation();
  
  validFormBuscar = true;
  
  if(w <= 768){
      $(".autocomplete-responsive .ui-widget.ui-widget-content").removeClass("d-block");
      $(".autocomplete-responsive .ui-widget.ui-widget-content").hide();
      $(".box-caret.box-navbar-nav").css("display","none");
      $(".box-pesquisa").css('border-bottom','none');
  }
  
  //loadButton($(".btnBuscar"));
  buscar();
});

$("#formBuscar").submit(function(event) {
  event.preventDefault();
  event.stopPropagation();
  
  validFormBuscar = true;
  
  //loadButton($(".btnBuscar"));
  buscar();
  $(".collapse-icon").trigger("click");

});

$(document).on("click", ".marker", function() {
    
  clique = 1;    
  info = $(this).data("info");
  mrk = $(this).data("marker");
  console.log("click .marker", info);
  if (mrk < 4) {
      
      //mrk == 1
  
        if (mrk != 1) // NOVO TESTANDO
            setMarker(mrk - 1, true, getPosition(info.lat, info.long)); // NOVO TESTANDO
            
    hidePpImovel();
    showPpImovel(info.idImovel);
    map.panTo(getPosition(info.lat, info.long));
    if (info.lancamento == "Sim") {
        data = {
          pesquisa: $pesquisa,
          tipo: $tipo,
          quartos: $quartos,
          valor: $valor,
          bairro: $bairro,
          id_lancamento: info.idImovel
        }
        pesquisaAjax(null, null, data);
    }
    else
    {
        pesquisaAjax(null, null);
    }
    
  } else {
    
    $bairro = info.bairro;
    pesquisaAjax(null, null);
        
    setMarker(mrk - 1, true, getPosition(info.lat, info.long));
  }
});

$(document).on("click", ".closePpImovel", function() {
  hidePpImovel();
  
});

$(document).on("click", ".ppImovel", function() {
  info = $(this).data("info");
  
  link_imovel = base_url+"imovel/"+info.idImovel;
  link_lancamento = base_url+"lancamento/"+info.idImovel;
  
  //console.log(info.lancamento);
  //info.lancamento == "Sim" ? window.location.href = link_lancamento : window.location.href = link_imovel;
  info.lancamento == "Sim" ? window.open(link_lancamento, '_blank') : window.location.href = link_imovel;
  //info.lancamento == "Sim" ? window.open(link_lancamento, '_blank') : window.open(link_imovel, '_blank');
});

function setBoxImovel(imovel) {
  boxHtml  = '<div class="box-item"><div class="row"><div class="col-md-7 col-lg-7 pr-0">';
  boxHtml += '<div class="col-md-5 col-lg-5 pl-0 d-block-767">';
  boxHtml += '<a href="'+base_url+"imovel/"+imovel.idImovel+'" target="”_blank”">';
  boxHtml += '<div class="content-img box-img" style="background-image: url('+imovel.baseImg+imovel.img+');"></div>';
  boxHtml += "</a></div>";
  boxHtml += '<div class="title"><a href="'+base_url+"imovel/"+imovel.idImovel+'" target="”_blank”">'+imovel.bairro+"</a></div>";
  boxHtml += '<div class="sub-title">'+imovel.endereco+"<br/> <span>"+imovel.cidade+"-"+imovel.estado+"</span></div>";
  boxHtml += '<div class="valor">R$ '+imovel.valor+"</div>";
  boxHtml += 
  '<div class="descricao">'+
  '<div class="tipo">'+imovel.tipo_imovel+'></div>'+
  imovel.area_privativa+" m²"+(imovel.quartos >= 1 ? " <span>|</span> "+imovel.quartos+" Quarto(s)" : "")+""+(imovel.suites >= 1 ? " <span>|</span> "+imovel.suites+" Suite(s)" : "") +
  "</div>";
  boxHtml += '</div><div class="col-md-5 col-lg-5 d-none-767">';
  boxHtml += '<a href="'+base_url+"imovel/"+imovel.idImovel+'" target="”_blank”">';
  boxHtml += '<div class="content-img box-img" style="background-image: url('+imovel.baseImg+imovel.img+');"></div>';
  boxHtml += "</a></div></div></div><hr>";
  
  $(".blocoImoveis").append(boxHtml);
}

function getZoomMark(resTypesZoom) {
  res = 4;
  $.each(resTypesZoom, function(id, value) {
    if (
      $.inArray(value, [
        "administrative_area_level_2",
        "administrative_area_level_4",
        "sublocality_level_3",
        "sublocality_level_5"
      ]) >= 0
    ) {
      if (value == "administrative_area_level_2") res = 4;
      if (value == "administrative_area_level_4") res = 4;
      if (value == "sublocality_level_3") res = 3;
      if (value == "sublocality_level_5") res = 2;
    }
  });
  return res;
  //return nMarkerIni;
}

function getPosition(latid, longid) {
  return { lat: parseFloat(latid), lng: parseFloat(longid) };
}

function showMarker(i) {
  $(".marker_" + i).show();
  //$('.marker_'+i).next().show();
  //$('.marker_'+i).next().removeClass('d-none');
}

function hideMarker(i) {
  $(".marker_" + i).hide();
  //$('.marker_'+i).next().hide();
}

function hidePpImovel() {
  $(".container-detalhes").hide();
}

function showPpImovel(i) {
  $("#ppImovel_" + i).show();
}

function zoomMarker(mapZoom) {
  $.each($niveis, function(mark, zoons) {
    $.each(zoons, function(i, zoom) {
      if (mapZoom == zoom) {setMarker(mark); return 5;}
    });
  });
}

function setMarker(m, zoom = false, position = null) {
  for (i = 1; i <= countMarker; i++) {
    hideMarker(i);
  }
  showMarker(m);

  if (zoom) setZoomMark(m);

  if (position != null) map.panTo(position);

  if (m > 1) hidePpImovel();
  
  //resizeWidth()
  
}

function setZoomMark(m) {
  $.each($niveis, function(mark, zoons) {
    if (m == mark) map.setZoom(zoons[0]);
  });
}

/*

if(mapZoom <= 13)
{
   setMarker(4);
}
if(mapZoom > 13 & mapZoom <= 16)
{
    setMarker(3);
}
if(mapZoom > 16 & mapZoom <= 18)
{
    setMarker(2);
}
if(mapZoom > 18)
{
    setMarker(1);
}


if(m >= 4)
{
   map.setZoom(12);
}
if(m == 3)
{
    map.setZoom(14);
}
if(m == 2)
{
    map.setZoom(17);
}
if(m == 1)
{
    map.setZoom(19);
}*/

/** Defines the Popup class. */
function definePopupImovel() {
  /**
   * A customized popup on the map.
   * @param {!google.maps.LatLng} position
   * @param {!Element} content
   * @constructor
   * @extends {google.maps.OverlayView}
   */
  PpImovel = function(position, content) {
    this.position = position;

    content.classList.add("popup-imovel-content");

    var pixelOffset = document.createElement("div");

    pixelOffset.classList.add("popup-bubble-anchor"); //popup-imovel-anchor

    pixelOffset.appendChild(content);

    //pixelOffset.dataset.teste = "teste";

    //pixelOffset.insertAdjacentHTML('beforeend', '<div class="arrow-down d-none"></div>');

    this.anchor = document.createElement("div");
    this.anchor.classList.add("popup-tip-anchor"); //popup-imovel-tip
    this.anchor.appendChild(pixelOffset);

    this.anchor.style.cursor = "default";
  };

  PpImovel.prototype = Object.create(google.maps.OverlayView.prototype);

  /** Called when the popup is added to the map. */
  PpImovel.prototype.onAdd = function() {
    this.getPanes().floatPane.appendChild(this.anchor);
  };

  /** Called when the popup is removed from the map. */
  PpImovel.prototype.onRemove = function() {
    if (this.anchor.parentElement) {
      this.anchor.parentElement.removeChild(this.anchor);
    }
  };

  /** Called when the popup needs to draw itself. */
  PpImovel.prototype.draw = function() {
    var divPosition = this.getProjection().fromLatLngToDivPixel(this.position);
    // Hide the popup when it is far out of view.
    var display =
      Math.abs(divPosition.x) < 4000 && Math.abs(divPosition.y) < 4000 ? "block" : "none";

    if (display === "block") {
      this.anchor.style.left = divPosition.x + "px";
      this.anchor.style.top = divPosition.y + "px";
    }
    if (this.anchor.style.display !== display) {
      this.anchor.style.display = display;
    }
  };

  /** Stops clicks/drags from bubbling up to the map. */
  PpImovel.prototype.stopEventPropagation = function() {
    var anchor = this.anchor;
    anchor.style.cursor = "auto";

    [
      "click",
      "dblclick",
      "contextmenu",
      "wheel",
      "mousedown",
      "touchstart",
      "pointerdown"
    ].forEach(function(event) {
      anchor.addEventListener(event, function(e) {
        e.stopPropagation();
      });
    });
  };
}

/** Defines the Popup class. */
function definePopupClass() {
  /**
   * A customized popup on the map.
   * @param {!google.maps.LatLng} position
   * @param {!Element} content
   * @constructor
   * @extends {google.maps.OverlayView}
   */
  Popup = function(position, content) {
    this.position = position;

    content.classList.add("popup-bubble-content");

    var pixelOffset = document.createElement("div");

    pixelOffset.classList.add("popup-bubble-anchor");

    pixelOffset.appendChild(content);

    //pixelOffset.dataset.teste = "teste";

    //pixelOffset.insertAdjacentHTML('beforeend', '<div class="arrow-down d-none"></div>');

    this.anchor = document.createElement("div");
    this.anchor.classList.add("popup-tip-anchor");
    this.anchor.appendChild(pixelOffset);

    //NAO APAGAR EXEMPLOS-----------------------

    // Optionally stop clicks, etc., from bubbling up to the map.
    //this.stopEventPropagation();
    this.anchor.style.cursor = "pointer";
    //click dblclick
    /*this.anchor.addEventListener('click', function(e) {
            e.stopPropagation();
            info = $(this).find( ".marker" ).data('info');
            mrk = $(this).find( ".marker" ).data('marker');
            console.log($(this).find( ".marker" ));
            //console.log(mrk,info);
            if(mrk == 1)
            {
                alert('mostrar imovel');
            }
            else
            {
                setMarker(mrk-1,true,getPosition(info.lat,info.long));
            }
            
        });*/
    //NAO APAGAR EXEMPLOS-----------------------
  };
  // NOTE: google.maps.OverlayView is only defined once the Maps API has
  // loaded. That is why Popup is defined inside init Map().
  Popup.prototype = Object.create(google.maps.OverlayView.prototype);

  /** Called when the popup is added to the map. */
  Popup.prototype.onAdd = function() {
    this.getPanes().floatPane.appendChild(this.anchor);
  };

  /** Called when the popup is removed from the map. */
  Popup.prototype.onRemove = function() {
    if (this.anchor.parentElement) {
      this.anchor.parentElement.removeChild(this.anchor);
    }
  };

  /** Called when the popup needs to draw itself. */
  Popup.prototype.draw = function() {
    var divPosition = this.getProjection().fromLatLngToDivPixel(this.position);
    // Hide the popup when it is far out of view.
    var display =
      Math.abs(divPosition.x) < 4000 && Math.abs(divPosition.y) < 4000
        ? "block"
        : "none";

    if (display === "block") {
      this.anchor.style.left = divPosition.x + "px";
      this.anchor.style.top = divPosition.y + "px";
    }
    if (this.anchor.style.display !== display) {
      this.anchor.style.display = display;
    } 
  };

  /** Stops clicks/drags from bubbling up to the map. */
  Popup.prototype.stopEventPropagation = function() {
    var anchor = this.anchor;
    anchor.style.cursor = "auto";
 
    [
      "click",
      "dblclick",
      "contextmenu",
      "wheel",
      "mousedown",
      "touchstart",
      "pointerdown"
    ].forEach(function(event) {
      anchor.addEventListener(event, function(e) {
        e.stopPropagation();
      });
    });
  };
}