(function (drupalSettings) {
  farmOS.map.behaviors.mapbox = {
    attach: function (instance) {
      var key = drupalSettings.farm_map.behaviors.mapbox.api_key;
      this.addMapboxLayer(instance, 'Mapbox Outdoors', 'mapbox/outdoors-v11', key);
      this.addMapboxLayer(instance, 'Mapbox Satellite', 'mapbox/satellite-v9', key, true);
    },
    addMapboxLayer: function (instance, title, tileset, key, visible = false) {

      // Create the MapBox watermark and attribution.
      // See https://docs.mapbox.com/help/how-mapbox-works/attribution/
      var watermark_styles = 'position: absolute; display: block !important; height: 20px; width: 65px; top: -30px; right: 10px; background-image: url(data:image/svg+xml;base64,[encoded data, 11888 characters]); background-repeat: no-repeat; background-position: 0 0; background-size: 65px 20px;';
      var watermark = '<a href="https://mapbox.com/about/maps" style="' + watermark_styles + '" target="_blank"></a>';
      var links = '<a href="https://www.mapbox.com/about/maps/">© Mapbox</a> | <a href="http://www.openstreetmap.org/copyright">© OpenStreetMap</a> | <a href="https://www.mapbox.com/map-feedback/" target="_blank"><strong>Improve this map</strong></a>';
      var attribution = watermark + links;

      // Add the layer.
      var opts = {
        title: title,
        url: 'https://api.mapbox.com/styles/v1/' + tileset + '/tiles/512/{z}/{x}/{y}?access_token=' + key,
        tileSize: 512,
        attribution: attribution,
        group: 'Base layers',
        base: true,
        visible: visible,
      };
      instance.addLayer('xyz', opts);
    }
  };
}(drupalSettings));
