L.Draw.Polygon = L.Draw.Polyline.extend({
	statics: {
		TYPE: 'polygon'
	},

	Poly: L.Polygon,

	options: {
		showArea: false,
		shapeOptions: {
			stroke: true,
			color: '#f06eaa',
			weight: 4,
			opacity: 0.5,
			fill: true,
			fillColor: null, //same as color by default
			fillOpacity: 0.2,
			clickable: true
		}
	},

	initialize: function (map, options) {
		L.Draw.Polyline.prototype.initialize.call(this, map, options);

		// Save the type so super can fire, need to do this as cannot do this.TYPE :(
		this.type = L.Draw.Polygon.TYPE;
	},

	_updateFinishHandler: function () {
		var markerCount = this._markers.length;

		// The first marker shold have a click handler to close the polygon
		if (markerCount === 1) {
			this._markers[0].on('click', this._finishShape, this);
		}

		// Add and update the double click handler
		if (markerCount > 2) {
			this._markers[markerCount - 1].on('dblclick', this._finishShape, this);
			// Only need to remove handler if has been added before
			if (markerCount > 3) {
				this._markers[markerCount - 2].off('dblclick', this._finishShape, this);
			}
		}
	},

	_getTooltipText: function () {
		var text, subtext;

		if (this._markers.length === 0) {
			text = L.drawLocal.draw.polygon.tooltip.start;
		} else if (this._markers.length < 3) {
			text = L.drawLocal.draw.polygon.tooltip.cont;
		} else {
			text = L.drawLocal.draw.polygon.tooltip.end;
			subtext = this._area;
		}

		return {
			text: text,
			subtext: subtext
		};
	},

	_shapeIsValid: function () {
		return this._markers.length >= 3;
	},

	_vertexAdded: function () {
		// Check to see if we should show the area
		if (this.options.allowIntersection || !this.options.showArea) {
			return;
		}

		var latLngs = this._poly.getLatLngs(),
			area = L.PolygonUtil.geodesicArea(latLngs);

		// Convert to most appropriate units
		if (area > 1000000) {
			area = (area * 0.000001).toFixed(2) + ' km&sup2;';
		} else if (area > 10000) {
			area = (area * 0.0001).toFixed(2) + ' ha';
		} else {
			area = area.toFixed(2) + ' m&sup2;';
		}

		this._area = area;
	},

	_cleanUpShape: function () {
		var markerCount = this._markers.length;

		if (markerCount > 0) {
			this._markers[0].off('click', this._finishShape, this);

			if (markerCount > 2) {
				this._markers[markerCount - 1].off('dblclick', this._finishShape, this);
			}
		}
	}
});
