/*
 Leaflet.markercluster, Provides Beautiful Animated Marker Clustering functionality for Leaflet, a JS library for interactive maps.
 https://github.com/Leaflet/Leaflet.markercluster
 (c) 2012-2013, Dave Leaver, smartrak
*/
(function (window, document, undefined) {/*
 * L.MarkerClusterGroup extends L.FeatureGroup by clustering the markers contained within
 */

L.MarkerClusterGroup = L.FeatureGroup.extend({

  options: {
    maxClusterRadius: 80, //A cluster will cover at most this many pixels from its center
    iconCreateFunction: null,

    spiderfyOnMaxZoom: true,
    showCoverageOnHover: true,
    zoomToBoundsOnClick: true,
    singleMarkerMode: false,

    disableClusteringAtZoom: null,

    // Setting this to false prevents the removal of any clusters outside of the viewpoint, which
    // is the default behaviour for performance reasons.
    removeOutsideVisibleBounds: true,

    //Whether to animate adding markers after adding the MarkerClusterGroup to the map
    // If you are adding individual markers set to true, if adding bulk markers leave false for massive performance gains.
    animateAddingMarkers: false,

    //Increase to increase the distance away that spiderfied markers appear from the center
    spiderfyDistanceMultiplier: 1,

    // When bulk adding layers, adds markers in chunks. Means addLayers may not add all the layers in the call, others will be loaded during setTimeouts
    chunkedLoading: false,
    chunkInterval: 200, // process markers for a maximum of ~ n milliseconds (then trigger the chunkProgress callback)
    chunkDelay: 50, // at the end of each interval, give n milliseconds back to system/browser
    chunkProgress: null, // progress callback: function(processed, total, elapsed) (e.g. for a progress indicator)

    //Options to pass to the L.Polygon constructor
    polygonOptions: {}
  },

  initialize: function (options) {
    L.Util.setOptions(this, options);
    if (!this.options.iconCreateFunction) {
      this.options.iconCreateFunction = this._defaultIconCreateFunction;
    }

    this._featureGroup = L.featureGroup();
    this._featureGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);

    this._nonPointGroup = L.featureGroup();
    this._nonPointGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);

    this._inZoomAnimation = 0;
    this._needsClustering = [];
    this._needsRemoving = []; //Markers removed while we aren't on the map need to be kept track of
    //The bounds of the currently shown area (from _getExpandedVisibleBounds) Updated on zoom/move
    this._currentShownBounds = null;

    this._queue = [];
  },

  addLayer: function (layer) {

    if (layer instanceof L.LayerGroup) {
      var array = [];
      for (var i in layer._layers) {
        array.push(layer._layers[i]);
      }
      return this.addLayers(array);
    }

    //Don't cluster non point data
    if (!layer.getLatLng) {
      this._nonPointGroup.addLayer(layer);
      return this;
    }

    if (!this._map) {
      this._needsClustering.push(layer);
      return this;
    }

    if (this.hasLayer(layer)) {
      return this;
    }

    //If we have already clustered we'll need to add this one to a cluster

    if (this._unspiderfy) {
      this._unspiderfy();
    }

    this._addLayer(layer, this._maxZoom);

    //Work out what is visible
    var visibleLayer = layer,
      currentZoom = this._map.getZoom();
    if (layer.__parent) {
      while (visibleLayer.__parent._zoom >= currentZoom) {
        visibleLayer = visibleLayer.__parent;
      }
    }

    if (this._currentShownBounds.contains(visibleLayer.getLatLng())) {
      if (this.options.animateAddingMarkers) {
        this._animationAddLayer(layer, visibleLayer);
      } else {
        this._animationAddLayerNonAnimated(layer, visibleLayer);
      }
    }
    return this;
  },

  removeLayer: function (layer) {

    if (layer instanceof L.LayerGroup)
    {
      var array = [];
      for (var i in layer._layers) {
        array.push(layer._layers[i]);
      }
      return this.removeLayers(array);
    }

    //Non point layers
    if (!layer.getLatLng) {
      this._nonPointGroup.removeLayer(layer);
      return this;
    }

    if (!this._map) {
      if (!this._arraySplice(this._needsClustering, layer) && this.hasLayer(layer)) {
        this._needsRemoving.push(layer);
      }
      return this;
    }

    if (!layer.__parent) {
      return this;
    }

    if (this._unspiderfy) {
      this._unspiderfy();
      this._unspiderfyLayer(layer);
    }

    //Remove the marker from clusters
    this._removeLayer(layer, true);

    if (this._featureGroup.hasLayer(layer)) {
      this._featureGroup.removeLayer(layer);
      if (layer.setOpacity) {
        layer.setOpacity(1);
      }
    }

    return this;
  },

  //Takes an array of markers and adds them in bulk
  addLayers: function (layersArray) {
    var fg = this._featureGroup,
      npg = this._nonPointGroup,
      chunked = this.options.chunkedLoading,
      chunkInterval = this.options.chunkInterval,
      chunkProgress = this.options.chunkProgress,
      newMarkers, i, l, m;

    if (this._map) {
      var offset = 0,
        started = (new Date()).getTime();
      var process = L.bind(function () {
        var start = (new Date()).getTime();
        for (; offset < layersArray.length; offset++) {
          if (chunked && offset % 200 === 0) {
            // every couple hundred markers, instrument the time elapsed since processing started:
            var elapsed = (new Date()).getTime() - start;
            if (elapsed > chunkInterval) {
              break; // been working too hard, time to take a break :-)
            }
          }

          m = layersArray[offset];

          //Not point data, can't be clustered
          if (!m.getLatLng) {
            npg.addLayer(m);
            continue;
          }

          if (this.hasLayer(m)) {
            continue;
          }

          this._addLayer(m, this._maxZoom);

          //If we just made a cluster of size 2 then we need to remove the other marker from the map (if it is) or we never will
          if (m.__parent) {
            if (m.__parent.getChildCount() === 2) {
              var markers = m.__parent.getAllChildMarkers(),
                otherMarker = markers[0] === m ? markers[1] : markers[0];
              fg.removeLayer(otherMarker);
            }
          }
        }

        if (chunkProgress) {
          // report progress and time elapsed:
          chunkProgress(offset, layersArray.length, (new Date()).getTime() - started);
        }

        if (offset === layersArray.length) {
          //Update the icons of all those visible clusters that were affected
          this._featureGroup.eachLayer(function (c) {
            if (c instanceof L.MarkerCluster && c._iconNeedsUpdate) {
              c._updateIcon();
            }
          });

          this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
        } else {
          setTimeout(process, this.options.chunkDelay);
        }
      }, this);

      process();
    } else {
      newMarkers = [];
      for (i = 0, l = layersArray.length; i < l; i++) {
        m = layersArray[i];

        //Not point data, can't be clustered
        if (!m.getLatLng) {
          npg.addLayer(m);
          continue;
        }

        if (this.hasLayer(m)) {
          continue;
        }

        newMarkers.push(m);
      }
      this._needsClustering = this._needsClustering.concat(newMarkers);
    }
    return this;
  },

  //Takes an array of markers and removes them in bulk
  removeLayers: function (layersArray) {
    var i, l, m,
      fg = this._featureGroup,
      npg = this._nonPointGroup;

    if (!this._map) {
      for (i = 0, l = layersArray.length; i < l; i++) {
        m = layersArray[i];
        this._arraySplice(this._needsClustering, m);
        npg.removeLayer(m);
      }
      return this;
    }

    for (i = 0, l = layersArray.length; i < l; i++) {
      m = layersArray[i];

      if (!m.__parent) {
        npg.removeLayer(m);
        continue;
      }

      this._removeLayer(m, true, true);

      if (fg.hasLayer(m)) {
        fg.removeLayer(m);
        if (m.setOpacity) {
          m.setOpacity(1);
        }
      }
    }

    //Fix up the clusters and markers on the map
    this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);

    fg.eachLayer(function (c) {
      if (c instanceof L.MarkerCluster) {
        c._updateIcon();
      }
    });

    return this;
  },

  //Removes all layers from the MarkerClusterGroup
  clearLayers: function () {
    //Need our own special implementation as the LayerGroup one doesn't work for us

    //If we aren't on the map (yet), blow away the markers we know of
    if (!this._map) {
      this._needsClustering = [];
      delete this._gridClusters;
      delete this._gridUnclustered;
    }

    if (this._noanimationUnspiderfy) {
      this._noanimationUnspiderfy();
    }

    //Remove all the visible layers
    this._featureGroup.clearLayers();
    this._nonPointGroup.clearLayers();

    this.eachLayer(function (marker) {
      delete marker.__parent;
    });

    if (this._map) {
      //Reset _topClusterLevel and the DistanceGrids
      this._generateInitialClusters();
    }

    return this;
  },

  //Override FeatureGroup.getBounds as it doesn't work
  getBounds: function () {
    var bounds = new L.LatLngBounds();

    if (this._topClusterLevel) {
      bounds.extend(this._topClusterLevel._bounds);
    }

    for (var i = this._needsClustering.length - 1; i >= 0; i--) {
      bounds.extend(this._needsClustering[i].getLatLng());
    }

    bounds.extend(this._nonPointGroup.getBounds());

    return bounds;
  },

  //Overrides LayerGroup.eachLayer
  eachLayer: function (method, context) {
    var markers = this._needsClustering.slice(),
      i;

    if (this._topClusterLevel) {
      this._topClusterLevel.getAllChildMarkers(markers);
    }

    for (i = markers.length - 1; i >= 0; i--) {
      method.call(context, markers[i]);
    }

    this._nonPointGroup.eachLayer(method, context);
  },

  //Overrides LayerGroup.getLayers
  getLayers: function () {
    var layers = [];
    this.eachLayer(function (l) {
      layers.push(l);
    });
    return layers;
  },

  //Overrides LayerGroup.getLayer, WARNING: Really bad performance
  getLayer: function (id) {
    var result = null;

    this.eachLayer(function (l) {
      if (L.stamp(l) === id) {
        result = l;
      }
    });

    return result;
  },

  //Returns true if the given layer is in this MarkerClusterGroup
  hasLayer: function (layer) {
    if (!layer) {
      return false;
    }

    var i, anArray = this._needsClustering;

    for (i = anArray.length - 1; i >= 0; i--) {
      if (anArray[i] === layer) {
        return true;
      }
    }

    anArray = this._needsRemoving;
    for (i = anArray.length - 1; i >= 0; i--) {
      if (anArray[i] === layer) {
        return false;
      }
    }

    return !!(layer.__parent && layer.__parent._group === this) || this._nonPointGroup.hasLayer(layer);
  },

  //Zoom down to show the given layer (spiderfying if necessary) then calls the callback
  zoomToShowLayer: function (layer, callback) {

    var showMarker = function () {
      if ((layer._icon || layer.__parent._icon) && !this._inZoomAnimation) {
        this._map.off('moveend', showMarker, this);
        this.off('animationend', showMarker, this);

        if (layer._icon) {
          callback();
        } else if (layer.__parent._icon) {
          var afterSpiderfy = function () {
            this.off('spiderfied', afterSpiderfy, this);
            callback();
          };

          this.on('spiderfied', afterSpiderfy, this);
          layer.__parent.spiderfy();
        }
      }
    };

    if (layer._icon && this._map.getBounds().contains(layer.getLatLng())) {
      //Layer is visible ond on screen, immediate return
      callback();
    } else if (layer.__parent._zoom < this._map.getZoom()) {
      //Layer should be visible at this zoom level. It must not be on screen so just pan over to it
      this._map.on('moveend', showMarker, this);
      this._map.panTo(layer.getLatLng());
    } else {
      var moveStart = function () {
        this._map.off('movestart', moveStart, this);
        moveStart = null;
      };

      this._map.on('movestart', moveStart, this);
      this._map.on('moveend', showMarker, this);
      this.on('animationend', showMarker, this);
      layer.__parent.zoomToBounds();

      if (moveStart) {
        //Never started moving, must already be there, probably need clustering however
        showMarker.call(this);
      }
    }
  },

  //Overrides FeatureGroup.onAdd
  onAdd: function (map) {
    this._map = map;
    var i, l, layer;

    if (!isFinite(this._map.getMaxZoom())) {
      throw "Map has no maxZoom specified";
    }

    this._featureGroup.onAdd(map);
    this._nonPointGroup.onAdd(map);

    if (!this._gridClusters) {
      this._generateInitialClusters();
    }

    for (i = 0, l = this._needsRemoving.length; i < l; i++) {
      layer = this._needsRemoving[i];
      this._removeLayer(layer, true);
    }
    this._needsRemoving = [];

    //Remember the current zoom level and bounds
    this._zoom = this._map.getZoom();
    this._currentShownBounds = this._getExpandedVisibleBounds();

    this._map.on('zoomend', this._zoomEnd, this);
    this._map.on('moveend', this._moveEnd, this);

    if (this._spiderfierOnAdd) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
      this._spiderfierOnAdd();
    }

    this._bindEvents();

    //Actually add our markers to the map:
    l = this._needsClustering;
    this._needsClustering = [];
    this.addLayers(l);
  },

  //Overrides FeatureGroup.onRemove
  onRemove: function (map) {
    map.off('zoomend', this._zoomEnd, this);
    map.off('moveend', this._moveEnd, this);

    this._unbindEvents();

    //In case we are in a cluster animation
    this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');

    if (this._spiderfierOnRemove) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
      this._spiderfierOnRemove();
    }

    //Clean up all the layers we added to the map
    this._hideCoverage();
    this._featureGroup.onRemove(map);
    this._nonPointGroup.onRemove(map);

    this._featureGroup.clearLayers();

    this._map = null;
  },

  getVisibleParent: function (marker) {
    var vMarker = marker;
    while (vMarker && !vMarker._icon) {
      vMarker = vMarker.__parent;
    }
    return vMarker || null;
  },

  //Remove the given object from the given array
  _arraySplice: function (anArray, obj) {
    for (var i = anArray.length - 1; i >= 0; i--) {
      if (anArray[i] === obj) {
        anArray.splice(i, 1);
        return true;
      }
    }
  },

  //Internal function for removing a marker from everything.
  //dontUpdateMap: set to true if you will handle updating the map manually (for bulk functions)
  _removeLayer: function (marker, removeFromDistanceGrid, dontUpdateMap) {
    var gridClusters = this._gridClusters,
      gridUnclustered = this._gridUnclustered,
      fg = this._featureGroup,
      map = this._map;

    //Remove the marker from distance clusters it might be in
    if (removeFromDistanceGrid) {
      for (var z = this._maxZoom; z >= 0; z--) {
        if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) {
          break;
        }
      }
    }

    //Work our way up the clusters removing them as we go if required
    var cluster = marker.__parent,
      markers = cluster._markers,
      otherMarker;

    //Remove the marker from the immediate parents marker list
    this._arraySplice(markers, marker);

    while (cluster) {
      cluster._childCount--;

      if (cluster._zoom < 0) {
        //Top level, do nothing
        break;
      } else if (removeFromDistanceGrid && cluster._childCount <= 1) { //Cluster no longer required
        //We need to push the other marker up to the parent
        otherMarker = cluster._markers[0] === marker ? cluster._markers[1] : cluster._markers[0];

        //Update distance grid
        gridClusters[cluster._zoom].removeObject(cluster, map.project(cluster._cLatLng, cluster._zoom));
        gridUnclustered[cluster._zoom].addObject(otherMarker, map.project(otherMarker.getLatLng(), cluster._zoom));

        //Move otherMarker up to parent
        this._arraySplice(cluster.__parent._childClusters, cluster);
        cluster.__parent._markers.push(otherMarker);
        otherMarker.__parent = cluster.__parent;

        if (cluster._icon) {
          //Cluster is currently on the map, need to put the marker on the map instead
          fg.removeLayer(cluster);
          if (!dontUpdateMap) {
            fg.addLayer(otherMarker);
          }
        }
      } else {
        cluster._recalculateBounds();
        if (!dontUpdateMap || !cluster._icon) {
          cluster._updateIcon();
        }
      }

      cluster = cluster.__parent;
    }

    delete marker.__parent;
  },

  _isOrIsParent: function (el, oel) {
    while (oel) {
      if (el === oel) {
        return true;
      }
      oel = oel.parentNode;
    }
    return false;
  },

  _propagateEvent: function (e) {
    if (e.layer instanceof L.MarkerCluster) {
      //Prevent multiple clustermouseover/off events if the icon is made up of stacked divs (Doesn't work in ie <= 8, no relatedTarget)
      if (e.originalEvent && this._isOrIsParent(e.layer._icon, e.originalEvent.relatedTarget)) {
        return;
      }
      e.type = 'cluster' + e.type;
    }

    this.fire(e.type, e);
  },

  //Default functionality
  _defaultIconCreateFunction: function (cluster) {
    var childCount = cluster.getChildCount();

    var c = ' marker-cluster-';
    if (childCount < 10) {
      c += 'small';
    } else if (childCount < 100) {
      c += 'medium';
    } else {
      c += 'large';
    }

    return new L.DivIcon({ html: '
' + childCount + '
', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
  },

  _bindEvents: function () {
    var map = this._map,
        spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
        showCoverageOnHover = this.options.showCoverageOnHover,
        zoomToBoundsOnClick = this.options.zoomToBoundsOnClick;

    //Zoom on cluster click or spiderfy if we are at the lowest level
    if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
      this.on('clusterclick', this._zoomOrSpiderfy, this);
    }

    //Show convex hull (boundary) polygon on mouse over
    if (showCoverageOnHover) {
      this.on('clustermouseover', this._showCoverage, this);
      this.on('clustermouseout', this._hideCoverage, this);
      map.on('zoomend', this._hideCoverage, this);
    }
  },

  _zoomOrSpiderfy: function (e) {
    var map = this._map;
    if (map.getMaxZoom() === map.getZoom()) {
      if (this.options.spiderfyOnMaxZoom) {
        e.layer.spiderfy();
      }
    } else if (this.options.zoomToBoundsOnClick) {
      e.layer.zoomToBounds();
    }

    // Focus the map again for keyboard users.
    if (e.originalEvent && e.originalEvent.keyCode === 13) {
      map._container.focus();
    }
  },

  _showCoverage: function (e) {
    var map = this._map;
    if (this._inZoomAnimation) {
      return;
    }
    if (this._shownPolygon) {
      map.removeLayer(this._shownPolygon);
    }
    if (e.layer.getChildCount() > 2 && e.layer !== this._spiderfied) {
      this._shownPolygon = new L.Polygon(e.layer.getConvexHull(), this.options.polygonOptions);
      map.addLayer(this._shownPolygon);
    }
  },

  _hideCoverage: function () {
    if (this._shownPolygon) {
      this._map.removeLayer(this._shownPolygon);
      this._shownPolygon = null;
    }
  },

  _unbindEvents: function () {
    var spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
      showCoverageOnHover = this.options.showCoverageOnHover,
      zoomToBoundsOnClick = this.options.zoomToBoundsOnClick,
      map = this._map;

    if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
      this.off('clusterclick', this._zoomOrSpiderfy, this);
    }
    if (showCoverageOnHover) {
      this.off('clustermouseover', this._showCoverage, this);
      this.off('clustermouseout', this._hideCoverage, this);
      map.off('zoomend', this._hideCoverage, this);
    }
  },

  _zoomEnd: function () {
    if (!this._map) { //May have been removed from the map by a zoomEnd handler
      return;
    }
    this._mergeSplitClusters();

    this._zoom = this._map._zoom;
    this._currentShownBounds = this._getExpandedVisibleBounds();
  },

  _moveEnd: function () {
    if (this._inZoomAnimation) {
      return;
    }

    var newBounds = this._getExpandedVisibleBounds();

    this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, newBounds);
    this._topClusterLevel._recursivelyAddChildrenToMap(null, this._map._zoom, newBounds);

    this._currentShownBounds = newBounds;
    return;
  },

  _generateInitialClusters: function () {
    var maxZoom = this._map.getMaxZoom(),
      radius = this.options.maxClusterRadius,
      radiusFn = radius;

    //If we just set maxClusterRadius to a single number, we need to create
    //a simple function to return that number. Otherwise, we just have to
    //use the function we've passed in.
    if (typeof radius !== "function") {
      radiusFn = function () { return radius; };
    }

    if (this.options.disableClusteringAtZoom) {
      maxZoom = this.options.disableClusteringAtZoom - 1;
    }
    this._maxZoom = maxZoom;
    this._gridClusters = {};
    this._gridUnclustered = {};

    //Set up DistanceGrids for each zoom
    for (var zoom = maxZoom; zoom >= 0; zoom--) {
      this._gridClusters[zoom] = new L.DistanceGrid(radiusFn(zoom));
      this._gridUnclustered[zoom] = new L.DistanceGrid(radiusFn(zoom));
    }

    this._topClusterLevel = new L.MarkerCluster(this, -1);
  },

  //Zoom: Zoom to start adding at (Pass this._maxZoom to start at the bottom)
  _addLayer: function (layer, zoom) {
    var gridClusters = this._gridClusters,
        gridUnclustered = this._gridUnclustered,
        markerPoint, z;

    if (this.options.singleMarkerMode) {
      layer.options.icon = this.options.iconCreateFunction({
        getChildCount: function () {
          return 1;
        },
        getAllChildMarkers: function () {
          return [layer];
        }
      });
    }

    //Find the lowest zoom level to slot this one in
    for (; zoom >= 0; zoom--) {
      markerPoint = this._map.project(layer.getLatLng(), zoom); // calculate pixel position

      //Try find a cluster close by
      var closest = gridClusters[zoom].getNearObject(markerPoint);
      if (closest) {
        closest._addChild(layer);
        layer.__parent = closest;
        return;
      }

      //Try find a marker close by to form a new cluster with
      closest = gridUnclustered[zoom].getNearObject(markerPoint);
      if (closest) {
        var parent = closest.__parent;
        if (parent) {
          this._removeLayer(closest, false);
        }

        //Create new cluster with these 2 in it

        var newCluster = new L.MarkerCluster(this, zoom, closest, layer);
        gridClusters[zoom].addObject(newCluster, this._map.project(newCluster._cLatLng, zoom));
        closest.__parent = newCluster;
        layer.__parent = newCluster;

        //First create any new intermediate parent clusters that don't exist
        var lastParent = newCluster;
        for (z = zoom - 1; z > parent._zoom; z--) {
          lastParent = new L.MarkerCluster(this, z, lastParent);
          gridClusters[z].addObject(lastParent, this._map.project(closest.getLatLng(), z));
        }
        parent._addChild(lastParent);

        //Remove closest from this zoom level and any above that it is in, replace with newCluster
        for (z = zoom; z >= 0; z--) {
          if (!gridUnclustered[z].removeObject(closest, this._map.project(closest.getLatLng(), z))) {
            break;
          }
        }

        return;
      }

      //Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards
      gridUnclustered[zoom].addObject(layer, markerPoint);
    }

    //Didn't get in anything, add us to the top
    this._topClusterLevel._addChild(layer);
    layer.__parent = this._topClusterLevel;
    return;
  },

  //Enqueue code to fire after the marker expand/contract has happened
  _enqueue: function (fn) {
    this._queue.push(fn);
    if (!this._queueTimeout) {
      this._queueTimeout = setTimeout(L.bind(this._processQueue, this), 300);
    }
  },
  _processQueue: function () {
    for (var i = 0; i < this._queue.length; i++) {
      this._queue[i].call(this);
    }
    this._queue.length = 0;
    clearTimeout(this._queueTimeout);
    this._queueTimeout = null;
  },

  //Merge and split any existing clusters that are too big or small
  _mergeSplitClusters: function () {

    //Incase we are starting to split before the animation finished
    this._processQueue();

    if (this._zoom < this._map._zoom && this._currentShownBounds.intersects(this._getExpandedVisibleBounds())) { //Zoom in, split
      this._animationStart();
      //Remove clusters now off screen
      this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, this._getExpandedVisibleBounds());

      this._animationZoomIn(this._zoom, this._map._zoom);

    } else if (this._zoom > this._map._zoom) { //Zoom out, merge
      this._animationStart();

      this._animationZoomOut(this._zoom, this._map._zoom);
    } else {
      this._moveEnd();
    }
  },

  //Gets the maps visible bounds expanded in each direction by the size of the screen (so the user cannot see an area we do not cover in one pan)
  _getExpandedVisibleBounds: function () {
    if (!this.options.removeOutsideVisibleBounds) {
      return this.getBounds();
    }

    var map = this._map,
      bounds = map.getBounds(),
      sw = bounds._southWest,
      ne = bounds._northEast,
      latDiff = L.Browser.mobile ? 0 : Math.abs(sw.lat - ne.lat),
      lngDiff = L.Browser.mobile ? 0 : Math.abs(sw.lng - ne.lng);

    return new L.LatLngBounds(
      new L.LatLng(sw.lat - latDiff, sw.lng - lngDiff, true),
      new L.LatLng(ne.lat + latDiff, ne.lng + lngDiff, true));
  },

  //Shared animation code
  _animationAddLayerNonAnimated: function (layer, newCluster) {
    if (newCluster === layer) {
      this._featureGroup.addLayer(layer);
    } else if (newCluster._childCount === 2) {
      newCluster._addToMap();

      var markers = newCluster.getAllChildMarkers();
      this._featureGroup.removeLayer(markers[0]);
      this._featureGroup.removeLayer(markers[1]);
    } else {
      newCluster._updateIcon();
    }
  }
});

