var map;
var CourseMap = {
	element: 'map',
	center_lat: null,
	center_lng: null,
	locations: null,
	exam: '',
	initialize: function() {
		CourseMap.initialize_icons();
		CourseMap.render();
		$(window).unload(GUnload);
	},
	render: function() { 
    if (GBrowserIsCompatible()) {
		CourseMap.compatible = true;
		map = new GMap2(document.getElementById(CourseMap.element));
		map.setCenter(new GLatLng(CourseMap.center_lat,CourseMap.center_lng), 8); 
		map.addControl(new GSmallMapControl());
		
		if (CourseMap.addresses !== null) {
			CourseMap.map_locations();
		}
    } 
  },
	initialize_icons: function() {
		regionIcon = new GIcon(); // region icon
		regionIcon.image = "/images/external/icon_googlemaps_marker.png";
		regionIcon.shadow = "/images/external/icon_googlemaps_marker_shadow.png";
		regionIcon.iconSize = new GSize(20, 34);
		regionIcon.shadowSize = new GSize(37, 34);
		regionIcon.iconAnchor = new GPoint(9, 34);
		regionIcon.infoWindowAnchor = new GPoint(9, 2);
		regionIcon.infoShadowAnchor = new GPoint(18, 25);
		locationIcon = new GIcon(); // location icon
		locationIcon.image = "/images/external/icon_googlemaps_marker.png";
		locationIcon.shadow = "/images/external/icon_googlemaps_marker_shadow.png";
		locationIcon.iconSize = new GSize(21, 33);
		locationIcon.shadowSize = new GSize(44, 33);
		locationIcon.iconAnchor = new GPoint(9, 33);
		locationIcon.infoWindowAnchor = new GPoint(9, 2);
		locationIcon.infoShadowAnchor = new GPoint(18, 25);		
	},
	map_locations: function() {
	  $.each(CourseMap.locations, function(){
	    var point = new GLatLng(this.lat, this.lng);
	    var marker = new GMarker(point, locationIcon);
	    var location_id = this.location_id;
	    // add the location marker
	    map.addOverlay(marker);
	    // when someone clicks a location, show the info box filled with courses.
	    GEvent.addListener(marker, "click", function(){
	      $.get('/courses-by-location/'+location_id+'/'+CourseMap.exam, function(html){
	        marker.openInfoWindowHtml(html);
	      });
	    });		
    });		
	}
}
