var GoogleMaps = {
	map: undefined,
	locations: {},
	locationInfo: undefined,

	init: function () {
		//set eventhandlers on all the links
		$$('.maplocations a').addEvent('click', function () {
			GoogleMaps.goToLocation(this.get('href').split('#')[1]);
		});

		//initialize the map
		GoogleMaps.map = new google.maps.Map(document.id('map'), {
			zoom: 11,
			center: new google.maps.LatLng(52.369232, 4.894538),
			mapTypeId: google.maps.MapTypeId.ROADMAP
		});

		//initialize the infowindow
		GoogleMaps.locationInfo = new google.maps.InfoWindow()

		GoogleMaps.getLocations();
	},

	//get the markers
	getLocations: function () {
		var markerRequest = new Request.JSON({
			url: '/location/markers/',
			method: 'get',
			onComplete: function (responseJSON) {
				GoogleMaps.plotLocations(responseJSON);
			}
		});

		markerRequest.get();
	},

	//plot all the locations on the map
	plotLocations: function (locations) {
		var marker;

		locations.each(function (location) {
			marker = new google.maps.Marker({
				map: GoogleMaps.map,
				position: new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng))
			});

			var infoWindowHTML = new Element('div', {'class': 'infowindow', 'html': location.html}) 

			google.maps.event.addListener(marker, 'click', function () {
				GoogleMaps.locationInfo.setContent(infoWindowHTML);
				GoogleMaps.locationInfo.open(GoogleMaps.map, this);
			});

			GoogleMaps.locations[location.tag] = marker;
		});

		GoogleMaps.goToLocation(document.location.href.split('#')[1]);
	},

	//pan the map to a location defined by its tag
	goToLocation: function (locationTag) {
		if (GoogleMaps.locations[locationTag]) {
			GoogleMaps.map.setCenter(GoogleMaps.locations[locationTag].getPosition());
			google.maps.event.trigger(GoogleMaps.locations[locationTag], 'click');
		}
	} 
}

window.addEvent('domready', function () {
	if (document.id('map')) GoogleMaps.init();
});