if (document.getElementById("placesmap") !== null) {
  var places_base_path = "/places";
  var nominatim_base_url = 'https://nominatim.openstreetmap.org/search/';
  var nominatim_user_agent_email = "<%= Rails.env == 'test' ? 0 : Rails.application.config.user_agent_email %>";

  L.Icon.Default.imagePath = '/assets'

  var placesmap;

  if (location.pathname === places_base_path || location.pathname === '/') { //places index page
    placesmap = L.map('placesmap').setView([0.0, -0.0], 2);
    showMap(placesmap);
  }
  else { // specific place page
    var place = location.pathname.replace(places_base_path + "/", '');
    var nominatim_query_url = nominatim_base_url + place;
    var nominatim_options = {
      format: "json",
      callback: "placeholder",
      limit: 1,
      email: nominatim_user_agent_email
    };
    $.getJSON(nominatim_query_url, nominatim_options, function(data) {
      placesmap = L.map('placesmap').setView([data[0].lat, data[0].lon], 5);
      showMap(placesmap);
    })
  }
}

function showMap(placesmap) {
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    maxZoom: 18
  }).addTo(placesmap);

  var markers = new L.MarkerClusterGroup({showCoverageOnHover: false, maxClusterRadius: 20 });

  var members_url = location.pathname + '.json';

  // Icon documentation: https://leafletjs.com/reference-1.5.0.html#icon
  var default_marker_icon = L.icon({
    iconUrl: "<%=image_url('spade-marker.svg')%>",
    iconSize: [48, 48],
    iconAnchor: [24, 48],
    popupAnchor: [0, -46],
  });

  $.getJSON(members_url, function(members) {
    $.each(members, function(i, m) {
      if (m.latitude && m.longitude) {
        var marker = new L.Marker(new L.LatLng(m.latitude, m.longitude), {icon: default_marker_icon});
        var link = "<p><a href='/members/" + m.slug + "'>" + m.login_name + "</a></p>";
        var where = "<p><i>" + m.location + "</i></p>";
        marker.bindPopup(link + where).openPopup();
        markers.addLayer(marker);
      }
    });
  });

  function fetchCropsForMap(url) {
    var n = 0;
    $.getJSON(url, function(crop_data) {
      $.each(crop_data['data'], function(i, p) {
        if (p.attributes.latitude && p.attributes.longitude) {
          var crop_marker = L.icon({
            iconUrl: "/crops/" + p.attributes['crop-slug'] + '.svg',
            iconSize: [48, 48],
            iconAnchor: [24, 48],
            popupAnchor: [0, -46],
          });
          var marker = new L.Marker(new L.LatLng(p.attributes.latitude, p.attributes.longitude),
            {icon: crop_marker});
          var link = "<p><a href='/plantings/" + p.attributes.slug + "'>" + p.attributes['crop-name'] + "</a></p>";
          var where = "<p><i>" + p.attributes.location + "</i></p>";
          if (p.attributes['thumbnail']) {
            where += '<img src="' + p.attributes['thumbnail'] + '" alt="photo of planting">';
          }
          marker.bindPopup(link + where).openPopup();
          markers.addLayer(marker);
        }
      });
      // We fetch pages of 10 at a time. Stop after 200 crops; so we are showing only 'active' plantings.
      if (crop_data['links']['next'] && n++ < 20) {
        fetchCropsForMap(crop_data['links']['next'])
      }
      return crop_data;
    });
  }
  fetchCropsForMap('/api/v1/plantings.json?filter[finished]=false&sort=-planted-at');
  placesmap.addLayer(markers);
}