L.MarkerClusterGroup.include(!L.DomUtil.TRANSITION ? {

  //Non Animated versions of everything
  _animationStart: function () {
    //Do nothing...
  },
  _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
    this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
    this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());

    //We didn't actually animate, but we use this event to mean "clustering animations have finished"
    this.fire('animationend');
  },
  _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
    this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
    this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());

    //We didn't actually animate, but we use this event to mean "clustering animations have finished"
    this.fire('animationend');
  },
  _animationAddLayer: function (layer, newCluster) {
    this._animationAddLayerNonAnimated(layer, newCluster);
  }
} : {

  //Animated versions here
  _animationStart: function () {
    this._map._mapPane.className += ' leaflet-cluster-anim';
    this._inZoomAnimation++;
  },
  _animationEnd: function () {
    if (this._map) {
      this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');
    }
    this._inZoomAnimation--;
    this.fire('animationend');
  },
  _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
    var bounds = this._getExpandedVisibleBounds(),
        fg = this._featureGroup,
        i;

    //Add all children of current clusters to map and remove those clusters from map
    this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
      var startPos = c._latlng,
        markers = c._markers,
        m;

      if (!bounds.contains(startPos)) {
        startPos = null;
      }

      if (c._isSingleParent() && previousZoomLevel + 1 === newZoomLevel) { //Immediately add the new child and remove us
        fg.removeLayer(c);
        c._recursivelyAddChildrenToMap(null, newZoomLevel, bounds);
      } else {
        //Fade out old cluster
        c.setOpacity(0);
        c._recursivelyAddChildrenToMap(startPos, newZoomLevel, bounds);
      }

      //Remove all markers that aren't visible any more
      //TODO: Do we actually need to do this on the higher levels too?
      for (i = markers.length - 1; i >= 0; i--) {
        m = markers[i];
        if (!bounds.contains(m._latlng)) {
          fg.removeLayer(m);
        }
      }

    });

    this._forceLayout();

    //Update opacities
    this._topClusterLevel._recursivelyBecomeVisible(bounds, newZoomLevel);
    //TODO Maybe? Update markers in _recursivelyBecomeVisible
    fg.eachLayer(function (n) {
      if (!(n instanceof L.MarkerCluster) && n._icon) {
        n.setOpacity(1);
      }
    });

    //update the positions of the just added clusters/markers
    this._topClusterLevel._recursively(bounds, previousZoomLevel, newZoomLevel, function (c) {
      c._recursivelyRestoreChildPositions(newZoomLevel);
    });

    //Remove the old clusters and close the zoom animation
    this._enqueue(function () {
      //update the positions of the just added clusters/markers
      this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
        fg.removeLayer(c);
        c.setOpacity(1);
      });

      this._animationEnd();
    });
  },

  _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
    this._animationZoomOutSingle(this._topClusterLevel, previousZoomLevel - 1, newZoomLevel);

    //Need to add markers for those that weren't on the map before but are now
    this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
    //Remove markers that were on the map before but won't be now
    this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel, this._getExpandedVisibleBounds());
  },
  _animationZoomOutSingle: function (cluster, previousZoomLevel, newZoomLevel) {
    var bounds = this._getExpandedVisibleBounds();

    //Animate all of the markers in the clusters to move to their cluster center point
    cluster._recursivelyAnimateChildrenInAndAddSelfToMap(bounds, previousZoomLevel + 1, newZoomLevel);

    var me = this;

    //Update the opacity (If we immediately set it they won't animate)
    this._forceLayout();
    cluster._recursivelyBecomeVisible(bounds, newZoomLevel);

    //TODO: Maybe use the transition timing stuff to make this more reliable
    //When the animations are done, tidy up
    this._enqueue(function () {

      //This cluster stopped being a cluster before the timeout fired
      if (cluster._childCount === 1) {
        var m = cluster._markers[0];
        //If we were in a cluster animation at the time then the opacity and position of our child could be wrong now, so fix it
        m.setLatLng(m.getLatLng());
        if (m.setOpacity) {
          m.setOpacity(1);
        }
      } else {
        cluster._recursively(bounds, newZoomLevel, 0, function (c) {
          c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel + 1);
        });
      }
      me._animationEnd();
    });
  },
  _animationAddLayer: function (layer, newCluster) {
    var me = this,
      fg = this._featureGroup;

    fg.addLayer(layer);
    if (newCluster !== layer) {
      if (newCluster._childCount > 2) { //Was already a cluster

        newCluster._updateIcon();
        this._forceLayout();
        this._animationStart();

        layer._setPos(this._map.latLngToLayerPoint(newCluster.getLatLng()));
        layer.setOpacity(0);

        this._enqueue(function () {
          fg.removeLayer(layer);
          layer.setOpacity(1);

          me._animationEnd();
        });

      } else { //Just became a cluster
        this._forceLayout();

        me._animationStart();
        me._animationZoomOutSingle(newCluster, this._map.getMaxZoom(), this._map.getZoom());
      }
    }
  },

  //Force a browser layout of stuff in the map
  // Should apply the current opacity and location to all elements so we can update them again for an animation
  _forceLayout: function () {
    //In my testing this works, infact offsetWidth of any element seems to work.
    //Could loop all this._layers and do this for each _icon if it stops working

    L.Util.falseFn(document.body.offsetWidth);
  }
});

