window.onload = loadMap;
window.onunload = GUnload;
if (typeof MAPS_IMAGE_PATH == 'undefined'){
	var MAPS_IMAGE_PATH = '';
}

function loadMap() {
	if (GBrowserIsCompatible())
	  {
	  	$('mapWrapper').style.display = 'block';
	  
	  	// Initialise map & apply settings
		var map = new GMap2($('mapHolder'));
		map.addControl(new GSmallZoomControl());
		map.addControl(new GOverviewMapControl());
		map.addControl(new RecentreControl());
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();	
		GEvent.addListener(map, "load", addLoadingReport);
		
		// Optional iconImage property (src of main icon image)
		function School(initObj){
			this.id = initObj.id;
			this.title = initObj.title;
			this.address = initObj.address;
			this.phone = initObj.phone;
			this.location = initObj.location;
			
			// Icon
			if (typeof initObj.icon != 'undefined')
				{ this.icon = initObj.icon; }			
			else if (typeof initObj.iconImage != 'undefined')
				{ this.icon = new GIcon(this.icon, initObj.iconImage); }
			
			// Marker
			this.marker = Object.extend(new GMarker(this.location, this.icon), {
				parent: this,
				title: this.title,
				getInfoWindowHtml: function() { return this.parent.contactDetailsToHtml(); }
			});
		}
		
		School.prototype = {
			icon: new GIcon(G_DEFAULT_ICON),
		
			contactDetailsToHtml: function(){
				var html = '<div class="contactDetails">';
				html += '<strong>' + this.title + '</strong>';
				html += '<br />';
				html += this.address.toString();
				html += '<br />';
				html += '<strong>Phone:</strong> ' + this.phone;
				html += '</div>';
				return html;
			},			
			
			addToMap: function(map){
				map.addOverlay(this.marker);
			}
		};
		
		// Extend icon with new properties
		Object.extend(School.prototype.icon, {
			image: MAPS_IMAGE_PATH + '/images/maps/map_icon_image2.png',
			shadow: MAPS_IMAGE_PATH + '/images/maps/map_icon_shadow2.png',
			iconSize: new GSize(32, 35),
			shadowSize: new GSize(59, 35),
			iconAnchor: new GPoint(16, 35),
			infoWindowAnchor: new GPoint(16, 2),
			printShadow: MAPS_IMAGE_PATH + '/images/maps/map_icon_printShadow2.gif',
			transparent: MAPS_IMAGE_PATH + '/images/maps/map_icon_transparent2.png',
			imageMap: [0,16,2,8,8,2,11,1,21,0,28,5,31,10,32,19,30,25,28,27,24,30,16,35,10,30,6,28,1,23]
		});

		
		
		
		function Address(street, city, postcode){
			this.street = street;
			this.city = city;
			this.postcode = postcode;
		}
		
		Address.prototype = {
			toString: function() {
				return this.street + ', ' + this.city + ', ' + this.postcode;
			}
		};


		// Specific Schools
		var stokeNewington = new School ({
			id: stokeNewington,
			title: 'Stoke Newington Nursery',
			address: new Address('1 Cazenove Road', 'London', 'N16 6PA'),
			phone: '020 8 806 6279',
			location: new GLatLng(51.564279363282594, -0.07216215133666992),
			iconImage: MAPS_IMAGE_PATH + '/images/maps/map_icon_image2_SN.png'
		});

		var tottenham = new School ({
			id: tottenham,
			title: 'Tottenham Primary School &amp; Nursery',
			address: new Address('55 Coniston Road', 'London', 'N17 0EX'),
			phone: '020 8 885 3354',
			location: new GLatLng(51.6070369890419, -0.06554245948791504),
			iconImage: MAPS_IMAGE_PATH + '/images/maps/map_icon_image2_T.png'
		});
		
		
		var midPoint = getMidLatLng(stokeNewington.location, tottenham.location);
		map.setCenter(midPoint, 12);
		map.savePosition();
		
		stokeNewington.addToMap(map);
		tottenham.addToMap(map);

		//map.addOverlay(snMarker);
		//map.addOverlay(tMarker);
		
		// Preload images
		preloadGoogleImages();
		
		GEvent.addListener(map, "click", function(marker, point) {
			if (marker)
				{
					if (marker.getInfoWindowHtml)
						{
							marker.openInfoWindowHtml(marker.getInfoWindowHtml());
							//marker.showMapBlowup();
						}
				}
		});
		
		
	  } // end if GBrowserIsCompatible
  
  
  else
  	{
		var mapImg = Object.extend(document.createElement('img'), {
			src:MAPS_IMAGE_PATH + '/images/map_sm.png',
			alt:'London Map, showing Sunrise schools',
			width:240,
			height:148
		});
		$('mapWrapper').parentNode.insertBefore(mapImg, $('mapWrapper'));
	}
} // end loadMap



