// Generated by CoffeeScript 1.12.7
var MapDetailPlugin,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

MapDetailPlugin = (function(superClass) {
  extend(MapDetailPlugin, superClass);

  function MapDetailPlugin() {
    this.__addMarker = bind(this.__addMarker, this);
    return MapDetailPlugin.__super__.constructor.apply(this, arguments);
  }

  MapDetailPlugin.bigIconSize = 320;

  MapDetailPlugin.smallIconSize = 64;

  MapDetailPlugin.mapboxTilesetStreets = {
    name: "mapbox/streets-v11",
    maxZoom: 18
  };

  MapDetailPlugin.mapboxTilesetStreetsEnglish = {
    name: "mapbox/outdoors-v11",
    maxZoom: 18
  };

  MapDetailPlugin.mapboxTilesetSatellite = {
    name: "mapbox/satellite-v9",
    maxZoom: 12
  };

  MapDetailPlugin.prototype.getButtonLocaKey = function() {
    return "map.detail.plugin.button";
  };

  MapDetailPlugin.prototype.prefName = function() {
    return "detail_sidebar_show_map";
  };

  MapDetailPlugin.prototype.isAvailable = function() {
    return MapDetailPlugin.getConfiguration().enabled && this.__areMarkersAvailable();
  };

  MapDetailPlugin.prototype.isDisabled = function() {
    var assetMarkerOptions, isPluginSupportedByOtherFields;
    assetMarkerOptions = this.__getAssetMarkerOptions();
    isPluginSupportedByOtherFields = this._detailSidebar.object.isPluginSupported(this, "detail");
    return assetMarkerOptions.length === 0 && !isPluginSupportedByOtherFields;
  };

  MapDetailPlugin.prototype.hideDetail = function() {
    return this._detailSidebar.mainPane.empty("top");
  };

  MapDetailPlugin.prototype.renderObject = function() {
    var markerOptions;
    if (this.__map) {
      this.resetMap();
    }
    markerOptions = this.__getAssetMarkerOptions();
    this.__menuButton = this.__getMenuButton();
    this.__buttonsUpperRight = this.__menuButton ? [this.__menuButton] : [];
    this.__map = this.__buildMap(markerOptions);
    CUI.Events.listen({
      type: "map-detail-center",
      node: this._detailSidebar.container,
      instance: this,
      call: (function(_this) {
        return function(_, position) {
          if (CUI.Map.isValidPosition(position)) {
            if (!_this.getButton().isActive()) {
              _this.getButton().activate();
            }
            if (_this.__isMapReady) {
              return _this.__map.setCenter(position, CUI.Map.defaults.maxZoom);
            } else {
              return _this.__initCenter = position;
            }
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "end-fill-screen",
      node: this.__map,
      instance: this,
      call: (function(_this) {
        return function() {
          return _this.__onCloseFullscreen();
        };
      })(this)
    });
  };

  MapDetailPlugin.prototype.showDetail = function() {
    if (!this.__map) {
      return;
    }
    return this._detailSidebar.mainPane.replace(this.__map, "top");
  };

  MapDetailPlugin.prototype.__buildMap = function(markersOptions) {
    return new CUI.LeafletMap({
      "class": "ez5-detail-map-plugin",
      clickable: false,
      markersOptions: markersOptions,
      zoomToFitAllMarkersOnInit: true,
      buttonsUpperRight: this.__buttonsUpperRight,
      onClick: (function(_this) {
        return function() {
          if (_this.__markerSelected) {
            return _this.__setIconToMarker(_this.__markerSelected, MapDetailPlugin.smallIconSize);
          }
        };
      })(this),
      onReady: (function(_this) {
        return function() {
          _this.__isMapReady = true;
          if (_this.__initCenter) {
            _this.__map.setCenter(_this.__initCenter, CUI.Map.defaults.maxZoom);
            return delete _this.__initCenter;
          }
        };
      })(this)
    });
  };

  MapDetailPlugin.prototype.__getAssetMarkerOptions = function() {
    var asset, assetMarkerOptions, assets, gps_location, i, len, ref;
    assets = this._detailSidebar.object.getAssetsForBrowser("detail");
    assetMarkerOptions = [];
    for (i = 0, len = assets.length; i < len; i++) {
      asset = assets[i];
      if (!this.__isAssetEnabledByCustomSetting(asset)) {
        continue;
      }
      if (CUI.util.isEmpty(asset.value.versions)) {
        continue;
      }
      gps_location = (ref = asset.value.technical_metadata) != null ? ref.gps_location : void 0;
      if (gps_location && gps_location.latitude && gps_location.longitude) {
        (function(_this) {
          return (function(asset) {
            var options;
            options = {
              position: {
                lat: gps_location.latitude,
                lng: gps_location.longitude
              },
              cui_onClick: function(event) {
                var marker;
                marker = event.target;
                return _this.__assetMarkerOnClick(marker);
              },
              cui_onDoubleClick: function(event) {
                var marker;
                marker = event.target;
                return _this.__map.setCenter(marker.getLatLng(), CUI.Map.defaults.maxZoom);
              }
            };
            if (asset.value.versions.small && asset.value.versions.small.width > 0 && asset.value.versions.small.height > 0) {
              options.icon = _this.__getDivIcon(asset.value.versions.small, MapDetailPlugin.smallIconSize);
              options.asset = asset;
            }
            return assetMarkerOptions.push(options);
          });
        })(this)(asset);
      }
    }
    return assetMarkerOptions;
  };

  MapDetailPlugin.prototype.__addMarker = function(data) {
    var location;
    if (!MapDetailPlugin.getConfiguration().enabled) {
      return;
    }
    location = {
      position: data.position,
      iconColor: data.iconColor,
      iconName: data.iconName,
      group: data.group,
      cui_onClick: (function(_this) {
        return function(event) {
          var marker, markerIcon;
          marker = event.target;
          markerIcon = event.originalEvent.target;
          return _this.__customLocationMarkerOnClick(marker, markerIcon, data);
        };
      })(this),
      cui_onDoubleClick: (function(_this) {
        return function(event) {
          var marker;
          marker = event.target;
          return _this.__map.setCenter(marker.getLatLng(), CUI.Map.defaults.maxZoom);
        };
      })(this)
    };
    this.__map.addMarker(location);
  };

  MapDetailPlugin.prototype.__getMenuButton = function() {
    if (MapDetailPlugin.getConfiguration().tiles === "Mapbox") {
      return new LocaButton({
        loca_key: "map.detail.plugin.menu.button",
        icon_right: false,
        group: "upper-right",
        menu: {
          items: this.__getMenuItems()
        }
      });
    }
  };

  MapDetailPlugin.prototype.__getMenuItems = function() {
    var currentTilesetName;
    currentTilesetName = ez5.session.getPref("mapboxTilesetOptions").name;
    return [
      new LocaLabel({
        loca_key: "map.detail.plugin.menu.language.label"
      }), {
        text: $$("map.detail.plugin.menu.language.english.label"),
        active: currentTilesetName === MapDetailPlugin.mapboxTilesetStreetsEnglish.name,
        disabled: currentTilesetName === MapDetailPlugin.mapboxTilesetSatellite.name,
        onClick: (function(_this) {
          return function() {
            ez5.session.savePref("mapboxTilesetOptions", MapDetailPlugin.mapboxTilesetStreetsEnglish);
            return _this.__reload();
          };
        })(this)
      }, {
        text: $$("map.detail.plugin.menu.language.local.label"),
        active: currentTilesetName === MapDetailPlugin.mapboxTilesetStreets.name || currentTilesetName === MapDetailPlugin.mapboxTilesetSatellite.name,
        onClick: (function(_this) {
          return function() {
            if (currentTilesetName !== MapDetailPlugin.mapboxTilesetSatellite.name) {
              ez5.session.savePref("mapboxTilesetOptions", MapDetailPlugin.mapboxTilesetStreets);
              return _this.__reload();
            }
          };
        })(this)
      }, new LocaLabel({
        loca_key: "map.detail.plugin.menu.tileset.label"
      }), {
        text: $$("map.detail.plugin.menu.tileset.street.label"),
        active: currentTilesetName === MapDetailPlugin.mapboxTilesetStreets.name || currentTilesetName === MapDetailPlugin.mapboxTilesetStreetsEnglish.name,
        onClick: (function(_this) {
          return function() {
            ez5.session.savePref("mapboxTilesetOptions", MapDetailPlugin.mapboxTilesetStreets);
            return _this.__reload();
          };
        })(this)
      }, {
        text: $$("map.detail.plugin.menu.tileset.satellite.label"),
        active: currentTilesetName === MapDetailPlugin.mapboxTilesetSatellite.name,
        onClick: (function(_this) {
          return function() {
            ez5.session.savePref("mapboxTilesetOptions", MapDetailPlugin.mapboxTilesetSatellite);
            return _this.__reload();
          };
        })(this)
      }
    ];
  };

  MapDetailPlugin.prototype.__areMarkersAvailable = function() {
    var assets, isAvailableByAssets, isPluginSupportedByOtherFields;
    assets = this._detailSidebar.object.getAssetsForBrowser("detail");
    isPluginSupportedByOtherFields = this._detailSidebar.object.isPluginSupported(this, "detail");
    isAvailableByAssets = assets && assets.length > 0 && this.__existsAtLeastOneAssetEnabledByCustomSettings(assets);
    return isAvailableByAssets || isPluginSupportedByOtherFields;
  };

  MapDetailPlugin.prototype.__existsAtLeastOneAssetEnabledByCustomSettings = function(assets) {
    var asset, i, len;
    for (i = 0, len = assets.length; i < len; i++) {
      asset = assets[i];
      if (this.__isAssetEnabledByCustomSetting(asset)) {
        return true;
      }
    }
    return false;
  };

  MapDetailPlugin.prototype.__isAssetEnabledByCustomSetting = function(asset) {
    var ref, ref1, showInMapSetting;
    showInMapSetting = (ref = asset.getField().FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1.show_in_map : void 0 : void 0;
    return CUI.util.isNull(showInMapSetting) || showInMapSetting;
  };

  MapDetailPlugin.prototype.__getDivIcon = function(image, size) {
    var divIcon, height, iconAnchorOffsetX, iconHeight, iconWidth, imageUrl, padding, pointerHeight, ref, width;
    ref = ez5.fitRectangle(image.width, image.height, size, size), width = ref[0], height = ref[1];
    padding = 3;
    pointerHeight = 7;
    iconWidth = width + 2 * padding;
    iconHeight = Math.round(height + 2 * padding + pointerHeight);
    iconAnchorOffsetX = Math.floor(iconWidth / 2);
    imageUrl = Session.addToken(image.url);
    divIcon = L.divIcon({
      html: "<div class=\"ez5-map-marker\">\n									<img class=\"ez5-map-marker-image\" src=\"" + imageUrl + "\" style=\"width: " + width + "px; height: " + height + "px\">\n		<div class=\"ez5-map-marker-pointer\"></div>\n</div>",
      className: "ez5-leaflet-div-icon",
      iconAnchor: [iconAnchorOffsetX, iconHeight],
      iconSize: [iconWidth, iconHeight]
    });
    return divIcon;
  };

  MapDetailPlugin.prototype.__assetMarkerOnClick = function(marker) {
    var ref;
    if (!((ref = marker.options.asset) != null ? ref.value : void 0)) {
      return;
    }
    if (this.__isFullscreen()) {
      if (this.__markerSelected) {
        this.__setIconToMarker(this.__markerSelected, MapDetailPlugin.smallIconSize);
        if (this.__markerSelected === marker) {
          this.__markerSelected = null;
          return;
        }
      }
      this.__setIconToMarker(marker, MapDetailPlugin.bigIconSize);
      return this.__markerSelected = marker;
    } else {
      return CUI.Events.trigger({
        node: this._detailSidebar.container,
        type: "asset-browser-show-asset",
        info: {
          value: marker.options.asset.value
        }
      });
    }
  };

  MapDetailPlugin.prototype.__customLocationMarkerOnClick = function(marker, markerIcon, data) {
    var eventType, info;
    info = {
      data: data
    };
    if (this.__isFullscreen()) {
      eventType = "map-detail-fullscreen-click-location";
      info.icon = markerIcon;
    } else {
      eventType = "map-detail-click-location";
    }
    return CUI.Events.trigger({
      node: this._detailSidebar.container,
      type: eventType,
      info: info
    });
  };

  MapDetailPlugin.prototype.__onCloseFullscreen = function() {
    if (this.__markerSelected) {
      this.__setIconToMarker(this.__markerSelected, MapDetailPlugin.smallIconSize);
    }
    return this.showDetail();
  };

  MapDetailPlugin.prototype.__setIconToMarker = function(marker, size) {
    var assetValue, icon, imageVersion, versionName;
    assetValue = marker.options.asset.value;
    versionName = Asset.getStandardVersionName(assetValue);
    imageVersion = assetValue.versions[versionName];
    icon = this.__getDivIcon(imageVersion, size);
    return marker.setIcon(icon);
  };

  MapDetailPlugin.prototype.__reload = function() {
    MapDetailPlugin.initMapbox();
    this.renderObject();
    return this.showDetail();
  };

  MapDetailPlugin.prototype.__isFullscreen = function() {
    return this.__map.getFillScreenState();
  };

  MapDetailPlugin.prototype.addMarker = function(data) {
    var _data, i, len, results;
    if (CUI.isArray(data)) {
      results = [];
      for (i = 0, len = data.length; i < len; i++) {
        _data = data[i];
        if (_data) {
          results.push(this.__addMarker(_data));
        } else {
          results.push(void 0);
        }
      }
      return results;
    } else {
      return this.__addMarker(data);
    }
  };

  MapDetailPlugin.prototype.resetMap = function() {
    var ref, ref1;
    if ((ref = this.__map) != null) {
      ref.destroy();
    }
    delete this.__map;
    delete this.__isMapReady;
    if ((ref1 = this.__menuButton) != null) {
      ref1.destroy();
    }
    delete this.__menuButton;
    delete this.__markerSelected;
    delete this.__buttonsUpperRight;
    delete this.__initCenter;
    CUI.Events.ignore({
      instance: this
    });
  };

  MapDetailPlugin.prototype.destroy = function() {
    this.resetMap();
    return MapDetailPlugin.__super__.destroy.call(this);
  };

  MapDetailPlugin.getConfiguration = function() {
    var baseConfig;
    baseConfig = ez5.session.getBaseConfig("plugin", "easydb-detail-map-plugin");
    baseConfig = baseConfig.system || baseConfig;
    return baseConfig["detail_map"] || {};
  };

  MapDetailPlugin.initMapbox = function() {
    var mapboxAttribution, mapboxTileset;
    mapboxAttribution = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>';
    mapboxTileset = ez5.session.getPref("mapboxTilesetOptions") || MapDetailPlugin.mapboxTilesetStreets;
    CUI.Map.defaults.maxZoom = mapboxTileset.maxZoom;
    CUI.LeafletMap.defaults.tileLayerOptions.attribution = mapboxAttribution;
    CUI.LeafletMap.defaults.tileLayerOptions.id = mapboxTileset.name;
    CUI.LeafletMap.defaults.tileLayerOptions.accessToken = MapDetailPlugin.getConfiguration().mapboxToken;
    CUI.LeafletMap.defaults.tileLayerOptions.tileSize = 512;
    CUI.LeafletMap.defaults.tileLayerOptions.zoomOffset = -1;
    return CUI.LeafletMap.defaults.tileLayerUrl = 'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}';
  };

  return MapDetailPlugin;

})(DetailSidebarPlugin);

ez5.session_ready(function() {
  DetailSidebar.plugins.registerPlugin(MapDetailPlugin);
  if (MapDetailPlugin.getConfiguration().tiles === "Mapbox") {
    ez5.session.addCookieOnlyPref("mapboxTilesetOptions", MapDetailPlugin.mapboxTilesetStreets);
    return MapDetailPlugin.initMapbox();
  }
});

CUI.ready(function() {
  CUI.Events.registerEvent({
    type: "map-detail-center",
    sink: true
  });
  CUI.Events.registerEvent({
    type: "map-detail-click-location",
    sink: true
  });
  return CUI.Events.registerEvent({
    type: "map-detail-fullscreen-click-location",
    sink: true
  });
});
