var req = false;
var _self = false;
var markers = new Array();
var baseIcon = false;
var map;

function directoryMap () {
	this.map = false;
	this.kml = false;
	this.points = false;
	this.autozoom = false;
	this.controls = true;
	
	this.init = function (lat, lng, zoom) {
		_self = this;
		var self = this;
		this.map = new google.maps.Map2(document.getElementById("map"));
		
		
		var mt = this.map.getMapTypes();
		// Overwrite the getMinimumResolution() and getMaximumResolution() methods
		for (var i=0; i<mt.length; i++) {
			mt[i].getMinimumResolution = function() {return 10;}
			mt[i].getMaximumResolution = function() {return 12;}
		}
	  
		this.map.setCenter(new GLatLng(lat, lng), zoom);

		
		if (this.controls) {
			this.map.addControl(new GSmallMapControl());
			//this.map.addControl(new GMapTypeControl());
		}
		
		var overlay = new GGeoXml('http://www.foremanhomes.co.uk/static/foreman/overlay.kml?v3');
		this.map.addOverlay(overlay);
		
		// Add a move listener to restrict the bounds range
		
		GEvent.addListener(this.map, "move", function() {
			_self.checkBounds();
		});

		// The allowed region which the whole map must be within
		
		this.allowedBounds = new GLatLngBounds(new GLatLng(50.77255588302838,-1.418231162900252), new GLatLng(50.96963931796406,-1.1970652166687802));

		
		// Base Icon
		baseIcon = new GIcon();
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
		
		//this.loadKML(this.kml);
		this.loadPoints(this.kml);
		//}
		
	}
	
	// If the map position is out of range, move it back
	this.checkBounds = function () {
		// Perform the check and return if OK
		if (this.allowedBounds.contains(this.map.getCenter())) {
			return;
		}
		
		// It`s not OK, so find the nearest allowed point and move there
		var C = this.map.getCenter();
		var X = C.lng();
		var Y = C.lat();

		var AmaxX = this.allowedBounds.getNorthEast().lng();
		var AmaxY = this.allowedBounds.getNorthEast().lat();
		var AminX = this.allowedBounds.getSouthWest().lng();
		var AminY = this.allowedBounds.getSouthWest().lat();

		if (X < AminX) {X = AminX;}
		if (X > AmaxX) {X = AmaxX;}
		if (Y < AminY) {Y = AminY;}
		if (Y > AmaxY) {Y = AmaxY;}
		//alert ("Restricting "+Y+" "+X);
		this.map.setCenter(new GLatLng(Y,X));
	}
	
	this.loadKML = function (url) {
		this.geoXml = new GGeoXml(url);
		this.map.addOverlay(this.geoXml);
	}
	
	this.loadPoints = function (url) {
		//var url = this.points + '&BBOX=' + this.map.getBounds();
		_self = this;
		// Create Google XmlHttpRequest object
		req = GXmlHttp.create();
			
		req.onreadystatechange = function () {
			if (req.readyState == 4) {
				if (req.status == 200) { 
					var bounds = new GLatLngBounds();
					var points = req.responseXML.getElementsByTagName("Placemark");
					
					if (points.length > 0) {
						//_self.map.clearOverlays();
						for (i=0; i<points.length; i++) {
							/*
								Create Marker
							*/
							var lat = points[i].getElementsByTagName('Point')[0].getElementsByTagName('latitude')[0].firstChild.data;
							var lng = points[i].getElementsByTagName('Point')[0].getElementsByTagName('longitude')[0].firstChild.data;
							var title = points[i].getElementsByTagName('name')[0].firstChild.data;
							var info = points[i].getElementsByTagName('description')[0].firstChild.data;
							var siteUrl = points[i].getElementsByTagName('url')[0].firstChild.data;
							var siteType = points[i].getElementsByTagName('type');
							
							
							
							// Create Marker
							var customIcon = new GIcon(baseIcon);
							//customIcon.image = icon[0].firstChild.data;
							switch (siteType[0].firstChild.data) {
								case 'site':
									customIcon.image = 'http://www.foremanhomes.co.uk/css/uploads/58/map-icon.png';
									customIcon.iconSize = new GSize(24, 24);
									customIcon.iconAnchor = new GPoint(12, 12);
								break;
								
								case 'soon':
									title = 'Coming Soon: ' + title;
									customIcon.image = 'http://www.foremanhomes.co.uk/css/uploads/58/map-icon-soon.png';
									customIcon.iconSize = new GSize(24, 24);
									customIcon.iconAnchor = new GPoint(12, 12);
								break;
								
								case 'previoussite':
									title = 'Previous Site: ' + title;
									customIcon.image = 'http://www.foremanhomes.co.uk/css/uploads/58/map-icon-old.png';
									customIcon.iconSize = new GSize(10, 10);
									customIcon.iconAnchor = new GPoint(5, 5);
								break;
							}
							customIcon.shadow = false;
							var markerOptions = { icon:customIcon, title:title, zIndexProcess:orderOfCreation };
							markers[i] = new GMarker(new GLatLng(lat, lng), markerOptions);
							
							switch (siteType[0].firstChild.data) {
								case 'site':
									GEvent.addListener(markers[i], "mouseover", showSite(points[i].getElementsByTagName('id')[0].firstChild.data));
									GEvent.addListener(markers[i], "mouseout", hideSite(points[i].getElementsByTagName('id')[0].firstChild.data));
									GEvent.addListener(markers[i], "click", openLink(siteUrl));
								break;
								
								default:
									GEvent.addListener(markers[i], "click", openLink(siteUrl));
								break;
							}
							
							// Extend Bounds
							bounds.extend(markers[i].getPoint());
							_self.map.addOverlay(markers[i]);
						}
						
						if (_self.autozoom) {
							_self.map.setZoom(_self.map.getBoundsZoomLevel(bounds));
							var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
							var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
							_self.map.setCenter(new GLatLng(clat,clng));
							_self.autozoom = false;
						}
					}
				}
			}
		}
	  
		req.open("GET", url,true);
		req.send(null);
	}
}

function openMarker (marker, title, info) {
	return function() {marker.openInfoWindowHtml('<div class="balloon" style="width:200px;"><div style="font-weight: bold; font-size: medium; margin-bottom: 0em;">' + title + '</div>' + info + '</div>');}
}

function openLink (link) {
	return function () {window.location = link;}
}

function showSite (link) {
	return function () { if (e = document.getElementById(link)) { e.style.display = 'block'; }}
}
function hideSite (link) {
	return function () { if (e = document.getElementById(link)) { e.style.display = 'none'; }}
}
function orderOfCreation(marker,b) {
	return 1;
} 
