/**
 * @author jamesnicol
 */

// Creates a marker at the given point
function createMarker(point, lat, lon, city, country, institution) 
{
	var marker = new GMarker(point);
	var new_html = '<div style="font-size:10px;text-align:left;">'
	new_html += '<p>' + city + ', ' + country + '</p>';
	new_html += '<p>' + institution + '</p>';
	new_html += '</div>';
	GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(new_html);
	});
	return marker;
}

function google_map_load()
{

	if (GBrowserIsCompatible()) 
	{
		//Create new instance of Google Map
		var map = new GMap2(document.getElementById("google_map"));
		//Add small controls, up/down/left/right, zoom in/zoom out
		map.addControl(new GSmallMapControl());
		//Add random center for map
		map.setCenter(new GLatLng(0, 0), 0);
		//Set the map to Hybrid mode
		var x=map.getMapTypes();
		map.setMapType(x[2]);
		
		//create new instance of boundary markers
		var bounds = new GLatLngBounds();
		
		var col_num = 0;

//Download the XML file that contains the relevant point markers for an overlay
		GDownloadUrl("http://moc.barcodeoflife.net/member_map.php", function(data, responseCode) {
		  var xml = GXml.parse(data);
		  var markers = xml.documentElement.getElementsByTagName("marker");
		  //Loop through the markes and create overlay points and set the boundary zone
		  for (var i = 0; i < markers.length; i++) {
			var bold_lat = parseFloat(markers[i].getAttribute("lat"));
			var bold_lon = parseFloat(markers[i].getAttribute("lng"));
			var city = markers[i].getAttribute("city");
			var country = markers[i].getAttribute("country");
			var institution =markers[i].getAttribute("institution");
			var point = new GLatLng(bold_lat,bold_lon);
			var marker = createMarker(point, bold_lat, bold_lon, city, country, institution);
			map.addOverlay(marker);
			bounds.extend(point);
			var zoom_lvl = map.getBoundsZoomLevel(bounds);
			if(zoom_lvl > 5){ zoom_lvl = 5; }
			map.setZoom(zoom_lvl);
			var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
			var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
			map.setCenter(new GLatLng(clat,clng));
		  }
		});	
		$('loading').style.display = 'none';
		
	}
}

Behaviour.addLoadEvent(google_map_load);