var map;
var popup;
var Popup;
var marker;
var geocoder;
var coordenadas;
var latid, longid, cep, ref;
var bairro_lat;
var bairro_long;
var quadra_lat;
var quadra_long;
var conjunto_lat;
var conjunto_long;
var deferredLocation = $.Deferred();

$(window).on('load',function(){
    iniLocalizacao();
});

$('body').on('click','.cancelar-localizacao',function(){
    $('.confirma_local').val('true');
    initGoogleMaps();
});


$('body').on('click','.confirmar-localizacao',function(){
   $('.confirma_local').val('true');
   
   if(document.getElementsByClassName('popup-confirmacao').length > 1)
        document.getElementsByClassName("popup-bubble-anchor-50")[0].remove();
});

function iniLocalizacao()
{
    cep = $('input[name=cep]').val();
    if(cep != undefined)
    {
        cep = cep.replace('.', '');
        endereco = $('input[name=endereco]').val();
        
        if(endereco.split(' ').length > 4)
            quadra = endereco.split(' ')[0]+' '+endereco.split(' ')[1]+' '+endereco.split(' ')[3];
        else
            quadra = endereco.split(' ')[0]+' '+endereco.split(' ')[1];
            
        bairro = $('input[name=bairro]').val();
        cidade = $('input[name=cidade]').val();
        estado = $('input[name=estado]').val();
        
        ref = endereco+', '+bairro+', '+cidade+', '+estado;
        
        setMapsConfig();
    }
        
}

function setMapsConfig()
{
    //console.log('setMapsConfig', $('input[name=latitude]').val())
    
    if($('input[name=latitude]').val().length === 0)
    {
        deferredLocation = $.Deferred();
		setCepLocation();
		deferredLocation.done(function(){
		    initGoogleMaps();
		});
    }
    else 
    {
        latid = $('input[name=latitude]').val();
        longid = $('input[name=longitude]').val();
        initGoogleMaps();
    }
}

function setCepLocation()
{
    geocoder = new google.maps.Geocoder();
    
    geocoder.geocode({ 'address': ref }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //console.log('latlong', results)
            if (results[0]) {
                latid = results[0].geometry.location.lat();
                longid = results[0].geometry.location.lng();
            }
        } else {
            latid = '-15.7875374';
            longid = '-47.9202016';
            //console.log('erro', results, status);
        }
        
        deferredLocation.resolve();
    });
    
    if($('input[name=bairro_lat]').val() == ''){
        geocoder.geocode({ 'address': bairro + ', Brasil'}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                console.log('latlong bairro', results);
                if (results[0]) {
                    bairro_lat = results[0].geometry.location.lat();
                    bairro_long = results[0].geometry.location.lng();
                    $('input[name=bairro_lat]').val(bairro_lat);
                    $('input[name=bairro_long]').val(bairro_long);
                    
                    cadastraGeocoder(bairro, bairro_lat, bairro_long);
                }
            } else {
                //console.log('erro', results, status);
                //console.log('Bairro nao encontrado',bairro);
            }
        });
    }
    
    geocoder.geocode({ 'address': quadra +', '+ bairro  + ', Brasil'}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            
            if (results[0]) {
                quadra_lat = results[0].geometry.location.lat();
                quadra_long = results[0].geometry.location.lng();
                $('input[name=quadra_lat]').val(quadra_lat);
                $('input[name=quadra_long]').val(quadra_long);
            }
        } else {
            //console.log('erro', results, status);
            //console.log('Quadra nao encontrado',quadra +', '+ bairro);
        }
    });
    geocoder.geocode({ 'address': endereco}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                conjunto_lat = results[0].geometry.location.lat();
                conjunto_long = results[0].geometry.location.lng();
                $('input[name=conjunto_lat]').val(conjunto_lat);
                $('input[name=conjunto_long]').val(conjunto_long);
            }
        } else {
            //console.log(results, status);
            //console.log('endereco nao encontrado',endereco);
        }
    });
}