L.markerClusterGroup = function (options) {
  return new L.MarkerClusterGroup(options);
};

L.MarkerCluster = L.Marker.extend({
  initialize: function (group, zoom, a, b) {

    L.Marker.prototype.initialize.call(this, a ? (a._cLatLng || a.getLatLng()) : new L.LatLng(0, 0), { icon: this });

    this._group = group;
    this._zoom = zoom;

    this._markers = [];
    this._childClusters = [];
    this._childCount = 0;
    this._iconNeedsUpdate = true;

    this._bounds = new L.LatLngBounds();

    if (a) {
      this._addChild(a);
    }
    if (b) {
      this._addChild(b);
    }
  },

  //Recursively retrieve all child markers of this cluster
  getAllChildMarkers: function (storageArray) {
    storageArray = storageArray || [];

    for (var i = this._childClusters.length - 1; i >= 0; i--) {
      this._childClusters[i].getAllChildMarkers(storageArray);
    }

    for (var j = this._markers.length - 1; j >= 0; j--) {
      storageArray.push(this._markers[j]);
    }

    return storageArray;
  },

  //Returns the count of how many child markers we have
  getChildCount: function () {
    return this._childCount;
  },

  //Zoom to the minimum of showing all of the child markers, or the extents of this cluster
  zoomToBounds: function () {
    var childClusters = this._childClusters.slice(),
      map = this._group._map,
      boundsZoom = map.getBoundsZoom(this._bounds),
      zoom = this._zoom + 1,
      mapZoom = map.getZoom(),
      i;

    //calculate how far we need to zoom down to see all of the markers
    while (childClusters.length > 0 && boundsZoom > zoom) {
      zoom++;
      var newClusters = [];
      for (i = 0; i < childClusters.length; i++) {
        newClusters = newClusters.concat(childClusters[i]._childClusters);
      }
      childClusters = newClusters;
    }

    if (boundsZoom > zoom) {
      this._group._map.setView(this._latlng, zoom);
    } else if (boundsZoom <= mapZoom) { //If fitBounds wouldn't zoom us down, zoom us down instead
      this._group._map.setView(this._latlng, mapZoom + 1);
    } else {
      this._group._map.fitBounds(this._bounds);
    }
  },

  getBounds: function () {
    var bounds = new L.LatLngBounds();
    bounds.extend(this._bounds);
    return bounds;
  },

  _updateIcon: function () {
    this._iconNeedsUpdate = true;
    if (this._icon) {
      this.setIcon(this);
    }
  },

  //Cludge for Icon, we pretend to be an icon for performance
  createIcon: function () {
    if (this._iconNeedsUpdate) {
      this._iconObj = this._group.options.iconCreateFunction(this);
      this._iconNeedsUpdate = false;
    }
    return this._iconObj.createIcon();
  },
  createShadow: function () {
    return this._iconObj.createShadow();
  },

  _addChild: function (new1, isNotificationFromChild) {

    this._iconNeedsUpdate = true;
    this._expandBounds(new1);

    if (new1 instanceof L.MarkerCluster) {
      if (!isNotificationFromChild) {
        this._childClusters.push(new1);
        new1.__parent = this;
      }
      this._childCount += new1._childCount;
    } else {
      if (!isNotificationFromChild) {
        this._markers.push(new1);
      }
      this._childCount++;
    }

    if (this.__parent) {
      this.__parent._addChild(new1, true);
    }
  },

  //Expand our bounds and tell our parent to
  _expandBounds: function (marker) {
    var addedCount,
        addedLatLng = marker._wLatLng || marker._latlng;

    if (marker instanceof L.MarkerCluster) {
      this._bounds.extend(marker._bounds);
      addedCount = marker._childCount;
    } else {
      this._bounds.extend(addedLatLng);
      addedCount = 1;
    }

    if (!this._cLatLng) {
      // when clustering, take position of the first point as the cluster center
      this._cLatLng = marker._cLatLng || addedLatLng;
    }

    // when showing clusters, take weighted average of all points as cluster center
    var totalCount = this._childCount + addedCount;

    //Calculate weighted latlng for display
    if (!this._wLatLng) {
      this._latlng = this._wLatLng = new L.LatLng(addedLatLng.lat, addedLatLng.lng);
    } else {
      this._wLatLng.lat = (addedLatLng.lat * addedCount + this._wLatLng.lat * this._childCount) / totalCount;
      this._wLatLng.lng = (addedLatLng.lng * addedCount + this._wLatLng.lng * this._childCount) / totalCount;
    }
  },

  //Set our markers position as given and add it to the map
  _addToMap: function (startPos) {
    if (startPos) {
      this._backupLatlng = this._latlng;
      this.setLatLng(startPos);
    }
    this._group._featureGroup.addLayer(this);
  },

  _recursivelyAnimateChildrenIn: function (bounds, center, maxZoom) {
    this._recursively(bounds, 0, maxZoom - 1,
      function (c) {
        var markers = c._markers,
          i, m;
        for (i = markers.length - 1; i >= 0; i--) {
          m = markers[i];

          //Only do it if the icon is still on the map
          if (m._icon) {
            m._setPos(center);
            m.setOpacity(0);
          }
        }
      },
      function (c) {
        var childClusters = c._childClusters,
          j, cm;
        for (j = childClusters.length - 1; j >= 0; j--) {
          cm = childClusters[j];
          if (cm._icon) {
            cm._setPos(center);
            cm.setOpacity(0);
          }
        }
      }
    );
  },

  _recursivelyAnimateChildrenInAndAddSelfToMap: function (bounds, previousZoomLevel, newZoomLevel) {
    this._recursively(bounds, newZoomLevel, 0,
      function (c) {
        c._recursivelyAnimateChildrenIn(bounds, c._group._map.latLngToLayerPoint(c.getLatLng()).round(), previousZoomLevel);

        //TODO: depthToAnimateIn affects _isSingleParent, if there is a multizoom we may/may not be.
        //As a hack we only do a animation free zoom on a single level zoom, if someone does multiple levels then we always animate
        if (c._isSingleParent() && previousZoomLevel - 1 === newZoomLevel) {
          c.setOpacity(1);
          c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel); //Immediately remove our children as we are replacing them. TODO previousBounds not bounds
        } else {
          c.setOpacity(0);
        }

        c._addToMap();
      }
    );
  },

  _recursivelyBecomeVisible: function (bounds, zoomLevel) {
    this._recursively(bounds, 0, zoomLevel, null, function (c) {
      c.setOpacity(1);
    });
  },

  _recursivelyAddChildrenToMap: function (startPos, zoomLevel, bounds) {
    this._recursively(bounds, -1, zoomLevel,
      function (c) {
        if (zoomLevel === c._zoom) {
          return;
        }

        //Add our child markers at startPos (so they can be animated out)
        for (var i = c._markers.length - 1; i >= 0; i--) {
          var nm = c._markers[i];

          if (!bounds.contains(nm._latlng)) {
            continue;
          }

          if (startPos) {
            nm._backupLatlng = nm.getLatLng();

            nm.setLatLng(startPos);
            if (nm.setOpacity) {
              nm.setOpacity(0);
            }
          }

          c._group._featureGroup.addLayer(nm);
        }
      },
      function (c) {
        c._addToMap(startPos);
      }
    );
  },

  _recursivelyRestoreChildPositions: function (zoomLevel) {
    //Fix positions of child markers
    for (var i = this._markers.length - 1; i >= 0; i--) {
      var nm = this._markers[i];
      if (nm._backupLatlng) {
        nm.setLatLng(nm._backupLatlng);
        delete nm._backupLatlng;
      }
    }

    if (zoomLevel - 1 === this._zoom) {
      //Reposition child clusters
      for (var j = this._childClusters.length - 1; j >= 0; j--) {
        this._childClusters[j]._restorePosition();
      }
    } else {
      for (var k = this._childClusters.length - 1; k >= 0; k--) {
        this._childClusters[k]._recursivelyRestoreChildPositions(zoomLevel);
      }
    }
  },

  _restorePosition: function () {
    if (this._backupLatlng) {
      this.setLatLng(this._backupLatlng);
      delete this._backupLatlng;
    }
  },

  //exceptBounds: If set, don't remove any markers/clusters in it
  _recursivelyRemoveChildrenFromMap: function (previousBounds, zoomLevel, exceptBounds) {
    var m, i;
    this._recursively(previousBounds, -1, zoomLevel - 1,
      function (c) {
        //Remove markers at every level
        for (i = c._markers.length - 1; i >= 0; i--) {
          m = c._markers[i];
          if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
            c._group._featureGroup.removeLayer(m);
            if (m.setOpacity) {
              m.setOpacity(1);
            }
          }
        }
      },
      function (c) {
        //Remove child clusters at just the bottom level
        for (i = c._childClusters.length - 1; i >= 0; i--) {
          m = c._childClusters[i];
          if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
            c._group._featureGroup.removeLayer(m);
            if (m.setOpacity) {
              m.setOpacity(1);
            }
          }
        }
      }
    );
  },

  //Run the given functions recursively to this and child clusters
  // boundsToApplyTo: a L.LatLngBounds representing the bounds of what clusters to recurse in to
  // zoomLevelToStart: zoom level to start running functions (inclusive)
  // zoomLevelToStop: zoom level to stop running functions (inclusive)
  // runAtEveryLevel: function that takes an L.MarkerCluster as an argument that should be applied on every level
  // runAtBottomLevel: function that takes an L.MarkerCluster as an argument that should be applied at only the bottom level
  _recursively: function (boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel) {
    var childClusters = this._childClusters,
        zoom = this._zoom,
      i, c;

    if (zoomLevelToStart > zoom) { //Still going down to required depth, just recurse to child clusters
      for (i = childClusters.length - 1; i >= 0; i--) {
        c = childClusters[i];
        if (boundsToApplyTo.intersects(c._bounds)) {
          c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
        }
      }
    } else { //In required depth

      if (runAtEveryLevel) {
        runAtEveryLevel(this);
      }
      if (runAtBottomLevel && this._zoom === zoomLevelToStop) {
        runAtBottomLevel(this);
      }

      //TODO: This loop is almost the same as above
      if (zoomLevelToStop > zoom) {
        for (i = childClusters.length - 1; i >= 0; i--) {
          c = childClusters[i];
          if (boundsToApplyTo.intersects(c._bounds)) {
            c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
          }
        }
      }
    }
  },

  _recalculateBounds: function () {
    var markers = this._markers,
      childClusters = this._childClusters,
      i;

    this._bounds = new L.LatLngBounds();
    delete this._wLatLng;

    for (i = markers.length - 1; i >= 0; i--) {
      this._expandBounds(markers[i]);
    }
    for (i = childClusters.length - 1; i >= 0; i--) {
      this._expandBounds(childClusters[i]);
    }
  },

  //Returns true if we are the parent of only one cluster and that cluster is the same as us
  _isSingleParent: function () {
    //Don't need to check this._markers as the rest won't work if there are any
    return this._childClusters.length > 0 && this._childClusters[0]._childCount === this._childCount;
  }
});

