var northampton = {
	
	map : null
	
	, cols : ["#ff0000", "#00ff00"]
	
	, updateMapLayers : function (anchor) {
		
		if(!anchor) {
			return false;
		}
				
		//clear any old layers
		this.clearMapLayers();
		
		//ajax to server for new layers
		pointList = this.fetchPointList(anchor.id);		
						
	}
	
	, clearMapLayers : function () {
		this.map.clearOverlays();
	}
	
	, fetchPointList : function (mapCategory) {
		
		$.ajax({
			  url      : '/why/maplocations/' + mapCategory + '/'
			, dataType : 'json'
			, success  : northampton.drawPointList
		});		
	}
	
	
	, drawPointList : function (data,textStatus) {
		
		if(0 === data.points.length) {
			return false;
		}	
			
		for(i in data.points)
		{
			var thisPoint = data.points[i];
			var thisMarker = new GMarker(new GLatLng(thisPoint.lat,thisPoint.lon));
			var desc = null == thisPoint.description ? '' : thisPoint.description;
			thisMarker.bindInfoWindowHtml('<h5>' + thisPoint.title + ' </h5><p>' + desc + '</p>');
			northampton.map.addOverlay(thisMarker);
		}
		
		northampton.centreMap(data.points);
		
		var catTitle = data.category.title;
		if(null === data.category.description) {
			var catDesc = '';
		} else {
			var catDesc = data.category.description;
		}
		$('#gmap-meta *').each(function() { $(this).remove(); } );
		$('#gmap-meta').html('<h5>'+catTitle+'</h5><p class="intro">'+catDesc+'</p>');
		
	
	}
	
	, centreMap : function (pointList) {
		
		var latMin = Number.MAX_VALUE;
		var latMax = Number.MIN_VALUE;
		var lonMin = Number.MAX_VALUE;
		var lonMax = Number.MIN_VALUE;
				
		for (i in pointList)  {
			latMin = pointList[i].lat < latMin ? Number(pointList[i].lat) : Number(latMin);
			lonMin = pointList[i].lon < lonMin ? Number(pointList[i].lon) : Number(lonMin);
			                                     
			latMax = pointList[i].lat > latMax ? Number(pointList[i].lat) : Number(latMax);
			lonMax = pointList[i].lon > lonMax ? Number(pointList[i].lon) : Number(lonMax);	
		}

		latAvg = ((latMax + 0) + (latMin - 0)) / 2;
		lonAvg = ((lonMax + 0) + (lonMin - 0)) / 2;

		northampton.map.panTo(new GLatLng(latAvg,lonAvg));
		northampton.map.setZoom(7);
	}
	
	, handleHubplacesResponse : function (data,textStatus) {
		if(0 === data.hubs.length) {
			return false;
		}
		
		for(i in data.hubs) {
			
			var colour = northampton.cols[i];
			
			var thisHub = data.hubs[i];
			var hubLatLon = new GLatLng(thisHub.lat,thisHub.lon);
			var thisHubMarker = new GMarker(hubLatLon);
			northampton.map.addOverlay(thisHubMarker);
			var listOfLengths = '<ul>';
			
			//add its destination point, draw lines and compute their lengths
			for(j in thisHub.destinationplace) {
				var thisDest = thisHub.destinationplace[j];
				var destLatLon = new GLatLng(thisDest.lat,thisDest.lon);
				var thisDestMarker = new GMarker(destLatLon);
				
				northampton.map.addOverlay(thisDestMarker);
				thisHubMarker.bindInfoWindowHtml('<p>' + thisDest.title + '</p>');		
				
				var polyline = new GPolyline([hubLatLon, destLatLon], colour, 5);
				northampton.map.addOverlay(polyline);		
				
				//this is less accurate than it could be because we round twice, 
				//but we're not concerned for this usage.
				
				kmLength = Math.round(polyline.getLength() / 1000);
				mileLength = Math.round(northampton.km2m(kmLength));
				
				listOfLengths += 	'<li><strong>' + thisDest.title + '</strong>: ' + mileLength + ' miles ('+kmLength+' km)</li>';
						
			}
			
			listOfLengths += '</ul>';
			
			thisHubMarker.bindInfoWindowHtml('<h5>From ' + thisHub.title + ' to:</h5>' + listOfLengths);
			
			
		}
		
		northampton.map.setZoom(8);
		$('#gmap-meta *').each(function() { $(this).remove(); } );
		
	}
	
	, updateTransport : function () {
		
		northampton.clearMapLayers();
		
		$.ajax({
			  url      : '/hubplaces/'
			, dataType : 'json'
			, success  : northampton.handleHubplacesResponse
		});
	}
	
	, changeMenuState : function (menu, selectedElem) {
		
		$('#'+menu.attr('id')+' li').each(function (e) {
			//remove any previous selections
			if($(this).children('em').length === 1) {
				$(this).html($(this).children('em').html());
			}
			//test if this is current selection
			if($(this).children('a').attr('id') === selectedElem.id) {
				$(this).html('<em>' + $(this).html() + '</em>');
			}
			
		});
		
		northampton.addEventListeners();
	
	}
	
	, addEventListeners : function () {
		$('#gmap-controls li a').each(function (e) {
			$(this).click(function (e) {
				e.preventDefault();
				northampton.updateMapLayers(e.target);
				northampton.changeMenuState($('#gmap-controls'), e.target);
			});
		});

		$('#transport').unbind('click');

		$('#transport').click(function (e) {
				e.preventDefault();		
				northampton.updateTransport();
				northampton.changeMenuState($('#gmap-controls'), e.target);			
		});		
	}
	
	, km2m : function (km) {
		return 0.621371192237 * km;
	}
	
};

//onload.
$(function () {

	northampton.addEventListeners();

	//load map
	if(GBrowserIsCompatible()) {
		northampton.map = new GMap2(document.getElementById("map-canvas"));
		northampton.map.setCenter(new GLatLng(52.2378923494213, -0.89813232421875), 10);	
		northampton.map.addControl(new GLargeMapControl());
	}	
	
	//unbreak IE.
	$(window).unload(function () { GUnload(); });
	
});
