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

Function.prototype.bind = function() {
  var __method = this;
  var args = [];
  for(var i=0; i<arguments.length; i++) {
	args.push(arguments[i]);
  }
  var object = args.shift();
  return function() {
    return __method.apply(object, args.concat(arguments));
  }
}	

function load() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
	geocoder = new GClientGeocoder();
	bounds = new GLatLngBounds();

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

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(obj, response) {
	response = response[0];
  // map.clearOverlays();
  if (!response || response.Status.code != 200) {
	// if we can't find the address, knock the front off until we can
	/*
	current_address = current_address.split(',').slice(1).join(',');
	current_address = current_address.replace(/^\s+/,'').replace(/\s+$/,'');
	if (current_address.match(/,/)!=null) geocoder.getLocations(current_address, addAddressToMap);
	*/
    // alert("Sorry, we were unable to geocode that address");
	addMessage(obj.message);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    // map.addOverlay(marker);
	if (obj.is_search_location) {
		// Create our "tiny" marker icon
  		var blueIcon = new GIcon(G_DEFAULT_ICON);
  		blueIcon.image = "blank_marker_green.png";
		
		// Set up our GMarkerOptions object
		markerOptions = { icon:blueIcon };
        marker = new GMarker(point, markerOptions);
	}
	else {
		marker = new GMarker(point);
	}
	marker.bindInfoWindowHtml(place.address+'');
	markers.push(marker);
	bounds.extend(point);
  }
  processed_addresses++;
  showIt();
}

function addMessage(message) {
	document.getElementById('mapmessages').innerHTML += '<div>'+message+'<'+'/'+'div>';
}

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));
}

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++) {
		geocoder.getLocations(addresses[i].address, addAddressToMap.bind(this, {
			address: addresses[i].address,
			message: addresses[i].message,
			is_search_location: addresses[i].is_search_location
		}));
	}
}

function showIt() {
	if (processed_addresses>=addresses.length) {
		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';
		}
	}
}