L.DistanceGrid = function (cellSize) {
  this._cellSize = cellSize;
  this._sqCellSize = cellSize * cellSize;
  this._grid = {};
  this._objectPoint = { };
};

L.DistanceGrid.prototype = {

  addObject: function (obj, point) {
    var x = this._getCoord(point.x),
        y = this._getCoord(point.y),
        grid = this._grid,
        row = grid[y] = grid[y] || {},
        cell = row[x] = row[x] || [],
        stamp = L.Util.stamp(obj);

    this._objectPoint[stamp] = point;

    cell.push(obj);
  },

  updateObject: function (obj, point) {
    this.removeObject(obj);
    this.addObject(obj, point);
  },

  //Returns true if the object was found
  removeObject: function (obj, point) {
    var x = this._getCoord(point.x),
        y = this._getCoord(point.y),
        grid = this._grid,
        row = grid[y] = grid[y] || {},
        cell = row[x] = row[x] || [],
        i, len;

    delete this._objectPoint[L.Util.stamp(obj)];

    for (i = 0, len = cell.length; i < len; i++) {
      if (cell[i] === obj) {

        cell.splice(i, 1);

        if (len === 1) {
          delete row[x];
        }

        return true;
      }
    }

  },

  eachObject: function (fn, context) {
    var i, j, k, len, row, cell, removed,
        grid = this._grid;

    for (i in grid) {
      row = grid[i];

      for (j in row) {
        cell = row[j];

        for (k = 0, len = cell.length; k < len; k++) {
          removed = fn.call(context, cell[k]);
          if (removed) {
            k--;
            len--;
          }
        }
      }
    }
  },

  getNearObject: function (point) {
    var x = this._getCoord(point.x),
        y = this._getCoord(point.y),
        i, j, k, row, cell, len, obj, dist,
        objectPoint = this._objectPoint,
        closestDistSq = this._sqCellSize,
        closest = null;

    for (i = y - 1; i <= y + 1; i++) {
      row = this._grid[i];
      if (row) {

        for (j = x - 1; j <= x + 1; j++) {
          cell = row[j];
          if (cell) {

            for (k = 0, len = cell.length; k < len; k++) {
              obj = cell[k];
              dist = this._sqDist(objectPoint[L.Util.stamp(obj)], point);
              if (dist < closestDistSq) {
                closestDistSq = dist;
                closest = obj;
              }
            }
          }
        }
      }
    }
    return closest;
  },

  _getCoord: function (x) {
    return Math.floor(x / this._cellSize);
  },

  _sqDist: function (p, p2) {
    var dx = p2.x - p.x,
        dy = p2.y - p.y;
    return dx * dx + dy * dy;
  }
};

