var infowindow;

$(document).ready(function() {

	// Adjust the map size to fill the viewport
	$("#map").height($(window).height() - 20);
	$("#map").width($(window).width() - 40);

	plot();

});


function plot() {

	var centre = new google.maps.LatLng(spots[0].lat, spots[0].lng);
	var map = new google.maps.Map(document.getElementById("map"),{
		zoom:      13,
		center:    centre,
		mapTypeId: google.maps.MapTypeId.SATELLITE
	});

	var icon = new google.maps.MarkerImage(
		"/img/marker-gw.png",
		new google.maps.Size(16, 16), // Size
		new google.maps.Point(0, 0),  // Origin
		new google.maps.Point(8, 8)   // Anchor
	);

	var markerCluster = new MarkerClusterer(map, [], {gridSize: 20, maxZoom: 13});

	// Attempts at optimisation
	var ev = google.maps.event;
	var mp = google.maps;

	for (spot in spots) {
		markerCluster.addMarker(createmarker(map, spots[spot], icon, ev, mp));
	}

	scrollToId("map");

}


function createmarker(map, spot, icon, ev, mp) {

	var m = new mp.Marker({
		position: new mp.LatLng(spot.lat, spot.lng),
		title:    spot.name,
		icon:     icon
	});

	ev.addListener(m, 'click', function() {

		if (infowindow) {
			infowindow.close();
		}

		var description = "";
		if (spot.description) {
			description = spot.des;
		}

		infowindow = new mp.InfoWindow({
			content: "\
				<div class=\"infowindow\">\
					<div class=\"image\">\
						<img src=\"" + spot.img + "\" width=\"100\" height=\"100\" alt=\"\" />\
					</div>\
					<div class=\"name\">" + spot.nam + "</div>\
					<div class=\"description\">" + description + "</div>\
				</div>\
			"
		});

		infowindow.open(map, m);

	});

	return m;

}


function scrollToId(id) {
	$('html,body').animate(
		{
			scrollTop: $("#" + id).offset().top - 5
		},
		'slow'
	);
}

