/* map_function.js */

	var map;
	var mgr;
	var icons = {};
	var allmarkers = [];
	var centerLatitude = 56.4700;
	var centerLongitude = -5.9500;
	var startZoom = 10;
	var maptype = 1;
	var bus = "";
//	var attrmsg = "Z = ";

// === Some cookie parameters ===
	var cookiename = "mapstate";  // name for this cookie
	var expiredays = 0;          // number of days before cookie expiry

// === Look for the cookie ===
	if (document.cookie.length>0) {
		cookieStart = document.cookie.indexOf(cookiename + "=");
		if (cookieStart!=-1) {
			cookieStart += cookiename.length+1;
			cookieEnd=document.cookie.indexOf(";",cookieStart);
			if (cookieEnd==-1) {
			  cookieEnd=document.cookie.length;
			}
			cookietext = document.cookie.substring(cookieStart,cookieEnd);
			// == split the cookie text and create the variables ==
			bits = cookietext.split("|");
			centerLatitude = parseFloat(bits[0]);
			centerLongitude = parseFloat(bits[1]);
			startZoom = parseInt(bits[2]);
			maptype = parseInt(bits[3]);
		}
	}



	function load() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GLargeMapControl3D());
			map.addControl(new GOverviewMapControl());
			map.removeMapType(G_SATELLITE_MAP);
			map.removeMapType(G_HYBRID_MAP);
			map.addMapType(G_PHYSICAL_MAP);
			map.addControl(new GHierarchicalMapTypeControl());
			map.addControl(new GScaleControl());
			map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom, map.getMapTypes()[maptype]);
			map.getDragObject().setDraggableCursor("crosshair");
//			map.enableDoubleClickZoom();
			mgr = new MarkerManager(map);
			window.setTimeout(setupMullMarkers, 0);
		}
		// allow the user to click the map to create a marker or form
//		GEvent.addListener(map, "click", function(overlay, latlng) {
//			// create an HTML form element
//			var inputForm = document.createElement("form");
//			inputForm.setAttribute("action", "");
//			inputForm.onsubmit = function() {storeMarker(); return false;};
//
//			// retrieve the lat and long of the click point
//			var lng = latlng.lng();
//			var lat = latlng.lat();
//
//			inputForm.innerHTML = '<fieldset>'
//				+ '<legend>Your Location</legend>'
//				+ '<label for="bus">Enter your Business Name</label>'
//				+ '<input type="text" id="bus" value = "" />'
//				+ '<input type="text" readonly id="latitude" value= "' + lat + '" />'
//				+ '<input type="text" readonly id="longitude" value="' + lng + '" />'
//				+ '<input id="sub" type="submit" value="Save" />'
//				'</fieldset>';
//
//			map.openInfoWindow(latlng, inputForm);
//		});
//		alert ("Bounds are " + GBounds);
	}

	function loadSmallMap() {
		startZoom = 9;
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GLargeMapControl3D());
//			map.addControl(new GOverviewMapControl());
			map.removeMapType(G_SATELLITE_MAP);
			map.removeMapType(G_HYBRID_MAP);
			map.addMapType(G_PHYSICAL_MAP);
			map.addControl(new GHierarchicalMapTypeControl());
			map.addControl(new GScaleControl());
			map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom, map.getMapTypes()[maptype]);
			map.getDragObject().setDraggableCursor("crosshair");
//			map.enableDoubleClickZoom();
			mgr = new MarkerManager(map);
			window.setTimeout(setupMullMarkers, 0);
		}
	}


function storeMarker() {
	if (bus == "") {
		alert ("Please enter your business name");
		return false;
	}
	var lng = document.getElementById("longitude").value;
	var lat = document.getElementById("latitude").value;
	var bus = document.getElementById("bus").value
	var getVars = "?bus=" + bus
		+ "&lng= " + lng
		+ "&lat=" + lat;
	var request = GXmlHttp.create();

	// open the request to storeMarker.php on server
	request.open('GET', 'storeMarker.php' + getVars, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			// the request is complete

			var xmlDoc = request.responseXML;
			// retrieve the root document element (response)
			var responseNode = xmlDoc.documentElement;
			// retrieve the type attribute of the node
			var type = responseNode.getAttribute("type");

			// retrieve the content ofthe responseNode
			var content = responseNode.firstChild.nodeValue;

			//check to see if it was an error, or success
			if (type != 'success') {
				alert(content);
			} else {
				// create a new marker and add its info window
				var latlng = new GLatLng(parseFloat(lat), parseFloat(lng));
//				var iconImage = responseNode.getAttribute("icon");
				var marker = makeTempMarker(latlng, content, bus);
				map.addOverlay(marker);
				map.closeInfoWindow();
			}
		}
	}
	request.send(null);
	return false;
}