/* Copyright (c) 2012 the authors listed at the following URL, and/or
the authors of referenced articles or incorporated external code:
http://en.literateprograms.org/Quickhull_(Javascript)?action=history&offset=20120410175256

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Retrieved from: http://en.literateprograms.org/Quickhull_(Javascript)?oldid=18434
*/

(function () {
  L.QuickHull = {

    /*
     * @param {Object} cpt a point to be measured from the baseline
     * @param {Array} bl the baseline, as represented by a two-element
     *   array of latlng objects.
     * @returns {Number} an approximate distance measure
     */
    getDistant: function (cpt, bl) {
      var vY = bl[1].lat - bl[0].lat,
        vX = bl[0].lng - bl[1].lng;
      return (vX * (cpt.lat - bl[0].lat) + vY * (cpt.lng - bl[0].lng));
    },

    /*
     * @param {Array} baseLine a two-element array of latlng objects
     *   representing the baseline to project from
     * @param {Array} latLngs an array of latlng objects
     * @returns {Object} the maximum point and all new points to stay
     *   in consideration for the hull.
     */
    findMostDistantPointFromBaseLine: function (baseLine, latLngs) {
      var maxD = 0,
        maxPt = null,
        newPoints = [],
        i, pt, d;

      for (i = latLngs.length - 1; i >= 0; i--) {
        pt = latLngs[i];
        d = this.getDistant(pt, baseLine);

        if (d > 0) {
          newPoints.push(pt);
        } else {
          continue;
        }

        if (d > maxD) {
          maxD = d;
          maxPt = pt;
        }
      }

      return { maxPoint: maxPt, newPoints: newPoints };
    },

    /*
     * Given a baseline, compute the convex hull of latLngs as an array
     * of latLngs.
     *
     * @param {Array} latLngs
     * @returns {Array}
     */
    buildConvexHull: function (baseLine, latLngs) {
      var convexHullBaseLines = [],
        t = this.findMostDistantPointFromBaseLine(baseLine, latLngs);

      if (t.maxPoint) { // if there is still a point "outside" the base line
        convexHullBaseLines =
          convexHullBaseLines.concat(
            this.buildConvexHull([baseLine[0], t.maxPoint], t.newPoints)
          );
        convexHullBaseLines =
          convexHullBaseLines.concat(
            this.buildConvexHull([t.maxPoint, baseLine[1]], t.newPoints)
          );
        return convexHullBaseLines;
      } else {  // if there is no more point "outside" the base line, the current base line is part of the convex hull
        return [baseLine[0]];
      }
    },

    /*
     * Given an array of latlngs, compute a convex hull as an array
     * of latlngs
     *
     * @param {Array} latLngs
     * @returns {Array}
     */
    getConvexHull: function (latLngs) {
      // find first baseline
      var maxLat = false, minLat = false,
        maxPt = null, minPt = null,
        i;

      for (i = latLngs.length - 1; i >= 0; i--) {
        var pt = latLngs[i];
        if (maxLat === false || pt.lat > maxLat) {
          maxPt = pt;
          maxLat = pt.lat;
        }
        if (minLat === false || pt.lat < minLat) {
          minPt = pt;
          minLat = pt.lat;
        }
      }
      var ch = [].concat(this.buildConvexHull([minPt, maxPt], latLngs),
                this.buildConvexHull([maxPt, minPt], latLngs));
      return ch;
    }
  };
}());

L.MarkerCluster.include({
  getConvexHull: function () {
    var childMarkers = this.getAllChildMarkers(),
      points = [],
      p, i;

    for (i = childMarkers.length - 1; i >= 0; i--) {
      p = childMarkers[i].getLatLng();
      points.push(p);
    }

    return L.QuickHull.getConvexHull(points);
  }
});

//This code is 100% based on https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
//Huge thanks to jawj for implementing it first to make my job easy :-)

L.MarkerCluster.include({

  _2PI: Math.PI * 2,
  _circleFootSeparation: 25, //related to circumference of circle
  _circleStartAngle: Math.PI / 6,

  _spiralFootSeparation:  28, //related to size of spiral (experiment!)
  _spiralLengthStart: 11,
  _spiralLengthFactor: 5,

  _circleSpiralSwitchover: 9, //show spiral instead of circle from this marker count upwards.
                // 0 -> always spiral; Infinity -> always circle

  spiderfy: function () {
    if (this._group._spiderfied === this || this._group._inZoomAnimation) {
      return;
    }

    var childMarkers = this.getAllChildMarkers(),
      group = this._group,
      map = group._map,
      center = map.latLngToLayerPoint(this._latlng),
      positions;

    this._group._unspiderfy();
    this._group._spiderfied = this;

    //TODO Maybe: childMarkers order by distance to center

    if (childMarkers.length >= this._circleSpiralSwitchover) {
      positions = this._generatePointsSpiral(childMarkers.length, center);
    } else {
      center.y += 10; //Otherwise circles look wrong
      positions = this._generatePointsCircle(childMarkers.length, center);
    }

    this._animationSpiderfy(childMarkers, positions);
  },

  unspiderfy: function (zoomDetails) {
    /// <param Name="zoomDetails">Argument from zoomanim if being called in a zoom animation or null otherwise</param>
    if (this._group._inZoomAnimation) {
      return;
    }
    this._animationUnspiderfy(zoomDetails);

    this._group._spiderfied = null;
  },

  _generatePointsCircle: function (count, centerPt) {
    var circumference = this._group.options.spiderfyDistanceMultiplier * this._circleFootSeparation * (2 + count),
      legLength = circumference / this._2PI,  //radius from circumference
      angleStep = this._2PI / count,
      res = [],
      i, angle;

    res.length = count;

    for (i = count - 1; i >= 0; i--) {
      angle = this._circleStartAngle + i * angleStep;
      res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
    }

    return res;
  },

  _generatePointsSpiral: function (count, centerPt) {
    var legLength = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthStart,
      separation = this._group.options.spiderfyDistanceMultiplier * this._spiralFootSeparation,
      lengthFactor = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthFactor,
      angle = 0,
      res = [],
      i;

    res.length = count;

    for (i = count - 1; i >= 0; i--) {
      angle += separation / legLength + i * 0.0005;
      res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
      legLength += this._2PI * lengthFactor / angle;
    }
    return res;
  },

  _noanimationUnspiderfy: function () {
    var group = this._group,
      map = group._map,
      fg = group._featureGroup,
      childMarkers = this.getAllChildMarkers(),
      m, i;

    this.setOpacity(1);
    for (i = childMarkers.length - 1; i >= 0; i--) {
      m = childMarkers[i];

      fg.removeLayer(m);

      if (m._preSpiderfyLatlng) {
        m.setLatLng(m._preSpiderfyLatlng);
        delete m._preSpiderfyLatlng;
      }
      if (m.setZIndexOffset) {
        m.setZIndexOffset(0);
      }

      if (m._spiderLeg) {
        map.removeLayer(m._spiderLeg);
        delete m._spiderLeg;
      }
    }

    group._spiderfied = null;
  }
});

