﻿/*
ALL THE MAP BEHAVIOUR SHOULD BE DEFINED HERE
*/

MYAPP.containerIds = {
		map_canvas_id: 'map_canvas'
	};
MYAPP.mapObject = null;  // this will be initialized when the time is right - after DOM is loaded


/* startup function - called right after the DOM is loaded */
$(function() {
	// google map is initilized when this object is created
	var lMapObject = new MapObject();

	// we keep our enhanced map object in MYAPP
	MYAPP.mapObject = lMapObject;
});

// The object that will hold the actual google map
function MapObject() {
	var inner_map;
	return {
		// this is executed when the object is created .. see the '()' right after '}'
		map: function() {
			// load map
			inner_map = new GMap2(document.getElementById(MYAPP.containerIds.map_canvas_id));
			inner_map.setUIToDefault();
			inner_map.disableScrollWheelZoom();
			inner_map.addControl(new GOverviewMapControl());

			return inner_map;
		} (),
		// this will load all markers on the map
		loadMarkers: function(markers) {
			var lMarker;
			for (var i = 0; i < markers.length; i++) {

				lMarker = new EntityMarker(new GLatLng(markers[i].lat, markers[i].lng), markers[i].type, markers[i].text, markers[i].url, MarkerBehaviour.simple);

				// if you find this tricky - read about JS closures and loops
				GEvent.addListener(lMarker, "click", function(index) {
					return function() { MYAPP.queryManager.callQueryService(index); };
				} (markers[i].index));

				inner_map.addOverlay(lMarker);
			}
		},
		// we use this method when we don't know for sure that the map was initialized
		loadMarkersSafe: function(markers) {
			if (inner_map.isLoaded)
				this.loadMarkers(markers);
			else
			// we wait for the map to get loaded (setCenter has to be called for that)
				setTimeout(this.loadMarkersSafe(markers), 1000);
		},
		openInfoWindow: function(marker) {
			var lMarker = new EntityMarker(new GLatLng(marker.lat, marker.lng), marker.type, marker.text, marker.url, MarkerBehaviour.info_window);
			inner_map.addOverlay(lMarker);
		},
		openInfoWindowSafe: function(marker) {
			if (inner_map.isLoaded)
				this.openInfoWindow(marker);
			else
			// we wait for the map to get loaded (setCenter has to be called for that)
				setTimeout(this.openInfoWindowSafe(marker), 1000);
		},
		// get the actual GMap object
		getGMap: function() { return inner_map; }
	};
}
