             circle: false
             polygon:
               allowIntersection: false
-              showArea: true
+              showArea: false
         zoom:
           position: "topleft"
           zoomInText: ""

          widget.element.trigger 'mapeditor:feature_delete', layer.feature

        widget.update()

      this._resize()
      # console.log "resized"

#    $(this._getInnerContentContainer()).find('.modal-body > :first-child').replaceWith($content)
    $(this._getInnerContentContainer()).find('.modal-body').append($(content))
    this.update()

  # Portage from leaflet1.0.0-rc1: https://github.com/Leaflet/Leaflet/blob/master/src/layer/vector/Polygon.js
  # Return true centroid
  L.Polygon.include

    __getCenter: ->

      @projectLatlngs()
      @__project()
      points = @_rings[0]
      len = points.length
      if !len
        return null
      # polygon centroid algorithm; only uses the first ring if there are multiple
      area = x = y = 0
      i = 0
      j = len - 1
      while i < len
        p1 = points[i]
        p2 = points[j]
        f = p1.y * p2.x - (p2.y * p1.x)
        x += (p1.x + p2.x) * f
        y += (p1.y + p2.y) * f
        area += f * 3
        j = i++
      if area == 0
        # Polygon is so small that all points are on same pixel.
        center = points[0]
      else
        center = [
          x / area
          y / area
        ]
      @_map.layerPointToLatLng center

  L.Polyline.include
    getLatLngsAsArray: ->
      arr = []
      for latlng in @_latlngs
        arr.push [latlng.lat, latlng.lng]
      arr
    # Portage from leaflet1.0.0-rc1: https://github.com/Leaflet/Leaflet/blob/master/src/layer/vector/Polyline.js
    # Return true centroid
    __getCenter: ->
      @projectLatlngs()
      @__project()
      i = undefined
      halfDist = undefined
      segDist = undefined
      dist = undefined
      p1 = undefined
      p2 = undefined
      ratio = undefined
      points = @_rings[0]
      len = points.length
      if !len
        return null
      # polyline centroid algorithm; only uses the first ring if there are multiple
      i = 0
      halfDist = 0
      while i < len - 1
        halfDist += points[i].distanceTo(points[i + 1]) / 2
        i++
      # The line is so small in the current view that all points are on the same pixel.
      if halfDist == 0
        return @_map.layerPointToLatLng(points[0])
      i = 0
      dist = 0
      while i < len - 1
        p1 = points[i]
        p2 = points[i + 1]
        segDist = p1.distanceTo(p2)
        dist += segDist
        if dist > halfDist
          ratio = (dist - halfDist) / segDist
          return @_map.layerPointToLatLng([
            p2.x - (ratio * (p2.x - (p1.x)))
            p2.y - (ratio * (p2.y - (p1.y)))
          ])
        i++
      return

    __project: ->
      pxBounds = new (L.Bounds)
      @_rings = []
      @__projectLatlngs @_latlngs, @_rings, pxBounds
      w = @__clickTolerance()
      p = new (L.Point)(w, w)
      if @getBounds().isValid() and pxBounds.isValid()
        pxBounds.min._subtract p
        pxBounds.max._add p
        @_pxBounds = pxBounds
      return

    # recursively turns latlngs into a set of rings with projected coordinates
    __projectLatlngs: (latlngs, result, projectedBounds) ->
      flat = latlngs[0] instanceof L.LatLng
      len = latlngs.length
      i = undefined
      ring = undefined
      if flat
        ring = []
        i = 0
        while i < len
          ring[i] = @_map.latLngToLayerPoint(latlngs[i])
          projectedBounds.extend ring[i]
          i++
        result.push ring
      else
        i = 0
        while i < len
          @__projectLatlngs latlngs[i], result, projectedBounds
          i++
      return

    __clickTolerance: ->
      # used when doing hit detection for Canvas layers
      (@options.stroke ? @options.weight / 2 : 0) + (L.Browser.touch ? 10 : 0)

  L.Draw.Polyline.include
    __addHooks: L.Draw.Polyline.prototype.addHooks
    __removeHooks: L.Draw.Polyline.prototype.removeHooks

    __onMouseMove: (e) ->
      return unless @_markers.length > 0
      newPos = @_map.mouseEventToLayerPoint(e.originalEvent)
      mouseLatLng = @_map.layerPointToLatLng(newPos)

      latLngArray = []
      for latLng in @_poly.getLatLngs()
        latLngArray.push latLng
      latLngArray.push mouseLatLng

      # draw a polyline
      if @_markers.length == 1
        clone = L.polyline(latLngArray)

      # draw a polygon
      if @_markers.length >= 2

