function addEvent(obj, evType, fn, useCapture) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
 	}
 	else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}

google.load("maps", "2.x");
google.load("earth", "1");
// arrays to hold copies of the markers
var gmarkers = [];
// arrays to hold variants of the info window html with get direction forms open
var htmls = [];
var fromCentre_htmls = [];
var fromYours_htmls = [];

// functions that open the directions forms
function fromCentre(i) {
	gmarkers[i].openInfoWindowHtml(fromCentre_htmls[i],{maxWidth:240});
}
function fromYours(i) {
	gmarkers[i].openInfoWindowHtml(fromYours_htmls[i],{maxWidth:240});
}

function loadMap () {
	
	var map = document.getElementById("mapDiv");

	var baseIcon = new GIcon();
	baseIcon.image = "http://www.wales.info/nearby/ylw-pushpin.png";
	baseIcon.shadow = "http://www.wales.info/nearby/shadow-ylw-pushpin.png";
	baseIcon.iconSize = new GSize(32, 32);
	baseIcon.shadowSize = new GSize(49, 32);
	baseIcon.iconAnchor = new GPoint(5, 32);
	baseIcon.infoWindowAnchor = new GPoint(16, 2);
	baseIcon.infoShadowAnchor = new GPoint(5, 32);
	// baseIcon.image = "http://www.wales.info/nearby/arrow.png";
	// baseIcon.shadow = "http://www.wales.info/nearby/arrowshadow.png";
	// baseIcon.iconSize = new GSize(39, 34);
	// baseIcon.shadowSize = new GSize(39, 34);
	// baseIcon.iconAnchor = new GPoint(20, 34);
	// baseIcon.infoWindowAnchor = new GPoint(9, 2);
	// baseIcon.infoShadowAnchor = new GPoint(18, 25);

	var restIcon = new GIcon();
	restIcon.image = "http://www.wales.info/nearby/ico_restaurant.png";
	restIcon.iconSize = new GSize(20, 20);
	restIcon.iconAnchor = new GPoint(10, 10);
	restIcon.infoWindowAnchor = new GPoint(10, 10);

	var attractIcon = new GIcon();
	attractIcon.image = "http://www.wales.info/nearby/ico_attraction.png";
	attractIcon.iconSize = new GSize(20, 20);
	attractIcon.iconAnchor = new GPoint(10, 10);
	attractIcon.infoWindowAnchor = new GPoint(10, 10);

	var nnrIcon = new GIcon();
	nnrIcon.image = "http://www.wales.info/nearby/ico_nnr.gif";
	nnrIcon.iconSize = new GSize(35, 16);
	nnrIcon.iconAnchor = new GPoint(18, 8);
	nnrIcon.infoWindowAnchor = new GPoint(18, 8);

	var cadwIcon = new GIcon();
	cadwIcon.image = "http://www.wales.info/nearby/ico_cadw.png";
	cadwIcon.iconSize = new GSize(20,20);
	cadwIcon.iconAnchor = new GPoint(10, 10);
	cadwIcon.infoWindowAnchor = new GPoint(10, 10);

	var natIcon = new GIcon();
	natIcon.image = "http://www.wales.info/nearby/ico_nt.gif";
	natIcon.iconSize = new GSize(19, 16);
	natIcon.iconAnchor = new GPoint(10, 8);
	natIcon.infoWindowAnchor = new GPoint(10, 8);

	var ssaIcon = new GIcon();
	ssaIcon.image = "http://www.wales.info/nearby/ico_ssa.gif";
	ssaIcon.iconSize = new GSize(16, 21);
	ssaIcon.iconAnchor = new GPoint(8, 11);
	ssaIcon.infoWindowAnchor = new GPoint(8, 11);

	var bfaIcon = new GIcon();
	bfaIcon.image = "http://www.wales.info/nearby/ico_blueflag.gif";
	bfaIcon.iconSize = new GSize(16, 21);
	bfaIcon.iconAnchor = new GPoint(8, 11);
	bfaIcon.infoWindowAnchor = new GPoint(8, 11);

	var nmgwIcon = new GIcon();
	nmgwIcon.image = "http://www.wales.info/nearby/ico_nmgw.gif";
	nmgwIcon.iconSize = new GSize(25, 16);
	nmgwIcon.iconAnchor = new GPoint(12, 8);
	nmgwIcon.infoWindowAnchor = new GPoint(12, 8);

	var wtaIcon = new GIcon();
	wtaIcon.image = "http://www.wales.info/nearby/ico_star.gif";
	wtaIcon.iconSize = new GSize(16, 23);
	wtaIcon.iconAnchor = new GPoint(8, 12);
	wtaIcon.infoWindowAnchor = new GPoint(8, 12);

	var yhaIcon = new GIcon();
	yhaIcon.image = "http://www.wales.info/nearby/ico_yha.gif";
	yhaIcon.iconSize = new GSize(20, 20);
	yhaIcon.iconAnchor = new GPoint(10, 10);
	yhaIcon.infoWindowAnchor = new GPoint(10, 10);
	
	if (GBrowserIsCompatible()) {

		var i = 0;

		// A function to create the marker and set up the event window
		// Dont try to unroll this function. It has to be here for the function closure
		// Each instance of the function preserves the contends of a different instance
		// of the "marker" and "html" variables which will be needed later when the event triggers.    
		function createMarker(i, curr) {
			var marker;
			if (i==-1) { //if (curr.type == "B") {
				marker = new GMarker(centrePoint,baseIcon);
			} else if (curr.orglist.indexOf("CADW") != -1) {
				marker = new GMarker(curr.point,cadwIcon);
			} else if (curr.orglist.indexOf("CAD") != -1) {
				marker = new GMarker(curr.point,cadwIcon);
			} else if (curr.orglist.indexOf("WTA") != -1) {
				marker = new GMarker(curr.point,wtaIcon);
			} else if (curr.orglist.indexOf("SGA") != -1) {
				marker = new GMarker(curr.point,wtaIcon);
			} else if (curr.orglist.indexOf("NMGW") != -1) {
				marker = new GMarker(curr.point,nmgwIcon);
			} else if (curr.orglist.indexOf("SSA") != -1) {
				marker = new GMarker(curr.point,ssaIcon);
			} else if (curr.orglist.indexOf("BFA") != -1) {
				marker = new GMarker(curr.point,bfaIcon);
			} else if (curr.orglist.indexOf("CCW") != -1) {
				marker = new GMarker(curr.point,nnrIcon);
			} else if (curr.orglist.indexOf("NAT") != -1) {
				marker = new GMarker(curr.point,natIcon);
			} else if (curr.type == "R") {
				marker = new GMarker(curr.point,restIcon);
			} else {
				marker = new GMarker(curr.point,attractIcon);
			}

			var html = "<div class=\"bubble\">";
			if (i!=-1) {  //if (curr.type != "B") {
				if (curr.niceurl=="") {
					html += "<h1>" + curr.name + "</h1>\n";
				}else{
					html += "<h1><a href=\"" + curr.niceurl + "\">" + curr.name + "</a></h1>\n";
				}
				html += "<p>" + curr.desc + "</p>";
				// The info window version with the "from centre" form open (all hidden fields, button only)
				fromCentre_htmls[i] = html + '<br />Directions to here from:<br />&nbsp;&nbsp;<b>' + centreName + '</b>,<br />&nbsp;&nbsp;or <a href="javascript:fromYours(' + i + ')">your place</a>' +
					'<br /><form action="http://maps.google.com/maps" method="get"" target="_blank">' +
					'<input value="Get Directions" TYPE="SUBMIT">' +
					'<input type="hidden" name="saddr" value="' + mapLat + ',' + mapLng + "(" + centreName + ")" + '"/>' +
					'<input type="hidden" name="daddr" value="' + curr.point.lat() + ',' + curr.point.lng() + "(" + curr.name + ")" + '"/></div>';
				// The info window version with the "from your place" form open
				fromYours_htmls[i] = html + '<br />Directions to here from:<br />&nbsp;&nbsp;<a href="javascript:fromCentre(' + i + ')">' + centreName + '</a>,<br />&nbsp;&nbsp;or <b>your place</b>' +
					'<br />Start address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
					'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
					'<input value="Get Directions" TYPE="SUBMIT">' +
					'<input type="hidden" name="daddr" value="' + curr.point.lat() + ',' + curr.point.lng() + "(" + curr.name + ")" + '"/></div>';
				// The inactive version of the direction info
				html += '<br />Directions to here from:<br />&nbsp;&nbsp;<a href="javascript:fromCentre('+i+')">' + centreName + '</a>,<br />&nbsp;&nbsp;or <a href="javascript:fromYours('+i+')">your place.</a>';
				//html += '<br />Directions to here from: <a href="javascript:gmarkers['+i+'].openInfoWindowHtml(fromCentre_htmls['+i+'])">' + cname + '</a>, or <a href="javascript:fromYours('+i+')">your place.</a>';
				html += "</div>";
				htmls[i] = html;
				gmarkers[i] = marker;

				GEvent.addListener(marker, "click", function() {
				  marker.openInfoWindowHtml(html,{maxWidth:240});
				});
			} else {
				html += "<h1>" + centreName + "</h1>\n";
				html += '<br />Directions to here from <b>your place</b>:' +
					'<br />Start address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
					'<input type="text" SIZE=20 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
					'<input value="Get Directions" TYPE="SUBMIT">' +
					'<input type="hidden" name="daddr" value="' + mapLat + ',' + mapLng + "(" + centreName + ")" + '"/></div>';
				GEvent.addListener(marker, "click", function() {
				  marker.openInfoWindowHtml(html,{maxWidth:240});
				});
			}
			return marker;
		}

		function parseJson (doc) {
			var currMarker;
			var msg="";
            doc = "(" + doc + ")";
			var jsonData = eval(doc);
			for (var i = 0; i < jsonData.markers.length; i++) {
				//create marker with index i+1 to reserver i=0 for centre location.
				var marker = createMarker(i, jsonData.markers[i]);
				gmap.addOverlay(marker);
			}
		}     	

		gmap = new GMap2(map);
		gmap.setCenter ( new GLatLng(mapLat,mapLng), 10, G_PHYSICAL_MAP);
        gmap.addMapType(G_PHYSICAL_MAP);
		gmap.addMapType(G_SATELLITE_3D_MAP);
		//gmap.addControl( new GMapTypeControl()) ;
		gmap.addControl( new GHierarchicalMapTypeControl() );
		gmap.addControl( new GSmallMapControl() );
		gmap.addControl( new GOverviewMapControl(new GSize(80,80)) );
		gmap.enableDoubleClickZoom();
		gmap.enableContinuousZoom();
		gmap.enableScrollWheelZoom();

		GDownloadUrl("/nearby/nearby_json.asp?unique_id="+mapId+"&type="+mapType, function(data, responseCode) { 
			parseJson(data);
		});

		//createCentreMarker
		var centreMarker = createMarker(-1, null);
        gmap.addOverlay(centreMarker);

		GEvent.addDomListener(map, "DOMMouseScroll", wheelevent);
		map.onmousewheel = wheelevent;
		document.getElementById('resetMapLink').onclick = resetMap;
	} else {
		alert("Sorry, your browser cannot handle the true power of Google Maps");
	}
}

//----- Stop page scrolling if wheel over map ----
function wheelevent(e)
{
	if (!e) e = window.event;
	if (e.preventDefault) e.preventDefault();
	e.returnValue = false;
}
function resetMap() {
	if (gmap) gmap.returnToSavedPosition();
}

addEvent(window, 'load', loadMap, false);
window.onunload = GUnload;

function MM_preloadImages() { //v2.0
  if (document.images) {
    var imgFiles = MM_preloadImages.arguments;
    if (document.preloadArray==null) document.preloadArray = new Array();
    var i = document.preloadArray.length;
    with (document) for (var j=0; j<imgFiles.length; j++) if (imgFiles[j].charAt(0)!="#"){
      preloadArray[i] = new Image;
      preloadArray[i++].src = imgFiles[j];
  } }
}