var lineAddListener;
var polyAddListener;
var polygons = Array();
var polygonNumber = 0;

function lqpPolygon(marker) {
	this.marker = marker;
	this.points = Array();
	this.points.push(marker.getLatLng());
	this.overlays = Array();
	this.active = false;
	
	this.overlays.push(marker);
}

lqpPolygon.prototype.AddLine = function(point, gmap) {
	this.points.push(point);
	var line = getNewLine(this.points[this.points.length-2], this.points[this.points.length-1]);
	this.overlays.push(line);
	if (this.points.length == 3) ShowToolTip("Click to add additional points or click the marker to finish");
	gmap.addOverlay(line);
}

lqpPolygon.prototype.Finish = function(gmap) {
	if (this.points.length < 3)
		return false;
	this.AddLine(this.points[0], gmap);
	this.active = true;
	polyAddListener = false;
	ShowToolTip("");
	return true;
}

lqpPolygon.prototype.Destroy = function(gmap) {
	jQuery.each(this.overlays, function() {
		gmap.removeOverlay(this);
	});
	this.active = false;
}


function createPolyMarker(point) {
	// Create a lettered icon for this point using our icon class
	var icon = new GIcon(baseIcon);
	icon.image = "http://www.google.com/mapfiles/markerX.png";
	var marker = new GMarker(point, icon);
	marker.lqpPolygonID = polygonNumber++;
	var thisListener = GEvent.addListener(marker, "click", function() {
		if (polygons[this.lqpPolygonID].Finish(map))
		{
			GEvent.removeListener(thisListener);
			GEvent.removeListener(lineAddListener);
			
			var destructListener = GEvent.addListener(this, "click", function() {
				GEvent.removeListener(destructListener);
				polygons[this.lqpPolygonID].Destroy(map);
			});
			
			//polyAddListener = addPolygonListener();
		}
	});
	return marker;
}


function addPolygonListener() {
	ShowToolTip("Click on the map to begin your polygon");
	return GEvent.addListener(map, 'click', function(overlay, latlng) {
		if (latlng) {
			GEvent.removeListener(polyAddListener); //suppress the current listener
			var polymarker = createPolyMarker(latlng);
			map.addOverlay(polymarker);
			polygons.push(new lqpPolygon(polymarker));
			lineAddListener = GEvent.addListener(map, 'click', function(overlay, latlng) {
				if (latlng) polygons[polygons.length-1].AddLine(latlng, map);
			});
			ShowToolTip("Click to add additional points");
		}
	});
}


function getNewLine(startPoint, endPoint) {
	return new GPolyline([startPoint, endPoint],'#00C000',3,1);
}