#        console.log("The distance is " + L.GeographicUtil.distance(lastLatLng, mouseLatLng.toArray()) + " m.")

        clone = L.polygon(latLngArray)

      clone._map = @_map
      center = clone.__getCenter()

      g = new L.GeographicUtil.Polygon(clone.getLatLngsAsArray())

      measure = {}
      measure['perimeter'] = g.perimeter()
      measure['area'] = g.area()
      console.log measure

      @__updateTooltipMeasure center, measure


    addHooks: () ->
      @__addHooks.apply this, arguments
      @__tooltipMeasure = new L.Tooltip @_map, onTop: true
      @_map.on 'mousemove', @__onMouseMove, this
      return

    removeHooks: () ->
      @_map.off 'mousemove'
      @__removeHooks.apply this, arguments
      return

    __updateTooltipMeasure: (latLng, measure = {}) ->
      showLength = @options.showLength
      labelText =
        text: ''
      distanceStr = undefined
      # TODO: use L.drawLocal to i18n tooltip
      ###if @_markers.length == 0
        labelText = text: L.drawLocal.draw.handlers.polyline.tooltip.start
      else
        distanceStr = if showLength then @_getMeasurementString() else ''
        if @_markers.length == 1
          labelText =
            text: L.drawLocal.draw.handlers.polyline.tooltip.cont
            subtext: distanceStr
        else
          labelText =
            text: L.drawLocal.draw.handlers.polyline.tooltip.end
            subtext: distanceStr###
      if measure['perimeter']
        labelText['text'] += "<span class='leaflet-draw-tooltip-measure perimeter'>#{measure['perimeter']}</span>"
        console.log labelText


      #TODO clean html with class
      if measure['area']
        labelText['text']  += "<span class='leaflet-draw-tooltip-measure area'>#{measure['area']}</span>"

        console.log labelText

      if latLng
        @__tooltipMeasure.updatePosition latLng
#      if !@_errorShown
        @__tooltipMeasure.updateContent labelText
      return

  L.Edit.Poly.include
    __addHooks: L.Edit.Poly.prototype.addHooks

    __onHandlerDrag: (e) ->
      new_poly = e.target
      latLngs = new_poly.getLatLngs()
      geod = GeographicLib.Geodesic.WGS84

      poly = geod.Polygon(false)
      for latlng in latLngs
        poly.AddPoint latlng['lat'], latlng['lng']

      poly = poly.Compute(false, true)
      console.log 'Perimeter/area of polygon are ' + poly.perimeter.toFixed(3) + ' m / ' + poly.area.toFixed(1) + ' m^2.'

    addHooks: () ->
      @__addHooks.apply this, arguments
      if @options.reactiveMeasure
        this._poly.on 'editdrag', @__onHandlerDrag, this


  L.Edit.Poly.mergeOptions
    reactiveMeasure: true

  L.LatLng.prototype.toArray = ->
    [@lat, @lng]

  L.Tooltip.include
    __initialize: L.Tooltip.prototype.initialize

    initialize: (map,options = {}) ->
      @__initialize.apply this, arguments

      if options.onTop
        L.DomUtil.addClass(@_container, 'leaflet-draw-tooltip-top')



  L.GeographicUtil = L.extend L.GeographicUtil || {},
    geod: GeographicLib.Geodesic.WGS84

# Use Karney distance formula
# ([lat, lng], [lat, lng]) -> Number (in meters)
    distance: (a, b) ->
      r = @geod.Inverse(a[0], a[1], b[0], b[1])
      r.s12.toFixed(3)

    Polygon: (points) -> # (Array of [lat,lng] pair)
      @geod = GeographicLib.Geodesic.WGS84
      @poly = @geod.Polygon(false)
      for point in points
        @poly.AddPoint point[0], point[1]

      @poly = @poly.Compute(false, true)
      return

  L.GeographicUtil.Polygon.prototype =
    perimeter: ->
      @poly.perimeter
    area: ->
      @poly.area



  $.widget "ui.mapeditor",