// Get middle point for two lattitude and longitude coordinates
function getMidLatLng(latLng1, latLng2){
	function getMidPoint(point1, point2){
		var pointMax = Math.max(point1, point2);
		var pointMin = Math.min(point1, point2);
		return pointMin + ((pointMax - pointMin) / 2);
	}
	
	var midLat = getMidPoint(latLng1.lat(), latLng2.lat());
	var midLng = getMidPoint(latLng1.lng(), latLng2.lng());
	
	return new GLatLng(midLat, midLng);
}



// Add 'Loading Map' report to map
function addLoadingReport(){
	// Text to display
	var loadingText = 'Loading Map...';
	
	// Create a new element
	var info = document.createElement('div');
	info.appendChild(document.createTextNode(loadingText));
	
	// Add id, so it can be accessed for CSS styling
	info.setAttribute('id', 'mapLoading');
	
	// Insert into document
	this.getContainer().insertBefore(info, this.getContainer().firstChild);
}




// Recentre map to start-point (Custom control)
function RecentreControl() {
}
RecentreControl.prototype = new GControl();

RecentreControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	
	var button = Object.extend(document.createElement('img'), {
		src:MAPS_IMAGE_PATH + '/images/maps/map_recentre.png',
		alt:'Re-Centre Map',
		title:'Re-Centre Map',
		width:17,
		height:17
	});
	button.style.cursor = "pointer";

  GEvent.addDomListener(button, "click", function() {
	map.returnToSavedPosition();
  });

  container.appendChild(button);
  map.getContainer().appendChild(container);
  return container;
}

RecentreControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 43));
}



// Images on the map to preload
function preloadGoogleImages(){
var googleImages = {
	imgRoot: 'http://www.google.com/intl/en_ALL/mapfiles/',
	altImgRoot: 'http://www.google.com/mapfiles/',
	
	preload: function(collection){
		var returnArray = [];
		collection.each(function(filename){
			returnArray.push(googleImages.imgRoot + filename);
		});
		preloadImages(returnArray);
	},
	
	infoWindow: ['iw_nw.png', 'iw_n.png', 'iw_ne.png', 'iw_e.png', 'iw_c.png', 'iw_w.png', 'iw_sw.png', 'iw_s.png', 'iw_se.png', 'iw_tap.png', 'close.gif'],
	
	infoWindowShadow: ['iws_nw.png', 'iws_n.png', 'iws_ne.png', 'iws_e.png', 'iws_c.png', 'iws_w.png', 'iws_sw.png', 'iws_s.png', 'iws_se.png', 'iws_tap.png']
};

googleImages.preload(googleImages.infoWindow);
googleImages.preload(googleImages.infoWindowShadow);
}


// Can be passed unlimited args of either src strings, or arrays of src strings
function preloadImages(){
	if (!document.images || arguments.length == 0)
		{ return false; }

	$A(arguments).each(function(img){
		if (typeof img == 'object')
			{
				img.each(function(subImg){
					var i = new Image; i.src = subImg;
				});
			}
		else
			{ var i = new Image; i.src = img; }
	});
}
