var map;
var container;
var opacity = 0.3;
var circle;
var centerMarker;
var circleUnits;
var circleRadius;
var zoom = 2;
var centerPoint = new GLatLng(40,-100);

function load() {
	doLoad();
}


function doLoad() {
	if (GBrowserIsCompatible()) {
		container = document.getElementById("mapDiv");
		
		map = new GMap2(container, {draggableCursor:"crosshair"});
		geocoder = new GClientGeocoder();
		showAddress("Keilor Park Victoria Australia");
	}
}

function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					alert(address + " not found");
				} else {
					map.setCenter(point, 10);
					//var marker = new GMarker(point);
					//map.addOverlay(marker);
					map.addControl(new GScaleControl());
					map.addControl(new GLargeMapControl());
					map.addControl(new GMapTypeControl());
			
					map.enableScrollWheelZoom();		
			
					var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 620));
					drawCircle()
				}
			}
		);
	}
}		

function drawCircle() {

	circleRadius = 25;

	circleUnits = 'KM';


	doDrawCircle();
}



function doDrawCircle(){

	if (circle) {
		map.removeOverlay(circle);
	}


	if (centerMarker) {
		//map.setCenter(centerMarker.getLatLng())
	}
	else {
		//centerMarker = new GMarker(map.getCenter(),{draggable:true});
		//GEvent.addListener(centerMarker,"dragend",drawCircle)
		//map.addOverlay(centerMarker);
	}

	var center = map.getCenter();

	var bounds = new GLatLngBounds();

	
	var circlePoints = Array();

	with (Math) {
		if (circleUnits == "KM") {
			var d = circleRadius/6378.8;	// radians
		}
		else { //miles
			var d = circleRadius/3963.189;	// radians
		}

		var lat1 = (PI/180)* center.lat(); // radians
		var lng1 = (PI/180)* center.lng(); // radians

		for (var a = 0 ; a < 361 ; a++ ) {
			var tc = (PI/180)*a;
			var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
			var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
			var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
			var point = new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
			circlePoints.push(point);
			bounds.extend(point);
		}

		if (d < 1.5678565720686044) {
			circle = new GPolygon(circlePoints, "#6BB536", 2, 1, "#007D42", 0.25);	
		}
		else {
			circle = new GPolygon(circlePoints, "#6BB536", 2, 1);	
		}
		map.addOverlay(circle); 

		map.setZoom(map.getBoundsZoomLevel(bounds));
	}
}
