$(function() {
function geoloc_prefill(element_type, element_value)
{
  $('div[data-geolocation="' + element_type +'"] input').val(element_value);
  $('div[data-geolocation="' + element_type +'"] textarea').val(element_value);
  var $options = $('div[data-geolocation="' + element_type +'"] option');
  if ($options.length == 0) return;

  var slugified_value = $.slugify(element_value);
  var prefilled = false;
  for (var i=0; i<$options.length; i++) {
      var $option = $($options[i]);
      if ($.slugify($option.val()) == slugified_value ||
          $.slugify($option.text()) == slugified_value) {
        $option.prop('selected', true);
        $option.parent().trigger('change');
        prefilled = true;
        break;
      }
  }
  if (!prefilled) {
    $($options[0]).prop('selected', true);
    $($options[0]).parent().trigger('change');
  }
}

  $(document).on('set-geolocation', function(event, coords) {
    $.getJSON(WCS_ROOT_URL + '/api/reverse-geocoding?lat=' + coords.lat + '&lon=' + coords.lng, function(data) {
      unset_sync_callback()
      geoloc_prefill('house', data.address.house_number);
      var street = data.address.road;
      if (!street && data.address.pedestrian) {
        street = data.address.pedestrian;
      } else if (!street && data.address.footway) {
        street = data.address.footway;
      } else if (!street && data.address.path) {
        street = data.address.path;
      } else if (!street && data.address.cycleway) {
        street = data.address.cycleway;
      } else if (!street && data.address.park) {
        street = data.address.park;
      }
      geoloc_prefill('road', street);
      if (street && data.address.house_number) {
        number_and_street = data.address.house_number + ' ' + street;
      } else {
        number_and_street = street;
      }
      geoloc_prefill('number-and-street', number_and_street);
      geoloc_prefill('postcode', data.address.postcode);
      geoloc_prefill('city', data.address.village || data.address.town || data.address.city || data.address.county);
      geoloc_prefill('country', data.address.country);
      $(document).trigger('wcs:set-last-auto-save');
      set_sync_callback()
    });
  });
  if ($('.qommon-map').length == 0) {
    /* if there's no map on the page, we do the geolocation without leaflet. */
    if (navigator.geolocation) {
      $('div[data-geolocation] label').addClass('activity');
      navigator.geolocation.getCurrentPosition(
        function (position) {
          $('div[data-geolocation] label').removeClass('activity');
          var coords = {lat: position.coords.latitude, lng: position.coords.longitude};
          $(document).trigger('set-geolocation', coords);
        },
        function (error_msg) {
          $('div[data-geolocation] label').removeClass('activity');
          $($('div[data-geolocation] label')[0]).after(
                          '<span class="geoloc-error">' + error_msg.message + '</span>');
        },
        {timeout: 10000, maximumAge: 300000, enableHighAccuracy: false}
      );
    }
  }

  function set_sync_callback() {
    var $map = $('.qommon-map');
    if (! $map.data('address-sync')) return;
    $('div[data-geolocation]').on('change', 'input[type=text], textarea, select', function(event) {
      var address = '';
      var found_city = false;
      $(['number-and-street', 'house', 'road', 'postcode', 'city', 'country']).each(function(idx, elem) {
        var part = $('div[data-geolocation="' + elem + '"]').find('input, textarea, select').val();
        if (part) {
          address += part + ' ';
          if (elem == 'number-and-street' || elem == 'road' || elem == 'city') {
            address += ', ';
          }
          if (elem == 'postcode' || elem == 'city') {
            found_city = true;
          }
        }
      });
      if (found_city) {
        $.getJSON(WCS_ROOT_URL + '/api/geocoding?q=' + address, function(data) {
          if (data && $(data).length > 0) {
            var coords = {lat: data[0].lat, lng: data[0].lon};
            var map = $map[0].leaflet_map;
            map.flyTo(coords);
            if (map.marker === null) {
              map.marker = L.marker([0, 0]);
              map.marker.addTo(map);
            }
            $map.trigger('set-geolocation', coords, {'trigger': false});
          }
        });
      }
    });
  }
  function unset_sync_callback() {
    $('div[data-geolocation]').off('change', 'input[type=text], textarea, select');
  }
  set_sync_callback();
});
