$(document).ready(function() {
	var map = null;
	var geocoder = null;
	var mgr = null;
	function initialize() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("book-clubs-map"));
			map.setCenter(new GLatLng(51.51045188624856, -0.1263427734375), 10);
			map.setCenter(new GLatLng(geoData.lat, geoData.lon), 10);
			map.addControl(new GLargeMapControl());
			geocoder = new GClientGeocoder();
			geocoder.setBaseCountryCode('UK');
		}
	}
	function showAddress(address) {
		if (geocoder && address.length > 1) {
			geocoder.getLatLng(
				address+',UK',
				function(point) {
					if (!point) {
						alert(address + " not found");
					} else {
						map.setCenter(point, 13);
					}
				}
			);
		}
	}
	
	function plotPoints() {
		//this function attempts to grab all the book club meeting locations via ajax and plots them on a map with all their details.
		$.get($('#rootpath').attr('href')+"/special/book-club-meeting-locations-2/", null, function(data){
			var allmarkers = new Array();
			$(data).find('book-club').each(function() {
				var thislatlng = null;
				thislatlng = $(this).find('location').text();
				if (thislatlng) {
					var matches = /([\d+.-]+),\s*([\d+.-]+)/.exec(thislatlng);
					if (matches) {
						var matches = matches[0].split(',');
						//matches[0].replace(/^\s+|\s+$/g, '');
						//matches[1].replace(/^\s+|\s+$/g, '');
						//window.console.log(matches[0]);
						var thismarker = new GMarker(new GLatLng(matches[0],matches[1]));
						var bookClub = {
							name: 			$(this).find('book-club-name').text(),
							book:			$(this).find('book').text(),
							author:			$(this).find('author').text(),
							venue:			$(this).find('venue').text(),
							address:		$(this).find('address').text(),
							meetingtime:	$(this).find('meeting-time').text(),
							meetingdays:	$(this).find('meeting-days').text(),
							url:			$(data).find('rootpath').text()+'/view-book-club/'+$(this).find('book-club-name').attr('handle')
						};
						
						var bookClubHtml = '<h4>'+bookClub.name+'</h4><p>Meeting at '+bookClub.venue+', '+bookClub.address+' <br/>'+bookClub.meetingdays+' at '+bookClub.meetingtime+'</p><p>Currently discussing <em>'+bookClub.book+'</em> by <em>'+bookClub.author+'</em></p><p><a href="'+bookClub.url+'">More details &raquo;</a></p><br />';
						GEvent.addListener(thismarker,"click",function() {
							thismarker.openInfoWindowHtml(bookClubHtml);
						});
						allmarkers.push(thismarker);
					}
				}
			});
			var mgrOptions = { borderPadding: 100, maxZoom: 25, trackMarkers: true };
			var mgr = new MarkerManager(map,mgrOptions);
			mgr.addMarkers(allmarkers,0,25);
			mgr.refresh();
		});
	}
	
	initialize();
	plotPoints();
	$("#search-address-form").submit(function() {
		showAddress($('#search-address').val());
		return false;
	});
});