L.MarkerCluster.include(!L.DomUtil.TRANSITION ? {
  //Non Animated versions of everything
  _animationSpiderfy: function (childMarkers, positions) {
    var group = this._group,
      map = group._map,
      fg = group._featureGroup,
      i, m, leg, newPos;

    for (i = childMarkers.length - 1; i >= 0; i--) {
      newPos = map.layerPointToLatLng(positions[i]);
      m = childMarkers[i];

      m._preSpiderfyLatlng = m._latlng;
      m.setLatLng(newPos);
      if (m.setZIndexOffset) {
        m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
      }

      fg.addLayer(m);

      leg = new L.Polyline([this._latlng, newPos], { weight: 1.5, color: '#222' });
      map.addLayer(leg);
      m._spiderLeg = leg;
    }
    this.setOpacity(0.3);
    group.fire('spiderfied');
  },

  _animationUnspiderfy: function () {
    this._noanimationUnspiderfy();
  }
} : {
  //Animated versions here
  SVG_ANIMATION: (function () {
    return document.createElementNS('http://www.w3.org/2000/svg', 'animate').toString().indexOf('SVGAnimate') > -1;
  }()),

  _animationSpiderfy: function (childMarkers, positions) {
    var me = this,
      group = this._group,
      map = group._map,
      fg = group._featureGroup,
      thisLayerPos = map.latLngToLayerPoint(this._latlng),
      i, m, leg, newPos;

    //Add markers to map hidden at our center point
    for (i = childMarkers.length - 1; i >= 0; i--) {
      m = childMarkers[i];

      //If it is a marker, add it now and we'll animate it out
      if (m.setOpacity) {
        m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
        m.setOpacity(0);

        fg.addLayer(m);

        m._setPos(thisLayerPos);
      } else {
        //Vectors just get immediately added
        fg.addLayer(m);
      }
    }

    group._forceLayout();
    group._animationStart();

    var initialLegOpacity = L.Path.SVG ? 0 : 0.3,
      xmlns = L.Path.SVG_NS;

    for (i = childMarkers.length - 1; i >= 0; i--) {
      newPos = map.layerPointToLatLng(positions[i]);
      m = childMarkers[i];

      //Move marker to new position
      m._preSpiderfyLatlng = m._latlng;
      m.setLatLng(newPos);

      if (m.setOpacity) {
        m.setOpacity(1);
      }

      //Add Legs.
      leg = new L.Polyline([me._latlng, newPos], { weight: 1.5, color: '#222', opacity: initialLegOpacity });
      map.addLayer(leg);
      m._spiderLeg = leg;

      //Following animations don't work for canvas
      if (!L.Path.SVG || !this.SVG_ANIMATION) {
        continue;
      }

      //How this works:
      //http://stackoverflow.com/questions/5924238/how-do-you-animate-an-svg-path-in-ios
      //http://dev.opera.com/articles/view/advanced-svg-animation-techniques/

      //Animate length
      var length = leg._path.getTotalLength();
      leg._path.setAttribute("stroke-dasharray", length + "," + length);

      var anim = document.createElementNS(xmlns, "animate");
      anim.setAttribute("attributeName", "stroke-dashoffset");
      anim.setAttribute("begin", "indefinite");
      anim.setAttribute("from", length);
      anim.setAttribute("to", 0);
      anim.setAttribute("dur", 0.25);
      leg._path.appendChild(anim);
      anim.beginElement();

      //Animate opacity
      anim = document.createElementNS(xmlns, "animate");
      anim.setAttribute("attributeName", "stroke-opacity");
      anim.setAttribute("attributeName", "stroke-opacity");
      anim.setAttribute("begin", "indefinite");
      anim.setAttribute("from", 0);
      anim.setAttribute("to", 0.5);
      anim.setAttribute("dur", 0.25);
      leg._path.appendChild(anim);
      anim.beginElement();
    }
    me.setOpacity(0.3);

    //Set the opacity of the spiderLegs back to their correct value
    // The animations above override this until they complete.
    // If the initial opacity of the spiderlegs isn't 0 then they appear before the animation starts.
    if (L.Path.SVG) {
      this._group._forceLayout();

      for (i = childMarkers.length - 1; i >= 0; i--) {
        m = childMarkers[i]._spiderLeg;

        m.options.opacity = 0.5;
        m._path.setAttribute('stroke-opacity', 0.5);
      }
    }

    setTimeout(function () {
      group._animationEnd();
      group.fire('spiderfied');
    }, 200);
  },

  _animationUnspiderfy: function (zoomDetails) {
    var group = this._group,
      map = group._map,
      fg = group._featureGroup,
      thisLayerPos = zoomDetails ? map._latLngToNewLayerPoint(this._latlng, zoomDetails.zoom, zoomDetails.center) : map.latLngToLayerPoint(this._latlng),
      childMarkers = this.getAllChildMarkers(),
      svg = L.Path.SVG && this.SVG_ANIMATION,
      m, i, a;

    group._animationStart();

    //Make us visible and bring the child markers back in
    this.setOpacity(1);
    for (i = childMarkers.length - 1; i >= 0; i--) {
      m = childMarkers[i];

      //Marker was added to us after we were spidified
      if (!m._preSpiderfyLatlng) {
        continue;
      }

      //Fix up the location to the real one
      m.setLatLng(m._preSpiderfyLatlng);
      delete m._preSpiderfyLatlng;
      //Hack override the location to be our center
      if (m.setOpacity) {
        m._setPos(thisLayerPos);
        m.setOpacity(0);
      } else {
        fg.removeLayer(m);
      }

      //Animate the spider legs back in
      if (svg) {
        a = m._spiderLeg._path.childNodes[0];
        a.setAttribute('to', a.getAttribute('from'));
        a.setAttribute('from', 0);
        a.beginElement();

        a = m._spiderLeg._path.childNodes[1];
        a.setAttribute('from', 0.5);
        a.setAttribute('to', 0);
        a.setAttribute('stroke-opacity', 0);
        a.beginElement();

        m._spiderLeg._path.setAttribute('stroke-opacity', 0);
      }
    }

    setTimeout(function () {
      //If we have only <= one child left then that marker will be shown on the map so don't remove it!
      var stillThereChildCount = 0;
      for (i = childMarkers.length - 1; i >= 0; i--) {
        m = childMarkers[i];
        if (m._spiderLeg) {
          stillThereChildCount++;
        }
      }

      for (i = childMarkers.length - 1; i >= 0; i--) {
        m = childMarkers[i];

        if (!m._spiderLeg) { //Has already been unspiderfied
          continue;
        }

        if (m.setOpacity) {
          m.setOpacity(1);
          m.setZIndexOffset(0);
        }

        if (stillThereChildCount > 1) {
          fg.removeLayer(m);
        }

        map.removeLayer(m._spiderLeg);
        delete m._spiderLeg;
      }
      group._animationEnd();
    }, 200);
  }
});

L.MarkerClusterGroup.include({
  //The MarkerCluster currently spiderfied (if any)
  _spiderfied: null,

  _spiderfierOnAdd: function () {
    this._map.on('click', this._unspiderfyWrapper, this);

    if (this._map.options.zoomAnimation) {
      this._map.on('zoomstart', this._unspiderfyZoomStart, this);
    }
    //Browsers without zoomAnimation or a big zoom don't fire zoomstart
    this._map.on('zoomend', this._noanimationUnspiderfy, this);

    if (L.Path.SVG && !L.Browser.touch) {
      this._map._initPathRoot();
      //Needs to happen in the pageload, not after, or animations don't work in webkit
      //  http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements
      //Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable
    }
  },

  _spiderfierOnRemove: function () {
    this._map.off('click', this._unspiderfyWrapper, this);
    this._map.off('zoomstart', this._unspiderfyZoomStart, this);
    this._map.off('zoomanim', this._unspiderfyZoomAnim, this);

    this._unspiderfy(); //Ensure that markers are back where they should be
  },

  //On zoom start we add a zoomanim handler so that we are guaranteed to be last (after markers are animated)
  //This means we can define the animation they do rather than Markers doing an animation to their actual location
  _unspiderfyZoomStart: function () {
    if (!this._map) { //May have been removed from the map by a zoomEnd handler
      return;
    }

    this._map.on('zoomanim', this._unspiderfyZoomAnim, this);
  },
  _unspiderfyZoomAnim: function (zoomDetails) {
    //Wait until the first zoomanim after the user has finished touch-zooming before running the animation
    if (L.DomUtil.hasClass(this._map._mapPane, 'leaflet-touching')) {
      return;
    }

    this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
    this._unspiderfy(zoomDetails);
  },

  _unspiderfyWrapper: function () {
    /// _unspiderfy but passes no arguments
    this._unspiderfy();
  },

  _unspiderfy: function (zoomDetails) {
    if (this._spiderfied) {
      this._spiderfied.unspiderfy(zoomDetails);
    }
  },

  _noanimationUnspiderfy: function () {
    if (this._spiderfied) {
      this._spiderfied._noanimationUnspiderfy();
    }
  },

  //If the given layer is currently being spiderfied then we unspiderfy it so it isn't on the map anymore etc
  _unspiderfyLayer: function (layer) {
    if (layer._spiderLeg) {
      this._featureGroup.removeLayer(layer);

      layer.setOpacity(1);
      //Position will be fixed up immediately in _animationUnspiderfy
      layer.setZIndexOffset(0);

      this._map.removeLayer(layer._spiderLeg);
      delete layer._spiderLeg;
    }
  }
});

}(window, document));


