// ----------------
// Postcode Locator
// ----------------
var PCL = {
	
	postcodes: {},
	
	initialize: function (map_selector)
	{
		// load local search api
		if (typeof GlocalSearch !== 'undefined')
			this.localSearch = new GlocalSearch();

		// load map api
		if (GBrowserIsCompatible())
		{
			this.map = new GMap2(document.getElementById(map_selector));
			
			this.map.setMapType(G_SATELLITE_MAP);
			this.map.addControl(new GSmallMapControl());
			//this.map.addControl(new GMapTypeControl());
			this.map.setCenter(new GLatLng(54.622978,-2.592773), 10, G_NORMAL_MAP);
			
			// window.addEvent("unload",function () {
			// 	PCL.destroy();
			// });
		}
	},
	
	destroy: function ()
	{
		if (this.map) GUnload();
	},

	locate: function (postcode, callbackFunction)
	{
		this.localSearch.setSearchCompleteCallback(this, function () {
			if ( this.localSearch.results[0] )
			{
				var url = this.localSearch.results[0].url;
				var postcode = url.slice(
					url.indexOf('q=') + 2,
					url.indexOf('%2C+UK')).replace('\+',' ');
				
				if ( url.indexOf('latlng=') !== -1 )
					return; // something weird, let's skip it
				
				var resultLat = this.localSearch.results[0].lat;
				var resultLng = this.localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				
				callbackFunction(point,postcode);
			}
		});

		this.localSearch.execute(postcode + ", UK");
	},

	mark: function (point)
	{
		var marker = new GMarker(point);
		this.map.addOverlay(marker);
	},

	center: function (point)
	{
		this.map.setCenter(point, 15);
	},

	showOnMap: function (selector)
	{
		if ( typeof(this.map) == 'undefined' )
			return;
			
		var that = this;
		
		$(selector).each(function (i,el) {
			var postcode = $(el).text();
			var address = $(el).parent().parent().find('a[href^=/centres/]').html() + '<br>' + $(el).parent().html();
			var points = [];
			that.postcodes[postcode] = address;
			
			that.locate(postcode, function (point, postcode) {
				var marker = new GMarker(point, { icon: that.icon });
				
				that.map.addOverlay(marker);
				GEvent.addListener(marker, "click", function() {
					this.openInfoWindowHtml(that.postcodes[postcode]);
				});
				points.push(point);

				that.centerMap(points);
			});
			
		});
		
	},
	
	centerMap: function (points){
		var sum = {x: 0, y: 0};
		var bounds = { top: null, left: null, right: null, bottom: null};
		var i = 0;
		
		for (var j = 0; j < points.length; j++){
			v = points[j];
			sum.x = sum.x + v.x;
			sum.y = sum.y + v.y;
			i++;
			
			if ( !bounds.left || bounds.left < v.x )
				bounds.left = v.x;
			
			if ( !bounds.right || bounds.right > v.x )
				bounds.right = v.x;
			
			if ( !bounds.top || bounds.top > v.y )
				bounds.top = v.y;
			
			if ( !bounds.bottom || bounds.bottom < v.y )
				bounds.bottom = v.y;
		}
		
		var center = new GLatLng(sum.y / i, sum.x / i);
		var mapBounds = new GLatLngBounds(new GLatLng(bounds.bottom, bounds.right),
			new GLatLng(bounds.top, bounds.left));
		
		if (i > 1) {
			this.map.setCenter(center, this.map.getBoundsZoomLevel(mapBounds));
		} else {
			this.map.setCenter(center);
		}
		
	}
};

$(function() {
	
	if ( $('ul.show-on-map').length == 1) {
		$('#breadcrumbs').after('<div id="map" style="margin-top: 23px; height: 350px">&nbsp;</div>');
		PCL.initialize('map');
		PCL.showOnMap('ul.show-on-map .postcode');
	} else if ($('#pin-map')) {
		var el = $('#pin-down');
		PCL.initialize('pin-map');
		var postcode = el.text();
		var address = $(el).parent().html();
		var points = [];
		PCL.postcodes[postcode] = address;
		
		
		PCL.locate(postcode, function (point, postcode) {
			// var marker = new GMarker(point, { icon: PCL.icon });
			// 
			// PCL.map.addOverlay(marker);
			// GEvent.addListener(marker, "click", function() {
			// 	this.openInfoWindowHtml(PCL.postcodes[postcode]);
			// });
			points.push(point);

			PCL.centerMap(points);
		});
	}
});

