var radiusAddListener;
var circleAddListener;
var circles = Array();
var circleNumber = 0;

function lqpCircle(startPoint) {
	this.startPoint = startPoint;
	this.overlays = Array();
	this.active = false;
	
	this.overlays.push(startPoint);
}

lqpCircle.prototype.radiusPoint;

lqpCircle.prototype.Finish = function(point, gmap) {
	this.radiusPoint = point;
	this.DrawCircle(this.startPoint.getLatLng(), point, gmap);
	this.active = true;
	
	ShowToolTip("");
	var destructListener = GEvent.addListener(this.startPoint, "click", function() {
		GEvent.removeListener(destructListener);
		circles[this.lqpCircleID].Destroy(map);
	});
	
	//circleAddListener = addCircleListener();
	circleAddListener = false;
}

lqpCircle.prototype.Destroy = function(gmap) {
	$.each(this.overlays, function() {
		gmap.removeOverlay(this);
	});
	this.active = false;
}

lqpCircle.prototype.DrawCircle = function(centerPoint, radiusPoint, gmap) {
	var normalProj = G_NORMAL_MAP.getProjection();
	var zoom = gmap.getZoom();
	var centerPt = normalProj.fromLatLngToPixel(centerPoint, zoom);
	var radiusPt = normalProj.fromLatLngToPixel(radiusPoint, zoom);

	var circlePoints = Array();

	with (Math) {
		radius = floor(sqrt(pow((centerPt.x-radiusPt.x),2) + pow((centerPt.y-radiusPt.y),2)));

		for (var a = 0 ; a < 361 ; a+=10 ) {
			var aRad = a*(PI/180);
			var y = centerPt.y + radius * sin(aRad);
			var x = centerPt.x + radius * cos(aRad);
			var p = new GPoint(x,y);
			circlePoints.push(normalProj.fromPixelToLatLng(p, zoom));
		}
	}
	var circleLine = new GPolyline(circlePoints,'#00C000',2,1);
	gmap.addOverlay(circleLine);
	this.overlays.push(circleLine);
}

function createCircleMarker(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.lqpCircleID = index;
	return marker;
}

function addCircleListener() {
	ShowToolTip("Click to create the center of your circle");
	return GEvent.addListener(map, 'click', function(overlay, latlng) {
		if(latlng) {
			GEvent.removeListener(circleAddListener);
			
			var circleMarker = createCircleMarker(latlng, circleNumber++);
			map.addOverlay(circleMarker);
			circles.push(new lqpCircle(circleMarker));
			radiusAddListener = GEvent.addListener(map, 'click', function(overlay, latlng) {
				if (latlng) {
					circles[circles.length-1].Finish(latlng, map);
					GEvent.removeListener(radiusAddListener);
				}
			});
		}
		ShowToolTip("Now click to set the radius of your circle");
	});
}