function initGoogleMaps()
{
    definePopupClass();
    
    coordenadas = new google.maps.LatLng(latid, longid);
    map = new google.maps.Map(document.getElementById('map'),
    {
        center: coordenadas,
        zoom: 15,
        //mapTypeId: "satellite"
        mapTypeId: "roadmap",
        mapTypeControlOptions: {
              style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
              position: google.maps.ControlPosition.BOTTOM_CENTER
          },
    });
    
    // Place a draggable marker on the map
    marker = new google.maps.Marker({
        position: coordenadas,
        map: map,
        draggable:true,
        title:"Me arraste!"
    });
    
    marker.addListener('dragend', function(evt) {
        var lat = evt.latLng.lat();
        var long = evt.latLng.lng();
        var content = document.getElementsByClassName('popup-confirmacao')[0].cloneNode(true);
        
        $('.confirma_local').val('');
        
        position = new google.maps.LatLng(lat,long);
        
        if(document.getElementsByClassName('popup-confirmacao').length > 1)
            document.getElementsByClassName("popup-bubble-anchor-50")[0].remove();
        
        
        map.panTo(position);
        
        popup = new Popup(position,content);
        popup.setMap(map);
    }); 
    
    var input = /** @type {!HTMLInputElement} */ (
        document.getElementById('pac-input'));

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    //var autocomplete = new google.maps.places.Autocomplete(input);
    //autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();

    /*autocomplete.addListener('place_changed', function()
    {
        infowindow.close();
        marker.setVisible(false);
        var place = autocomplete.getPlace();
        if (!place.geometry)
        {
            window.alert("Nenhum local encontrado");
            return;
        }

        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport)
        {
            map.fitBounds(place.geometry.viewport);
        }
        else
        {
            map.setCenter(place.geometry.location);
            map.setZoom(17); // Why 17? Because it looks good.
        }
        
        marker.setPosition(place.geometry.location);
        marker.setVisible(true);

        var address = '';
        if (place.address_components)
        {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }

        infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
        infowindow.open(map, marker);
    });*/

    // Sets a listener on a radio button to change the filter type on Places
    // Autocomplete.
    function setupClickListener(id, types)
    {
        var radioButton = document.getElementById(id);
        radioButton.addEventListener('click', function()
        {
            //autocomplete.setTypes(types);
        });
    }
}

function resetMap()
{
    $('input[name=latitude]').val('');
    iniLocalizacao();
}

function showMap()
{
    var center = map.getCenter();
    google.maps.event.trigger(map, 'resize');         // fixes map display
    map.setCenter(center);                            // centers map correctly
}

function getLatitude()
{
    if(cep == '' || marker == undefined)
        return '';
     
    return marker.getPosition().lat();
}

function getLogitude()
{
    if(cep == '' || marker == undefined)
        return '';
    
        
    return marker.getPosition().lng();
}

function getCoordenadas()
{
    var lat = marker.getPosition().lat();
    var lng = marker.getPosition().lng();
    
    var result = [lat, lng];
    
    return result;
}

 // Sets the map on all markers in the array.
function setMapOnAll(map) 
{
    for (var i = 0; i < popups.length; i++) {
      popups[i].setMap(map);
    }
}

function clearPopups() 
{
    setMapOnAll(null);
}

function deletePopups() 
{
    clearPopups();
    popups = [];
}

/** 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-50');
        pixelOffset.appendChild(content);
        pixelOffset.insertAdjacentHTML('beforeend', '<div class="arrow-down"></div>');
    
        this.anchor = document.createElement('div');
        this.anchor.classList.add('popup-tip-anchor');
        this.anchor.appendChild(pixelOffset);
        
        this.anchor.style.cursor = "pointer";
        
        // Optionally stop clicks, etc., from bubbling up to the map.
        //this.stopEventPropagation();
      
  };
  // NOTE: google.maps.OverlayView is only defined once the Maps API has
  // loaded. That is why Popup is defined inside initMap().
  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();
          });
        });
  };
}