var rectangleFinishListener;
var rectangleAddListener;
var rectangles = Array();
var rectangleNumber = 0;

function lqpRectangle(startPoint) {
	this.startPoint = startPoint;
	this.midPointLL;
	this.overlays = Array();
	this.active = false;
	
	this.overlays.push(startPoint);
}

lqpRectangle.prototype.Finish = function(point, gmap) {
	this.DrawRectangle(this.startPoint.getLatLng(), point, gmap);
	this.midPointLL = point;
	this.active = true;
	
	ShowToolTip("");
	var destructListener = GEvent.addListener(this.startPoint, "click", function() {
		GEvent.removeListener(destructListener);
		rectangles[this.lqpRectangleID].Destroy(map);
	});
	
	//rectangleAddListener = addRectangleListener();
	rectangleAddListener = false;
}

lqpRectangle.prototype.Destroy = function(gmap) {
	$.each(this.overlays, function() {
		gmap.removeOverlay(this);
	});
	this.active = false;
}

lqpRectangle.prototype.DrawRectangle = function(basePoint, oppPoint, gmap) {

	var rectanglePoints = Array();
	
	rectanglePoints.push(basePoint);
	rectanglePoints.push(new GLatLng(basePoint.lat(), oppPoint.lng()));
	rectanglePoints.push(oppPoint);
	rectanglePoints.push(new GLatLng(oppPoint.lat(), basePoint.lng()));
	rectanglePoints.push(basePoint);
		
	var rectangleLine = new GPolyline(rectanglePoints,'#00C000',2,1);
	gmap.addOverlay(rectangleLine);
	this.overlays.push(rectangleLine);
}

function createRectangleMarker(point, index) {
	// 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.lqpRectangleID = index;
	return marker;
}

function addRectangleListener() {
	ShowToolTip("Click on the map to begin your rectangle");
	return GEvent.addListener(map, 'click', function(overlay, latlng) {
		if(latlng) {
			GEvent.removeListener(rectangleAddListener);
			
			var rectangleMarker = createRectangleMarker(latlng, rectangleNumber++);
			map.addOverlay(rectangleMarker);
			rectangles.push(new lqpRectangle(rectangleMarker));
			rectangleFinishListener = GEvent.addListener(map, 'click', function(overlay, latlng) {
				if (latlng) {
					rectangles[rectangles.length-1].Finish(latlng, map);
					GEvent.removeListener(rectangleFinishListener);
				}
			});
			ShowToolTip("Now add the other corner");
		}
	});
}