function makeTempMarker(latlng, content, bus) {
//		var icon = new GIcon();
//		icon.image = "icons/new.png";
//		icon.iconSize = new GSize(30,39);
//		icon.iconAnchor = new GPoint(15,39);
//		icon.infoWindowAnchor = new GPoint(15, 0);

		var marker = new GMarker(latlng, {draggable: true});
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(content);
		});
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});

		GEvent.addListener(marker, "dragend", function(GLatLng) {
			var lat = GLatLng.lat();
			var lng = GLatLng.lng();
			//	Now I need some Ajax to get these values saved
			changeMarker(bus, lat, lng);
			marker.openInfoWindowHtml("Name: " + bus + ",<br />Lat: " + lat+ ",<br />Long: " + lng);
		});
//	alert ("Create Temp Marker finished");
	return marker;
}

function changeMarker(bus, lat, lng) {
	var getVars = "?bus=" + bus
		+ "&lng= " + lng
		+ "&lat=" + lat;
	var request = GXmlHttp.create();
//alert ("getVars = " + getVars);
	// open the request to storeMarker.php on server
	request.open('GET', 'storemarker.php' + getVars, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			// the request is complete

			var xmlDoc = request.responseXML;
			// retrieve the root document element (response)
			var responseNode = xmlDoc.documentElement;
			// retrieve the type attribute of the node
			var type = responseNode.getAttribute("type");

			// retrieve the content ofthe responseNode
			var content = responseNode.firstChild.nodeValue;
		}
	}
	request.send(null);
	return false;
}
//	END OF STUFF FOR RECORDING LAT LONG

	function getIcon(images) {
//		alert ("images is " + images);
		var icon = null;
		if (images) {
			if (icons[images[0]]) {
				icon = icons[images[0]];
			} else {
//				alert ("We are here");
				icon = new GIcon();
				icon.image = "/maps5/icons/" + images[0] + ".png";
				var size = iconData[images[0]];
				icon.iconSize = new GSize(size.width, size.height);
				icon.iconAnchor = new GPoint(size.x, size.y);
//				icon.z = size.z;
				icon.infoWindowAnchor = new GPoint(12,12);
				icons[images[0]] = icon;
			}
		}
		return icon;
	}

	function setupMullMarkers() {
		if (typeof(moremarkers) !== 'undefined') {
			markerLayer.push(moremarkers);
		}
		allmarkers.length = 0;
		for (var i in markerLayer) {
			var layer = markerLayer[i];
			var markers = [];
			for (var j in layer["places"]) {
				var place = layer["places"][j];
if (place["icon"]) {
				var icon = getIcon(place["icon"]);
} else {
	alert ("Icon " + place["icon"] + " not found");
}				// place[icon] points to an icon in mullMarkers var iconData (=images in getIcon())
				var title = place["name"];
				var bus_class = place["bus_class"];
				var posn = new GLatLng(place["posn"][0], place["posn"][1]);

				if (place["desc"]) {
					var desc = place["desc"];
				}else {
					var desc = place["name"];
				}
				var marker = createMullMarker(posn,title,icon,desc)
				markers.push(marker);
				allmarkers.push(marker);
			}
			mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
		}
		mgr.refresh();
	}

	function createMullMarker(posn,title,icon,desc) {
		var marker = new GMarker (posn, {title: title, icon: icon, desc: desc, draggable: false});
		GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(desc);
		});
		return marker;
	}


//		Set cookie before unloading
	function setCookie() {
		maptype = 0;
		var len = map.getMapTypes().length;
		for (var i=0;i< len;i++) {
			if (map.getCurrentMapType() == map.getMapTypes()[i]) {
				maptype = i;
//				alert ("Map Type = " + maptype);
			}
		}
		var cookietext = cookiename+"="+map.getCenter().lat()+"|"+map.getCenter().lng()+"|"+map.getZoom()+"|"+maptype;
		if (expiredays) {
			var exdate=new Date();
			exdate.setDate(exdate.getDate()+expiredays);
			cookietext += ";expires="+exdate.toGMTString();
		}
		// == write the cookie ==
		document.cookie=cookietext;
		// == Call GUnload() on exit ==
		GUnload();
	}


    // The Cookie Javascript is based on code provided by the
    // Community Church Javascript Team
    // http://www.bisphamchurch.org.uk/
    // http://econym.org.uk/gmap/

	function mapDefault() {
		centerLatitude = 56.4700;
		centerLongitude = -5.9500;
		startZoom = 10;
		maptype = 1;
		load();
	}

window.onunload = setCookie;
//window.onunload = GUnload;

//        function createMarker(point, index) {
//          // Create a lettered icon for this point using our icon class
//          var letter = String.fromCharCode("A".charCodeAt(0) + index);
//          var letteredIcon = new GIcon(baseIcon);
//          letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
//
//          // Set up our GMarkerOptions object
//          markerOptions = { icon:letteredIcon };
//          var marker = new GMarker(point, markerOptions);
//
//          GEvent.addListener(marker, "click", function() {
//            marker.openInfoWindowHtml("Marker <b>" + letter + "</b>");
//          });
//          return marker;
//        }


