var map;
var MapBookings = {
	locations: {},
	bookingPagesUrl: "/locations/",
	map_id: "",
	
	addLocation: function (location) {
		$.each(['name','info','lat','long','message'], function () {
			if (location[this] == undefined) {
				location[this] = '';
			}
		});
		
		if (this.locations[location.name] == undefined) {
			this.locations[location.name] = location;
			(function (el, url) {
			location = el.name.toLowerCase().replace(/ /g,"");
			jQuery.ajax({
				url: url + location,
				success: function (data) {
						el.message = data;
						el.message = el.message.replace(/([\s\S]*)<body([^>]*)>([\s\S]*)<\/body>([\s\S]*)/img, "$3");
						el.message = el.message.replace(/([\s\S]*)<script([^>]*)>([\s\S]*)<\/script>([\s\S]*)/img, "$1 $4");
					},
				error: function () {
					el.message = "Could not find and location information."
				}
			});
			})(this.locations[location.name],this.bookingPagesUrl);
		}
	},
	
	getLocation: function (name) {
		return this.locations[name];
	},
	
	loadMap: function (map_id) {
		dataLoaded = true;
		for(var i in this.locations) {
			if (this.locations[i].message == "") {
				dataLoaded = false;
			}
		}
		
		if (dataLoaded) {
			this.createMap(map_id);
		} else {
			var me = this;
			setTimeout(function () {me.loadMap(map_id)}, 10);
		}
	},
	
	createMap: function (map_id) {
		var myOptions = {
		  zoom: 7,
		  center: new google.maps.LatLng(-44.097719, 170.828883),
		  disableDefaultUI: true,
		  navigationControl: true,
		  scaleControl: true,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById(map_id), myOptions);
		
		for(var i in this.locations) {
			var message = " " + this.locations[i].message;
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(this.locations[i].lat, this.locations[i].long), 
				map: map,
				title: this.locations[i].name
			});
			this.addBubble(marker,message);
		}
	},
	
	addBubble: function (marker,message) {
		var infowindow = new google.maps.InfoWindow({
			content: message
		});
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
	}
}
