var selectedIcon = "images/icons/marker_b.png";
var defaultIcon = "images/icons/marker.png";
var flexAppName = "main";

var geocoder;
var map;
var myMarkers;
var flexApp;

var userSelectedZoom = false;
var selected = -1;

function initializeMap() {
	if (GBrowserIsCompatible()) {
		myMarkers = new Array();
		// Initalize
		geocoder = new GClientGeocoder();
		
		// Create the map
		map = new GMap2(document.getElementById("map"));		
	    
		// Add controls
		map.addControl(new GLargeMapControl());
		
		// Set position
		map.setCenter(new GLatLng(40, -90), 4);
		
		// Populate the flex app
		if (navigator.userAgent.indexOf("MSIE") != -1) {
			flexApp = window[flexAppName];
		} else {
			flexApp = document[flexAppName];
		}
		
		// Add Event Listener for closing bubbles
		GEvent.addListener(map.getInfoWindow(), "closeclick", userClosedMarkerBubble);
		GEvent.addListener(map, "zoomend", function(){ userSelectedZoom = true;});
	}
}

function addMarker(num, longitude, latitude) {
	myMarkers[num] = new GMarker(new GLatLng(longitude, latitude), G_DEFAULT_ICON, false);
	
	function eventCallback() {
		flexApp.markerSelectedOnMap(num);
	}
	
	GEvent.addListener(myMarkers[num], "mousedown", eventCallback);
	map.addOverlay(myMarkers[num]);
}

function addMarkerUsingAddress(num, address) {
	function callback(point) {
		if (!point) {
			alert('Was unable to locate address: ' + address);
		} else {
			myMarkers[num] = new GMarker(point, G_DEFAULT_ICON, false);
			function eventCallback() {
				flexApp.markerSelectedOnMap(num);
			}
			GEvent.addListener(myMarkers[num], "mousedown", eventCallback);
			map.addOverlay(myMarkers[num]);
		}	
	}
	
	if (geocoder && map) {
		geocoder.getLatLng(address, callback);
	} else {
		alert("map or geocoder not yet loaded");
	}
}

function userClosedMarkerBubble() {
	flexApp.userClosedMarkerBubble();
	unsetMarkerSelected();
	selected = -1;
}

function setMarkerSelected(num) {
	myMarkers[num].setImage(selectedIcon);
	if(!userSelectedZoom)
		map.setCenter(myMarkers[num].getLatLng(), 6);
	selected = num;
}

function unsetMarkerSelected() {
	if(selected != -1)
		myMarkers[selected].setImage(defaultIcon);
}

function setMarkerBubble(num, string) {
	map.openInfoWindowHtml(myMarkers[num].getLatLng(), string);
}

function removeMarkerBubble() {
	map.closeInfoWindow();
}