$(document).ready(function() {
	$('#mapview_submit').click(function() {
		var location_id = $('#mapview_location').val();
		draw_map(location_id);
		return false;
	});
	
});

// This handles clicks on the map, moving the point and setting the lat/lng in the hidden fields.
function onClickPin() {
	
		console.log('got click on a pin');
	
		// if (point.lat != 0) {
		//     		mapstraction.removeAllMarkers();
		//     		mapstraction.addMarker( new Marker( new LatLonPoint(point.lat,point.lon)));
		// 
		// 	  	$('#id_2-latitude').val(point.lat);
		// $('#id_2-longitude').val(point.lng);
		// 
		// 	  	$('#message').html("Thank you. You can change your location as many times are you like until you're happy that we've got it right.");
		// }
}


function setup_map() {
	draw_map(12);
	
}





function draw_map(location_id) {

	// Get the default map on screen.
	var mapstraction = new Mapstraction('mapcontainer', 'google');


	// Focus the map on Manchester, setup the controls.
  	var manchester = new LatLonPoint(53.4805125, -2.2325765);
	mapstraction.setMapType(Mapstraction.TERRAIN);
 	mapstraction.setCenterAndZoom(manchester, 15);
	mapstraction.addControls( { pan: true, zoom: 'small', overview: false, scale: false, map_type: false } )

	// Clear all pins.
	mapstraction.removeAllMarkers();

	// Get the pins for this location.
	$.post("/home/locations/", {location: location_id}, function(response) {

		organisation_data = eval(response);

		$.each(organisation_data, function() {
			if (this.fields.lat && this.fields.long)
			{
				var bubbleText = "";
				var marker = new Marker(new LatLonPoint(this.fields.lat, this.fields.long));
				marker.setIcon('/static/images/map_icons/' + this.fields.slug + '.png');
				marker.setShadowIcon('/static/images/pushpin-shadow.png', new Array(43, 28));
				marker.setIconSize(new Array(29, 30));
				bubbleText = '<h3 class="maptitle"><a href="/organisation/' + this.fields.slug + '/">' + this.fields.name + '</a></h3><div class="mapaddr">';
				if (this.fields.address_1 != ""){
					bubbleText += this.fields.address_1 + ', ';
				}
				if (this.fields.address_2 != ""){
					bubbleText += this.fields.address_2 + ', ';
				}
				if (this.fields.address_3 != ""){
					bubbleText +=  this.fields.address_3 + ', ';
				}
				if (this.fields.post_code != ""){
					bubbleText += this.fields.post_code;
				}
				marker.setInfoBubble(bubbleText+'</div>');
        		mapstraction.addMarker(marker);

				if (location_id != 12)
				{
					// Move to contain all the pins.
					mapstraction.autoCenterAndZoom();
				}
			}
		});

	});    

}