$(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);
  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');
        break;
      }
  }
}

  $(document).on('set-geolocation', function(event, coords) {
    $.getJSON(WCS_ROOT_URL + '/api/reverse-geocoding?lat=' + coords.lat + '&lon=' + coords.lng, function(data) {
      geoloc_prefill('house', data.address.house_number);
      var street = data.address.road;
      if (!street && data.address.pedestrian) {
        street = data.address.pedestrian;
      }
      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);
    });
  });
  if ($('.qommon-map').length == 0 &&
      $('div[data-geolocation]').parents('form').data('is-backoffice') != true) {
    /* 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}
      );
    }
  }
});