var map;

// Create object to define tile provider settings and transformations. Supports
// all Leaflet TileLayer options.
var projectedTiles = {
  "EPSG:3571 Bering Sea": L.PolarMap.layer3571,
  "EPSG:3572 Alaska"    : L.PolarMap.layer3572,
  "EPSG:3573 Canada"    : L.PolarMap.layer3573,
  "EPSG:3574 Atlantic"  : L.PolarMap.layer3574,
  "EPSG:3575 Europe"    : L.PolarMap.layer3575,
  "EPSG:3576 Russia"    : L.PolarMap.layer3576
};

// Return the tile layer that has a key containing `projection`
var getTileLayerForProjection = function(projection) {
  for (var key in projectedTiles) {
    if (projectedTiles.hasOwnProperty(key)) {
      if (key.indexOf(projection) !== -1) {
        return projectedTiles[key];
      }
    }
  }

  return null;
};

// Set up next/prev linked list
$.each(projectedTiles, function (layerName, layer) {
  var keys = Object.keys(projectedTiles);
  var index = keys.indexOf(layerName);
  var prev = (index === 0) ? keys.length - 1 : index - 1;
  var next = (index === keys.length - 1) ? 0 : index + 1;

  layer.prev = projectedTiles[keys[prev]];
  layer.next = projectedTiles[keys[next]];
});

// Initialization
$(document).ready(function() {
  Autosize.enable();

  // Load PolarMap
  var defaultLayer = projectedTiles["EPSG:3571 Bering Sea"];
  map = L.PolarMap.map('xmap', {
    baseLayer: defaultLayer,
    center: defaultLayer.options.center,
    zoom: defaultLayer.options.zoom
  });

  // Add a Leaflet layer group. Assumed to be EPSG:3857.
  L.layerGroup([
    L.marker([51.080126, -114.13380900]).bindPopup("University of Calgary"),
    L.marker([90, 100]).bindPopup("North Pole")
  ]).addTo(map);

  var layersControl = L.control.layers(projectedTiles, null);
  layersControl.addTo(map);

  // Wire up rotation controls
  var getBaseLayer = function() {
    var foundLayer = null;
    $.each(projectedTiles, function (layerName, layer) {
      if (map.hasLayer(layer)) {
        foundLayer = layer;
      }
    });
    return foundLayer;
  };

  var rotationControls = L.PolarMap.Control.rotation({
    onRotateCW: function() {
      map.loadTileProjection(getBaseLayer().next);
    },

    onRotateCCW: function() {
      map.loadTileProjection(getBaseLayer().prev);
    }
  });
  rotationControls.addTo(map);

  // Projection Selection
  var setProjectionForLongitude = function (longitude) {
    var value;
    if (longitude >= -180 && longitude <= -165) {
      value = "EPSG:3571";
    } else if (longitude > -165 && longitude <= -125) {
      value = "EPSG:3572";
    } else if (longitude > -125 && longitude <= -70) {
      value = "EPSG:3573";
    } else if (longitude > -70 && longitude <= -15) {
      value = "EPSG:3574";
    } else if (longitude > -15 && longitude <= 50) {
      value = "EPSG:3575";
    } else if (longitude > 50 && longitude <= 135) {
      value = "EPSG:3576";
    } else {
      value = "EPSG:3571";
    }

    map.loadTileProjection(getTileLayerForProjection(value));
  };

  // Automatic Location and Projection Detection
  var userLocation = L.circle();

  map.on('locationfound', function (e) {
    console.log("Location info", e);
    userLocation.setLatLng(e.latlng);
    userLocation.setRadius(e.accuracy);

    if (!map.hasLayer(userLocation)) {
      userLocation.addTo(map);
    }

    setProjectionForLongitude(e.longitude);
  });

  map.on('locationerror', function (e) {
    console.warn("Location detection error:", e);
  });

  map.locate();
});


/* Strings */

var t = {
  attribution: 'Map © ArcticConnect. Data © OpenStreetMap contributors',
  locationDetectionError: "Location detection error: "
};

/* Tile Layer Configuration */

var tiles = {
  "EPSG:3571 Bering Sea": L.PolarMap.layer3571,
  "EPSG:3572 Alaska"    : L.PolarMap.layer3572,
  "EPSG:3573 Canada"    : L.PolarMap.layer3573,
  "EPSG:3574 Atlantic"  : L.PolarMap.layer3574,
  "EPSG:3575 Europe"    : L.PolarMap.layer3575,
  "EPSG:3576 Russia"    : L.PolarMap.layer3576
};

// Return the tile layer that has a key containing `projection`
var getTileLayerForProjection = function(projection) {
  for (var key in tiles) {
    if (tiles.hasOwnProperty(key)) {
      if (key.indexOf(projection) !== -1) {
        return tiles[key];
      }
    }
  }

  return null;
};

// Set up next/prev linked list
var keys = Object.keys(tiles).sort();
for (var i = 0; i < keys.length; i++) {
  var prev = (i === 0) ? 5 : i - 1;
  var next = (i === 5) ? 0 : i + 1;
  var layer = tiles[keys[i]];
  layer.prev = tiles[keys[prev]];
  layer.next = tiles[keys[next]];
}

/* PolarMap Library Function */

window.PolarMap = L.Class.extend({
  options: {
    geosearch: false,
    locate: false,
    permalink: true
  },

  statics: {
    VERSION: L.PolarMap.version
  },

  initialize: function (id, options) {
    var _this = this;
    L.Util.setOptions(this, options);
    this.tiles = tiles;

    /* Controls */

    this.layersControl = L.control.layers(this.tiles, null);

    this.rotationControls = L.PolarMap.Control.rotation({
      onRotateCW: function() {
        _this.map.loadTileProjection(_this.getBaseLayer().next);
      },

      onRotateCCW: function() {
        _this.map.loadTileProjection(_this.getBaseLayer().prev);
      }
    });

    /* Map */

    this.map = L.PolarMap.map(id, {
      baseLayer: this.tiles["EPSG:3573 Canada"],
      center: [90, 0],
      zoom: 4
    });

    this.layersControl.addTo(this.map);
    this.rotationControls.addTo(this.map);

    if (this.options.geosearch) {
      this._initGeosearch();
    }

    if (this.options.locate) {
      this._initLocate();
    }

    if (this.options.permalink) {
      this._initPermalink();
    }
  },

  addLayer: function (layer, options) {
    this.map.addLayer(layer);

    if (typeof(options) !== "undefined" && options.switcher) {
      this.layersControl.addOverlay(layer, options.name);
    }
  },

  getBaseLayer: function () {
    var foundLayer = null;

    for (var layer in this.tiles) {
      if (this.tiles.hasOwnProperty(layer)) {
        if (this.map.hasLayer(this.tiles[layer])) {
          foundLayer = this.tiles[layer];
        }
      }
    }
    return foundLayer;
  },

  _initGeosearch: function () {
    new L.Control.GeoSearch({
      provider: new L.GeoSearch.Provider.OpenStreetMap(),
      showMarker: false
    }).addTo(this.map);
  },

  _initLocate: function () {
    var _this = this;
    var userLocation = L.circle();

    this.map.on('locationfound', function (e) {
      userLocation.setLatLng(e.latlng);
      userLocation.setRadius(e.accuracy);

      if (!_this.map.hasLayer(userLocation)) {
        userLocation.addTo(_this.map);
      }

      _this._setProjectionForLongitude(e.longitude);
    });

    this.map.on('locationerror', function (e) {
      console.warn(t.locationDetectionError, e);
    });

    this.map.locate();
  },

  _initPermalink: function () {
    var _this = this;
    this.hash = L.PolarMap.Util.hash(this.map, {
      getBaseLayer: function () {
        return _this.getBaseLayer().options.name;
      },

      setBaseLayer: function (name) {
        _this._setBaseLayer(name);
      }
    });
  },

  _setBaseLayer: function (name) {
    var _this = this;

    for (var layer in this.tiles) {
      if (this.tiles.hasOwnProperty(layer)) {
        if (this.tiles[layer].options.name === name) {
          _this.map.loadTileProjection(this.tiles[layer]);
        }
      }
    }
  },

  _setProjectionForLongitude: function (longitude) {
    var value;
    if (longitude >= -180 && longitude <= -165) {
      value = "EPSG:3571";
    } else if (longitude > -165 && longitude <= -125) {
      value = "EPSG:3572";
    } else if (longitude > -125 && longitude <= -70) {
      value = "EPSG:3573";
    } else if (longitude > -70 && longitude <= -15) {
      value = "EPSG:3574";
    } else if (longitude > -15 && longitude <= 50) {
      value = "EPSG:3575";
    } else if (longitude > 50 && longitude <= 135) {
      value = "EPSG:3576";
    } else {
      value = "EPSG:3571";
    }

    this.map.loadTileProjection(getTileLayerForProjection(value));
  }
});

window.polarMap = function (id, options) {
  return new window.PolarMap(id, options);
};


