Event.observe(window, 'load', initialize);

var map = null;
var geocoder = null;
var brokerdata = null;
var distances = null;

function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(45.13555516012536, -62.666015625), 6);
		map.addControl(new GSmallMapControl());
		geocoder = new GClientGeocoder();
		brokerdata = document.getElementsByName("brokerdata");
		distances = new Array(brokerdata.length / 3);
	}
}

function computeZoom(point) {
	
	bounds = new GLatLngBounds(point, point);
	
	for ( var i = 0; i < brokerdata.length; i += 3) { // for each pair of lat long coordinates, test for distance from point
		var tempLatLng = new GLatLng(brokerdata[i].value,
				brokerdata[i + 1].value);
		var distance = point.distanceFrom(tempLatLng);
		distances[i / 3] = new Array(tempLatLng, distance, brokerdata[i+2].value);
	}
	distances.sort(sortDist);
	for ( var i = 0; i < minBrokers; i++) {
		bounds.extend(distances[i][0]);
	}
	distances = distances.slice(0, minBrokers);
	distances.sort(randOrd);
	return map.getBoundsZoomLevel(bounds);
}

function findBrokers(address) {
	if (geocoder) {
		geocoder.getLatLng(address, function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				var zoomLevel = computeZoom(point);
				map.setCenter(point, zoomLevel - 1);
				addMarkers();
				var ids = "";
				for (var i=0; i<minBrokers; i++) {
					ids += distances[i][2] + ",";
				}
				new Ajax.Updater('brokerList', '/modules/BrokerMap/updateBrokers.php?ids=' + ids);
			}
		});
	}
}

function addMarkers() {
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);

	// Creates a marker whose info window displays the letter corresponding
	// to the given index.
	function createMarker(point, index) {
		// Create a lettered icon for this point using our icon class
		var letter = String.fromCharCode("A".charCodeAt(0) + index);
		var letteredIcon = new GIcon(baseIcon);
		letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter
				+ ".png";

		// Set up our GMarkerOptions object
		markerOptions = {
			icon :letteredIcon
		};
		var marker = new GMarker(point, markerOptions);
		return marker;
	}
	
	for ( var i = 0; i < minBrokers; i++) {
		map.addOverlay(createMarker(distances[i][0], i));
	}
}

function sortDist(a, b) {
	return a[1] - b[1];
}

function randOrd(){
	return (Math.round(Math.random())-0.5);
}


