var map;
var geocoder;
var bounds;
var markers = new Array();
var addresses = new Array();

function init() {
  if (GBrowserIsCompatible()) {
	geocoder = new GClientGeocoder();
  }
}

function load() {
  if (GBrowserIsCompatible()) {
// console.log('loading map');
    map = new GMap2(document.getElementById("map"));
	bounds = new GLatLngBounds();

	map.setCenter(new GLatLng(0,0));
	map.addControl(new GLargeMapControl());
  }
}

function addAddressToMap(lat,lng,txt) {
	point = new GLatLng(lat,lng);
	var marker = new GMarker(point);
	marker.bindInfoWindowHtml(txt);
	markers.push(marker);
	bounds.extend(point);
	showIt();
}

function setZoom() {
	map.setZoom(map.getBoundsZoomLevel(bounds)-1);
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	map.setCenter(new GLatLng(clat,clng));
	map.savePosition();
}

function centerAtLocation(address) {
	geocoder.getLocations(address, function(response){
	  // map.clearOverlays();
	  if (!response || response.Status.code != 200) {
	    alert("Sorry, we were unable to geocode that address");
	  } else {
	    place = response.Placemark[0];
	    point = new GLatLng(place.Point.coordinates[1],
	                        place.Point.coordinates[0]);
		map.setCenter(point,5);
	  }
	});
}

function finishUp() {
	for (var i=0; i<addresses.length; i++) {
		var address = addresses[i];
		addAddressToMap(address.lat,address.lng,address.txt);
	}
}

function showIt() {
	if (markers.length>0) {
		mgr = new GMarkerManager(map);
		mgr.addMarkers(markers, 1);
		mgr.refresh();
		setZoom();
	}
	else {
		// if we don't have any markers on the map, hide it
		document.getElementById('map').style.display='none';
	}
}

init();