// Initialization
var locations = [
  { coordinates: [47.4815233, 8.4006206], href: "http://www.openstreetmap.org/node/1708613061" },
  { coordinates: [62.4538585, -114.3718282], href: "http://www.openstreetmap.org/node/3151501272" },
  { coordinates: [62.7810841, 40.3958394], href: "http://www.openstreetmap.org/node/1378696917" },
  { coordinates: [69.6466147, -141.0006022], href: "http://www.openstreetmap.org/node/244247661" },
  { coordinates: [64.153367, -21.9922], href: "http://www.openstreetmap.org/node/1565448715" },
  { coordinates: [51.5464344, -0.3257602], href: "http://www.openstreetmap.org/node/31472679" },
  { coordinates: [60.1720912, 24.9388441], href: "http://www.openstreetmap.org/node/1277737569" },
  { coordinates: [70.7880648, -53.654276], href: "http://www.openstreetmap.org/node/3665355722" },
  { coordinates: [72.3955761, 126.657488], href: "http://www.openstreetmap.org/node/1363089097" }
];

$(document).ready(function() {
  // Fill Select element
  $.each(locations, function(index, location) {
    var $element = $("<option></option>")
      .val(index)
      .text(location.coordinates.toString());
    $("#locations-list").append($element);
  });

  // Setup Maps
  var osmMap = L.map("osm");
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(osmMap);

  var pMap = polarMap("polar");

  osmMap.setView([51, -114], 2);
  pMap.map.setView([51, -114], 2);

  // Have to create a separate marker for each map else weirdness happens
  function addToMap(location, map) {
    var marker = L.marker(location.coordinates);
    marker.addTo(map);
  }

  $.each(locations, function(index, location) {
    addToMap(location, osmMap);
    addToMap(location, pMap);
  });

  // Sync maps
  var syncInProgress = false;

  osmMap.on("moveend", function() {
    if (!syncInProgress) {
      syncInProgress = true;
      pMap.map.setView(osmMap.getCenter(), osmMap.getZoom());
      setTimeout(function() { syncInProgress = false; }, 1000);
    }
  });

  pMap.map.on("moveend", function() {
    if (!syncInProgress) {
      syncInProgress = true;
      osmMap.setView(pMap.map.getCenter(), pMap.map.getZoom());
      setTimeout(function() { syncInProgress = false; }, 1000);
    }
  });

  // Select change event
  $("#locations-list").on("change", function() {
    var index = $(this).val();
    var location = locations[index];
    if (location) {
      osmMap.setView(L.latLng(location.coordinates), 18);
      pMap.map.setView(L.latLng(location.coordinates), 18);
    }
  });
});


var map;

// Create object to define tile provider settings and transformations. Supports
// all Leaflet TileLayer options.
var projectedTiles = {
  "EPSG:3571 Bering Sea": L.PolarMap.layer3571,
  "EPSG:3572 Alaska"    : L.PolarMap.layer3572,
  "EPSG:3573 Canada"    : L.PolarMap.layer3573,
  "EPSG:3574 Atlantic"  : L.PolarMap.layer3574,
  "EPSG:3575 Europe"    : L.PolarMap.layer3575,
  "EPSG:3576 Russia"    : L.PolarMap.layer3576
};

// Set up next/prev linked list
$.each(projectedTiles, function (layerName, layer) {
  var keys = Object.keys(projectedTiles);
  var index = keys.indexOf(layerName);
  var prev = (index === 0) ? keys.length - 1 : index - 1;
  var next = (index === keys.length - 1) ? 0 : index + 1;

  layer.prev = projectedTiles[keys[prev]];
  layer.next = projectedTiles[keys[next]];
});

// Initialization
$(document).ready(function() {
  Autosize.enable();

  // Load PolarMap
  map = L.PolarMap.map('xmap', {
    baseLayer: projectedTiles["EPSG:3571 Bering Sea"],
    center: [90, 0],
    zoom: 2
  });

  var layersControl = L.control.layers(projectedTiles, null);
  layersControl.addTo(map);

  // Add shapefiles
  var boundsLimit = L.latLngBounds([45,-180], [90,180]);

  // Options are the same as given to L.GeoJson
  var popPlaces = L.shapefile("ne_110m_populated_places_simple", {
    onEachFeature: function (feature, layer) {
      layer.bindPopup(feature.properties.name);
    },
    // avoid loading features South of 45N. Errors will occur when loading
    // Antarctic data.
    filter: function (featureData, layer) {
      var coords = featureData.geometry.coordinates;
      return boundsLimit.contains(L.latLng([coords[1], coords[0]]));
    }
  });

  map.addLayer(popPlaces);
  layersControl.addOverlay(popPlaces, "Populated Places");

  var glaciated = L.shapefile("ne_110m_glaciated_areas", {
    // avoid loading features South of 45N. Errors will occur when loading
    // Antarctic data.
    filter: function (featureData, layer) {
      var bbox = featureData.geometry.bbox;
      var llBounds = L.latLngBounds([bbox[1], bbox[0]], [bbox[3], bbox[2]]);
      return boundsLimit.contains(llBounds);
    }
  });

  map.addLayer(glaciated);
  layersControl.addOverlay(glaciated, "Glaciated Areas");

  // Wire up rotation controls
  var getBaseLayer = function() {
    var foundLayer = null;
    $.each(projectedTiles, function (layerName, layer) {
      if (map.hasLayer(layer)) {
        foundLayer = layer;
      }
    });
    return foundLayer;
  };

  var rotationControls = L.PolarMap.Control.rotation({
    onRotateCW: function() {
      map.loadTileProjection(getBaseLayer().next);
    },

    onRotateCCW: function() {
      map.loadTileProjection(getBaseLayer().prev);
    }
  });
  rotationControls.addTo(map);

  // Set location hash
  var hash = L.PolarMap.Util.hash(map, {
    getBaseLayer: function () {
      return getBaseLayer().options.name;
    },

    setBaseLayer: function (name) {
      $.each(projectedTiles, function (layerName, layer) {
        if (layer.options.name === name) {
          map.loadTileProjection(layer);
        }
      });
    }
  });
});


var toFn = require('to-function')
var extend = require('xtend')

/**
 * Page collection defaults.
 *
 * @type {Object}
 */
var DEFAULTS = {
  perPage: 10,
  noPageOne: false
}

/**
 * Paginate based on the collection.
 *
 * @param  {Object}   options
 * @return {Function}
 */
module.exports = function (options) {
  var keys = Object.keys(options)

  return function (files, metalsmith, done) {
    var metadata = metalsmith.metadata()

    // Iterate over all the paginate names and match with collections.
    var complete = keys.every(function (name) {
      var collection

      // Catch nested collection reference errors.
      try {
        collection = toFn(name)(metadata)
      } catch (error) {}

      if (!collection) {
        done(new TypeError('Collection not found (' + name + ')'))

        return false
      }

      var pageOptions = extend(DEFAULTS, options[name])
      var toShow = collection
      var groupBy = toFn(pageOptions.groupBy || groupByPagination)

      if (pageOptions.filter) {
        toShow = collection.filter(toFn(pageOptions.filter))
      }

      if (!pageOptions.template && !pageOptions.layout && !pageOptions.pageContents) {
        done(new TypeError('A template, layout or pageContents option is required (' + name + ')'))

        return false
      }

      if (pageOptions.template && pageOptions.layout) {
        done(new TypeError(
          'Template and layout can not be used simultaneosly (' + name + ')'
        ))

        return false
      }

      if (!pageOptions.path) {
        done(new TypeError('The path is required (' + name + ')'))

        return false
      }

      // Can't specify both
      if (pageOptions.noPageOne && !pageOptions.first) {
        done(new TypeError(
          'When `noPageOne` is enabled, a first page must be set (' + name + ')'
        ))

        return false
      }

      // Put a `pages` property on the original collection.
      var pages = collection.pages = []
      var pageMap = {}

      // Sort pages into "categories".
      toShow.forEach(function (file, index) {
        var name = String(groupBy(file, index, pageOptions))

        // Keep pages in the order they are returned. E.g. Allows sorting
        // by published year to work.
        if (!pageMap.hasOwnProperty(name)) {
          // Use the index to calculate pagination, page numbers, etc.
          var length = pages.length

          var pagination = {
            name: name,
            index: length,
            num: length + 1,
            pages: pages,
            files: [],
            getPages: createPagesUtility(pages, length)
          }

          // Generate the page data.
          var page = extend(pageOptions.pageMetadata, {
            template: pageOptions.template,
            layout: pageOptions.layout,
            contents: pageOptions.pageContents || Buffer.from(''),
            path: interpolate(pageOptions.path, pagination),
            pagination: pagination
          })

          // Copy collection metadata onto every page "collection".
          pagination.files.metadata = collection.metadata

          if (length === 0) {
            if (!pageOptions.noPageOne) {
              files[page.path] = page
            }

            if (pageOptions.first) {
              // Extend the "first page" over the top of "page one".
              page = extend(page, {
                path: interpolate(pageOptions.first, page.pagination)
              })

              files[page.path] = page
            }
          } else {
            files[page.path] = page

            page.pagination.previous = pages[length - 1]
            pages[length - 1].pagination.next = page
          }

          pages.push(page)
          pageMap[name] = pagination
        }

        // Files are kept sorted within their own category.
        pageMap[name].files.push(file)
      })

      // Add page utilities.
      pages.forEach(function (page, index) {
        page.pagination.first = pages[0]
        page.pagination.last = pages[pages.length - 1]
      })

      return true
    })

    return complete && done()
  }
}

/**
 * Interpolate the page path with pagination variables.
 *
 * @param  {String} path
 * @param  {Object} data
 * @return {String}
 */
function interpolate (path, data) {
  return path.replace(/:(\w+)/g, function (match, param) {
    return data[param]
  })
}

/**
 * Group by pagination by default.
 *
 * @param  {Object} file
 * @param  {number} index
 * @param  {Object} options
 * @return {number}
 */
function groupByPagination (file, index, options) {
  return Math.ceil((index + 1) / options.perPage)
}

/**
 * Create a "get pages" utility for people to use when rendering.
 *
 * @param  {Array}    pages
 * @param  {number}   index
 * @return {Function}
 */
function createPagesUtility (pages, index) {
  return function getPages (number) {
    var offset = Math.floor(number / 2)
    var start, end

    if (index + offset >= pages.length) {
      start = Math.max(0, pages.length - number)
      end = pages.length
    } else {
      start = Math.max(0, index - offset)
      end = Math.min(start + number, pages.length)
    }

    return pages.slice(start, end)
  }
}