var map;
var mapIcons = [];
var weatherIcons = [];
var markerFlags = [true, true, true, true, true, true, true, true, false, false, false, false];
var wikiOverlay = null;
var plakLat;
var plakLng;
var currZoom = 5;
var currLat = -28.2399;
var currLng = 24.7288;
var wikiflag = false;
var dirflag = false;
var dirStart = null;
var dirEnd = null;
var dirPoly = null;
var markers = [];
var weather = [];
var newMarker = null;
var ie = false;
var blinkInt;
var weatherStations;
var gettingWeather = false;
var daytime;

if (document.all) {
	ie = true;
}

var dirIcon = new GIcon();
dirIcon.iconSize = new GSize(24, 24);
dirIcon.iconAnchor = new GPoint(3, 24);
var startIcon = new GIcon(dirIcon);
startIcon.image = "/img/start.png";

var endIcon = new GIcon(dirIcon);
endIcon.image = "/img/end.png";

var xIcon = new GIcon();
xIcon.iconSize = new GSize(24, 24);
xIcon.iconAnchor = new GPoint(12, 12);
var crossIcon = new GIcon(xIcon);
crossIcon.image = "/img/cross.png";

var wIcon = new GIcon();
wIcon.iconSize = new GSize(24, 24);
wIcon.iconAnchor = new GPoint(12, 12);
wIcon.infoWindowAnchor = new GPoint(12, 12);

var wIIcon = new GIcon();
wIIcon.iconSize = new GSize(16, 16);
wIIcon.iconAnchor = new GPoint(8, 8);
wIIcon.infoWindowAnchor = new GPoint(8, 8);

var baseIcon = new GIcon();
baseIcon.iconSize = new GSize(14, 30);
baseIcon.iconAnchor = new GPoint(0, 30);
baseIcon.infoWindowAnchor = new GPoint(9, 2);

var serviceIcon = new GIcon();
serviceIcon.iconSize = new GSize(16, 16);
serviceIcon.iconAnchor = new GPoint(14, 16);
serviceIcon.infoWindowAnchor = new GPoint(9, 2);

function load() {

	document.getElementById("phonenohelp").target = "_blank";
	document.getElementById("faxnohelp").target = "_blank";
	document.getElementById("imageurlhelp").target = "_blank";

	if (GBrowserIsCompatible()) {

		map = new GMap2(document.getElementById("plak_map"));
		map.addMapType(G_PHYSICAL_MAP);
		var ca = document.cookie.split(';');
		for(var i=0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0)==' ')
				c = c.substring(1, c.length);
			if (c.indexOf("Plak") == 0) {
				var plakcookie = c.substring(5, c.length);
				var plakarray = plakcookie.split(":");
				var plakZoom = plakarray[0];
				currZoom = parseInt(plakZoom);
				var plakCurrLat = plakarray[1];
				if (plakCurrLat != "NaN")
					currLat = parseFloat(plakCurrLat);
				var plakCurrLng = plakarray[2];
				if (plakCurrLng != "NaN")
					currLng = parseFloat(plakCurrLng);
				if (plakarray[3] == "false")
					markerFlags[1] = false;
				if (plakarray[4] == "false")
					markerFlags[2] = false;
				if (plakarray[5] == "false")
					markerFlags[3] = false;
				if (plakarray[6] == "false")
					markerFlags[4] = false;
				if (plakarray[7] == "false")
					markerFlags[5] = false;
				if (plakarray[8] == "false")
					markerFlags[6] = false;
				if (plakarray[9] == "false")
					markerFlags[7] = false;
				if (plakarray[10] == "true")
					wikiflag = true;
				if (plakarray[11])
					map.setMapType(map.getMapTypes()[parseInt(plakarray[11])]);
				if (plakarray[12]) {
					if (plakarray[12] == "none") {
						document.getElementById("toggle_img").src="/img/rightbutton.gif";
						document.getElementById("toggle_img").setAttribute("title", "Maximize Sidebar");
						document.getElementById("sb_info").style.display = "none";
						document.getElementById("plak_map_border").style.width = "752px";
						document.getElementById("plak_map_directions").style.width = "752px";
						map.checkResize();
					}
				}
				if (plakarray[13]) {
					if (plakarray[13] == "true")
						dirflag = true;
				}
				if (plakarray[14]) {
					document.getElementById(plakarray[14]).checked = true;
				} else {
					document.getElementById("r1").checked = true;
				}
				if (plakarray[15] == "true")
					markerFlags[8] = true;
				if (plakarray[16] == "true")
					markerFlags[9] = true;
				if (plakarray[17] == "true")
					markerFlags[10] = true;
				if (plakarray[18] == "true")
					markerFlags[11] = true;
			}
		}

		for (var n = 1; n < 15; n++) {
			document.getElementById("check" + n).checked = false;
			document.getElementById("check" + n).disabled = true;
		}

		map.setCenter(new GLatLng(currLat, currLng), currZoom);

		var div = document.createElement("div");
		div.id = "pleasewait";
		div.style.position = "relative";
		div.style.whiteSpace = "nowrap";
		div.style.border = "1px solid silver";
		div.style.backgroundColor = "#F2F8FB";
		div.style.padding = "5px";
		div.innerHTML = "<h1>Loading. Please wait.</h1>";
		div.style.top = (map.fromLatLngToDivPixel(map.getCenter()).y - 50) + 'px';
		div.style.left = (map.fromLatLngToDivPixel(map.getCenter()).x - 142) + 'px';
		map.getPane(G_MAP_FLOAT_PANE).appendChild(div);

		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();

		var publisherID = 'ca-pub-4002245024903759';
		var adsManagerOptions = {
			maxAdsOnMap : 1,
			style: 'adunit',
			channel: '5626973176'
		};
		var adsManager = new GAdsManager(map, publisherID, adsManagerOptions);
		adsManager.enable();

		mapIcons.push(null);

		var mapIcon = new GIcon(baseIcon);
		mapIcon.image = "/img/GrayPin.png";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(baseIcon);
		mapIcon.image = "/img/BluePin.png";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(baseIcon);
		mapIcon.image = "/img/RedPin.png";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(baseIcon);
		mapIcon.image = "/img/PinkPin.png";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(baseIcon);
		mapIcon.image = "/img/PurplePin.png";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(baseIcon);
		mapIcon.image = "/img/GreenPin.png";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(baseIcon);
		mapIcon.image = "/img/YellowPin.png";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(serviceIcon);
		mapIcon.image = "/img/saps.gif";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(serviceIcon);
		mapIcon.image = "/img/school.gif";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(serviceIcon);
		mapIcon.image = "/img/hospital.gif";
		mapIcons.push(mapIcon);

		mapIcon = new GIcon(serviceIcon);
		mapIcon.image = "/img/other.gif";
		mapIcons.push(mapIcon);

		// 0
		mapIcon = new GIcon(wIIcon);
		mapIcon.image = "/img/winfo.png";
		weatherIcons.push(mapIcon);

		// 1
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wclear.png";
		weatherIcons.push(mapIcon);

		// 2
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wcloudy.png";
		weatherIcons.push(mapIcon);

		// 3
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wpcloudy.png";
		weatherIcons.push(mapIcon);

		// 4
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wmcloudy.png";
		weatherIcons.push(mapIcon);

		// 5
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wscloudy.png";
		weatherIcons.push(mapIcon);

		// 6
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wfog.png";
		weatherIcons.push(mapIcon);

		// 7
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/whaze.png";
		weatherIcons.push(mapIcon);

		// 8
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wdrizzle.png";
		weatherIcons.push(mapIcon);

		// 9
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wrain.png";
		weatherIcons.push(mapIcon);

		// 10
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wstorm.png";
		weatherIcons.push(mapIcon);

		// 11
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wsnow.png";
		weatherIcons.push(mapIcon);

		// 12
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wntclear.png";
		weatherIcons.push(mapIcon);

		// 13
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wntpcloudy.png";
		weatherIcons.push(mapIcon);

		// 14
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wntmcloudy.png";
		weatherIcons.push(mapIcon);

		// 15
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wntscloudy.png";
		weatherIcons.push(mapIcon);

		// 16
		mapIcon = new GIcon(wIcon);
		mapIcon.image = "/img/wnthaze.png";
		weatherIcons.push(mapIcon);

		wikiOverlay = new GLayer("org.wikipedia.en");

		GEvent.addListener(map, "moveend", function() {
			if (map.getInfoWindow().isHidden()) {
				displayMarkers(1);
			}
		});

		GEvent.addListener(map, "dblclick", function(overlay, latlng) {
			if (userid == 1) {
				document.location.href="http://plak.co.za/PlakLocKML.php?lat=" + latlng.lat() + "&lng=" + latlng.lng() + "&latbounds=0.3&lngbounds=0.3";
			}
		});

		GEvent.addListener(map, "singlerightclick", function(point,  src,  overlay) {
			if (document.getElementById("check9").checked) {
				var latlng = map.fromContainerPixelToLatLng(point);
 				plakLat = latlng.lat();
				plakLng = latlng.lng();
				if (plakLat < -22.1111 && plakLat > -34.8422 && plakLng > 16.4516 && plakLng < 32.8966) {
					if (dirStart == null) {
						var markerOptions = { icon:startIcon };
						dirStart = new GMarker(latlng, markerOptions);
						map.addOverlay(dirStart);
						if (dirEnd != null) {
							getDirections();
						}
					} else if (dirEnd == null) {
						var markerOptions = { icon:endIcon };
						dirEnd = new GMarker(latlng, markerOptions);
						map.addOverlay(dirEnd);
						if (dirStart != null) {
							getDirections();
						}
					} else {
						map.removeOverlay(dirStart);
						map.removeOverlay(dirEnd);
						map.removeOverlay(dirPoly);
						dirStart = null;
						dirEnd = null;
						dirPoly = null;
					}
				}
			} else {
				if (!loggedin) {
					alert("You must be logged in before you can add a Plak.");
				} else {
					if (map.getZoom() < 14) {
						alert ("Please zoom in before trying to add a Plak.\r\nYou are currently at zoom level " + map.getZoom() + ".\r\nYou must be at zoom level 14, or greater, before adding a Plak.");
					} else {
						var latlng = map.fromContainerPixelToLatLng(point);
 						plakLat = latlng.lat();
						plakLng = latlng.lng();
						if (plakLat < -22.1111 && plakLat > -34.8422 && plakLng > 16.4516 && plakLng < 32.8966) {
							document.getElementById("plak_lat").value = plakLat;
							document.getElementById("plak_lng").value = plakLng;
							document.getElementById("plak_add").style.display = "block";
							blinkInt = setInterval("doBlink()",1000);
						}
					}
				}
			}
		});

		var bounds = map.getBounds();
		var ne = bounds.getNorthEast();
		var sw = bounds.getSouthWest();
		var flag = getFlagBitmap();
		var rep;
		if (flag == "00000000000") {
			rep = eval("[['none']]");
			gotMarkers(rep);
		} else {
			AJAXCall("getNewMarkers", encodeURI("lat1=" + sw.lat() + "&lat2=" + ne.lat() + "&lng1=" + sw.lng() + "&lng2=" + ne.lng() + "&flag=" + flag + "&num=" + getNumMarkers()), "gotMarkers(rep)");
		}
	}
}

function getDirections() {
	document.getElementById("directions").src = "img/busy.gif";
	var sp = dirStart.getLatLng().lng() + "," + dirStart.getLatLng().lat();
	var ep = dirEnd.getLatLng().lng() + "," + dirEnd.getLatLng().lat();
	AGCall(sp, ep, "directionloadhandler(rep)", 1);
}

function getTextDirections() {
	document.getElementById("directions").src = "img/busy.gif";
	var sp = dirStart.getLatLng().lat() + "|" + dirStart.getLatLng().lng();
	var ep = dirEnd.getLatLng().lat() + "|" + dirEnd.getLatLng().lng();
	AGCall(sp, ep, "textdirloadhandler(rep)", 2);
}

function textdirloadhandler(obj) {
	document.getElementById("plak_map_border").style.display = "none";
	var doc = document.getElementById("dir_text").contentDocument || document.getElementById("dir_text").contentWindow.document;

	doc.open();
        doc.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='content-type' content='text/html; charset=UTF-8'/><link rel='stylesheet' type='text/css' href='Global.css'/></head><body style='background-color: white;'>" + obj + "</body></html>");
        doc.close();    

	document.getElementById("plak_map_directions").style.display = "block";
	document.getElementById("directions").src = "img/car.png";
}

function HideDir() {
	document.getElementById("plak_map_directions").style.display = "none";
	document.getElementById("plak_map_border").style.display = "block";
}

function directionloadhandler(obj) {
	var coords = obj.RoutingPoints.split("|");
	var polyCoords = [];
	for (var n = 0; n < coords.length; n++) {
		var ll = coords[n].split(",");
		polyCoords.push(new GLatLng(parseFloat(ll[1]), parseFloat(ll[0])));
	}
	dirPoly = new GPolyline(polyCoords);
	map.addOverlay(dirPoly);
	document.getElementById("directions").src = "img/car.png";
	var ans = confirm("Would you like text directions for the displayed route?");
	if (ans) {
		getTextDirections();
	}
}

function gotNewMarkers(object) {
	clearAll();
	if (object[0][0] != "none") {
		var marker;
		for (var n = 0; n < object.length; n++) {
			var LatLng = new GLatLng(object[n][1], object[n][2]);
			marker = new createMarker(LatLng, mapIcons[object[n][4]], object[n][3], object[n][0], object[n][4]);
			markers.push(marker);
		}
	}
	displayMarkers(0);
}

function displayMarkers(getFlag) {

	if (getFlag == 1) {
		var bounds = map.getBounds();
		var ne = bounds.getNorthEast();
		var sw = bounds.getSouthWest();
		if (document.getElementById("check13").checked && !gettingWeather) {
			document.getElementById("check13").disabled = true;
			gettingWeather = true;
			clearWeather();
			weatherCall(ne.lat(), sw.lat(), ne.lng(), sw.lng(), "gotWeather()", 4);
		}
		var flag = getFlagBitmap();
		if (flag != "00000000000") {
			AJAXCall("getNewMarkers", encodeURI("lat1=" + sw.lat() + "&lat2=" + ne.lat() + "&lng1=" + sw.lng() + "&lng2=" + ne.lng() + "&flag=" + flag + "&num=" + getNumMarkers()), "gotNewMarkers(rep)");
		} else {
			clearAll();
		}
	} else {

		for (var x = 0; x < markers.length; x++) {
			map.addOverlay(markers[x]);
		}
		var max = parseInt(getNumMarkers());
		if (max == 0) {
			document.getElementById("msg").innerHTML = "<strong>Click map pins to view more information.</strong>";
		} else {
			if (markers.length == max) {
				document.getElementById("msg").innerHTML = "<strong>Zoom in to see more Plaks.</strong>";
			} else {
				document.getElementById("msg").innerHTML = "<strong>Click map pins to view more information.</strong>";
			}
		}
	}
}

function clearAll() {
	hideName();
	if (newMarker != null) {
		map.removeOverlay(newMarker);
		newMarker = null;
	}
	if (markers.length > 0) {
		for (var n = 0; n < markers.length; n++) {
			map.removeOverlay(markers[n]);
		}
		markers = [];
	}
}

function GUnload() {
	if (!document.getElementById("check1").disabled) {
		var value = map.getZoom() + ":";
		value += map.getCenter().lat() + ":" + map.getCenter().lng() + ":";
		value += document.getElementById("check1").checked;
		value += ":" + document.getElementById("check2").checked;
		value += ":" + document.getElementById("check3").checked;
		value += ":" + document.getElementById("check4").checked;
		value += ":" + document.getElementById("check5").checked;
		value += ":" + document.getElementById("check6").checked;
		value += ":" + document.getElementById("check7").checked;
		value += ":" + document.getElementById("check8").checked;
		for (var i = 0; i < map.getMapTypes().length; i++) {
			if (map.getCurrentMapType() == map.getMapTypes()[i]) {
				value += ":" + i;
			}
		}
		value += ":" + document.getElementById("sb_info").style.display;
		value += ":" + document.getElementById("check9").checked;
		if (document.getElementById("r1").checked) {
			value += ":r1";
		} else {
			value += ":r2";
		}
		value += ":" + document.getElementById("check10").checked;
		value += ":" + document.getElementById("check11").checked;
		value += ":" + document.getElementById("check12").checked;
		value += ":" + document.getElementById("check14").checked;
		createCookie("Plak", value, 7);
	}
}

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function gotMarkers(object) {

	document.getElementById("check1").checked = markerFlags[1];
	document.getElementById("check2").checked = markerFlags[2];
	document.getElementById("check3").checked = markerFlags[3];
	document.getElementById("check4").checked = markerFlags[4];
	document.getElementById("check5").checked = markerFlags[5];
	document.getElementById("check6").checked = markerFlags[6];
	document.getElementById("check7").checked = markerFlags[7];
	document.getElementById("check10").checked = markerFlags[8];
	document.getElementById("check11").checked = markerFlags[9];
	document.getElementById("check12").checked = markerFlags[10];
	document.getElementById("check14").checked = markerFlags[11];
	document.getElementById("check13").checked = false;

	if (object[0][0] != "none") {
		var marker;
		for (var n = 0; n < object.length; n++) {
			var LatLng = new GLatLng(object[n][1], object[n][2]);
			marker = new createMarker(LatLng, mapIcons[object[n][4]], object[n][3], object[n][0], object[n][4]);
			markers.push(marker);
		}
	}

	document.getElementById("check1").disabled = false;
	document.getElementById("check2").disabled = false;
	document.getElementById("check3").disabled = false;
	document.getElementById("check4").disabled = false;
	document.getElementById("check5").disabled = false;
	document.getElementById("check6").disabled = false;
	document.getElementById("check7").disabled = false;
	document.getElementById("check10").disabled = false;
	document.getElementById("check11").disabled = false;
	document.getElementById("check12").disabled = false;
	document.getElementById("check13").disabled = false;
	document.getElementById("check14").disabled = false;

	document.getElementById("check8").disabled = false;
	document.getElementById("check8").checked = wikiflag;
	document.getElementById("check9").disabled = false;
	document.getElementById("check9").checked = dirflag;
	toggleWiki(wikiflag);
	displayMarkers(0);
	
	var pleasewait = document.getElementById("pleasewait");
	if(pleasewait) {
		map.getPane(G_MAP_FLOAT_PANE).removeChild(pleasewait);
	}
}

function dirFromTo(lat, lng) {
	map.getInfoWindow().hide();
	var latlng = new GLatLng(lat, lng);
	if (dirPoly != null) {
		map.removeOverlay(dirStart);
		map.removeOverlay(dirEnd);
		map.removeOverlay(dirPoly);
		dirStart = null;
		dirEnd = null;
		dirPoly = null;
	}

	if (dirStart == null) {
		var markerOptions = { icon:startIcon };
		dirStart = new GMarker(latlng, markerOptions);
		map.addOverlay(dirStart);
		if (dirEnd != null) {
			getDirections();
		}
	} else {
		var markerOptions = { icon:endIcon };
		dirEnd = new GMarker(latlng, markerOptions);
		map.addOverlay(dirEnd);
		if (dirStart != null) {
			getDirections();
		}
	}
}

function removeMarker( id) {
	var ans = confirm("Are you sure that you want to delete the marker?");
	if (ans) {
		AJAXCall("removeMarker", encodeURI("markerid=" + id), "posUpdated(rep)");
	}
}

function newPos(marker, id) {
	var ans = confirm("Are you sure that you want to move the marker?");
	if (ans) {
		var point = marker.getPoint();
		AJAXCall("updateMarker", encodeURI("lat=" + point.lat() + "&lng=" + point.lng() + "&markerid=" + id), "posUpdated(rep)");
	}
}

function posUpdated(object) {
	alert(object);
}

function createMarker(point, ico, name, id, type) {
	var alttext = "";

	if (userid == 1) {
		var marker = new GMarker(point, { icon:ico, draggable: true });
		GEvent.addListener(marker, "dragend", function(latng) { newPos(marker, id);});
		GEvent.addListener(marker, "click", function(latlng) { removeMarker(id);});
	} else {
		var marker = new GMarker(point, { icon:ico });
		GEvent.addListener(marker, "click", function() {
			showInfo(this, name, id);
		});
	}

	GEvent.addListener(marker, "mouseover", function(latlng) {
		showName(name, latlng, type);
	});

	GEvent.addListener(marker, "mouseout", function() {
		hideName();
	});

	return marker;
}

function createWMarker(point, ico, label, html) {
	var markerOptions = { icon:ico };
	var marker = new GMarker(point, markerOptions);

	GEvent.addListener(marker, "click", function() {
		showWInfo(this, html);
	});

	GEvent.addListener(marker, "mouseover", function(latlng) {
		showName(label + " - Weather", latlng, 0);
	});

	GEvent.addListener(marker, "mouseout", function() {
		hideName();
	});

	return marker;
}

function showInfo(marker, name, id) {
	hideName();
	var alttext = "";
	var point = marker.getPoint();
	var ico = marker.getIcon();
	marker.openInfoWindowHtml("<div class='info_div'><img src='" + ico.image + "' class='info_icon' alt='" + alttext + "'/><br/><div class='info_name'>" + name + "</div><br/><div style='text-align: center;'><input class='plak_button' type='button' value='More info...' onclick=\"document.location.href='/moreinfo.php?id=" + id + "'\"/><br/><br/><input class='plak_button' type='button' value='Directions' onclick=\"dirFromTo(" + point.lat() + ", " + point.lng() + ");\" /></div></div>");
}

function showWInfo(marker, html) {
	hideName();
	marker.openInfoWindowHtml(html);
}

function showName(name, latlng, type) {
	hideName();
	var div = document.createElement("div");
	div.id = "infopop";
	div.style.position = "relative";
	div.style.whiteSpace = "nowrap";
	div.innerHTML = name;
	if (type > 7) {
		div.style.top = (map.fromLatLngToDivPixel(latlng).y - 41) + 'px';
		div.style.left = (map.fromLatLngToDivPixel(latlng).x - 13) + 'px';
	} else if (type == 0) {
		div.style.top = (map.fromLatLngToDivPixel(latlng).y - 34) + 'px';
		div.style.left = (map.fromLatLngToDivPixel(latlng).x - 8) + 'px';
	} else {
		div.style.top = (map.fromLatLngToDivPixel(latlng).y - 54) + 'px';
		div.style.left = (map.fromLatLngToDivPixel(latlng).x + 8) + 'px';
	}
	map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
}

function hideName() {
	var infopop = document.getElementById("infopop");
	if(infopop) {
		map.getPane(G_MAP_FLOAT_PANE).removeChild(infopop);
	}
}

function cityChanged(LatLng) {
	var values = LatLng.split(",");
	map.setCenter(new GLatLng(values[0], values[1]), parseInt(values[2]));
}

function plak_add_close() {
	clearInterval (blinkInt);
	document.getElementById("plak_add").style.display = "none";
}

function isUrl(s) {
	var regexp = new RegExp();
	regexp.compile("^(http|https)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$");
	return regexp.test(s);
}

function isPNum(s) {
	var regexp  = /\b(0\d{2})\ \d{3}\ \d{4}\b/;
	return regexp.test(s);
}

function isImage(s) {
	var regexp = /(.jpg|.jpeg|.png|.gif)/i;
	return regexp.test(s);
}

function addPlak() {
	if (document.getElementById("plak_type").value == -1) {
		alert("Please select a type.");
	} else if (document.getElementById("plak_name").value.length == 0) {
		alert("Please supply a name.");
	} else if (checkCaps(document.getElementById("plak_name").value)) {
		alert("Sorry, but the name may not be supplied using only CAPS.");
	} else if (document.getElementById("plak_name").value.length > 40) {
		alert("Sorry, but the Plak name is limited to 40 characters.");
	} else if (document.getElementById("plak_desc").value.indexOf("!!") > -1) {
		alert("Please use only single exclamation marks!!!!!!!");
	} else if (document.getElementById("plak_desc").value.length == 0) {
		alert("Please supply a description.");
	} else if (document.getElementById("plak_address").value.length > 300) {
		alert("Sorry, but the address is limited to 300 characters.");
	} else if (document.getElementById("plak_address").value.length > 0 && !checkProv(document.getElementById("plak_address").value)) {
		alert("Please include the province in the address. Valid province names are: -\r\n\r\nEastern Cape\r\nFree State\r\nGauteng\r\nKwaZulu-Natal\r\nLimpopo\r\nMpumalanga\r\nNorth West\r\nNorthern Cape\r\nWestern Cape");
	} else if (document.getElementById("plak_address").value.length > 0 && !checkCountry(document.getElementById("plak_address").value)) {
		alert("Please include the country in the address.");
	} else if (document.getElementById("plak_phone").value.length > 20) {
		alert("Sorry, but the phone number is limited to 20 characters.");
	} else if (document.getElementById("plak_phone").value.length > 0 && !isPNum(document.getElementById("plak_phone").value)) {
		alert("The correct phone number format is 099 999 9999\r\nThe phone number MUST start with a zero\r\nDO NOT include 027 or +27 for international callers\r\nPlak will automatically add the +27");
	} else if (document.getElementById("plak_fax").value.length > 20) {
		alert("Sorry, but the fax number is limited to 20 characters.");
	} else if (document.getElementById("plak_fax").value.length > 0 && !isPNum(document.getElementById("plak_fax").value)) {
		alert("The correct fax number format is 099 999 9999\r\nThe fax number MUST start with a zero\r\nDO NOT include 027 or +27 for international callers\r\nPlak will automatically add the +27");
	} else if (document.getElementById("plak_site").value.length > 0 && !isUrl(document.getElementById("plak_site").value)) {
		alert("Sorry, but the website URL seems to be invalid. It must start with http:// or https:// and may not include spaces.\r\nExample of correct website URL - http://www.mywebsite.com");
	} else if (document.getElementById("plak_image").value.length > 0 && !isUrl(document.getElementById("plak_image").value)) {
		alert("Sorry, but the image URL seems to be invalid. It must start with http:// or https:// and may not include spaces.\r\nExample of correct image URL - http://www.mywebsite.com/pic1.jpg");
	} else if (document.getElementById("plak_image").value.length > 0 && !isImage(document.getElementById("plak_image").value)) {
		alert("Sorry, but the image URL seems to be invalid. It must point at either a jpeg, a gif or a png image.\r\nExample of correct image URL - http://www.mywebsite.com/pic1.jpg");
	} else {
		var icon = mapIcons[document.getElementById("plak_type").value];
		plak_add_close();
		var LatLng = new GLatLng(document.getElementById("plak_lat").value, document.getElementById("plak_lng").value);
		var markerOptions = { icon:icon };
		if (newMarker != null) {
			map.removeOverlay(newMarker);
		}
		newMarker = new GMarker(LatLng, markerOptions);
		map.addOverlay(newMarker);
		newMarker.openInfoWindowHtml("<br/><div class='info_name'>Are you sure that want to add that Plak there?</div><br/><input class='plak_button' type='button' value='Yes' onclick=\"addNewPlak();\" /> <input class='plak_button' type='button' value='No' onclick=\"removeNewPlak();\" />");
	}
}

function addNewPlak() {
	var hasWiFi;
	if (document.getElementById("plak_wifi").checked) {
		hasWiFi = 1;
	} else {
		hasWiFi = 0;
	}
	var plak_name = document.getElementById("plak_name").value;
	plak_name = plak_name.replace(/&/g, "%26");
	var plak_desc = document.getElementById("plak_desc").value;
	plak_desc = plak_desc.replace(/&/g, "%26");
	var plak_address = document.getElementById("plak_address").value;
	plak_address = plak_address.replace(/&/g, "%26");
	var plak_site = document.getElementById("plak_site").value;
	plak_site = plak_site.replace(/&/g, "%26");
	var plak_image = document.getElementById("plak_image").value;
	plak_image = plak_image.replace(/&/g, "%26");
	AJAXCall("add", encodeURI("name=" + plak_name + "&lat=" + document.getElementById("plak_lat").value + "&lng=" + document.getElementById("plak_lng").value + "&type=" + document.getElementById("plak_type").value + "&desc=" + plak_desc + "&address=" + plak_address + "&phone=" + document.getElementById("plak_phone").value + "&fax=" + document.getElementById("plak_fax").value + "&wifi=" + hasWiFi + "&wtype=" + document.getElementById("plak_wifitype").value + "&site=" + plak_site + "&image=" + plak_image), "plakAdded(rep)");
	map.removeOverlay(newMarker);
	newMarker = null;
}

function removeNewPlak() {
	map.removeOverlay(newMarker);
	newMarker = null;
}

function wifiClicked(value) {
	if (value) {
		document.getElementById("plak_wifitype").disabled = false;
	} else {
		document.getElementById("plak_wifitype").disabled = true;
	}
}

function plakTypeChange(value) {
	if (value == 1) {
		document.getElementById("plak_wifi").checked = true;
		document.getElementById("plak_wifi").disabled = true;
		document.getElementById("plak_wifitype").disabled = false;
	} else {
		document.getElementById("plak_wifi").disabled = false;
	}
}

function plakAdded(object) {

	document.getElementById("plak_type").selectedIndex = 0;
	document.getElementById("plak_name").value = "";
	document.getElementById("plak_desc").value = "";
	document.getElementById("plak_address").value = "";
	document.getElementById("plak_phone").value = "";
	document.getElementById("plak_fax").value = "";
	document.getElementById("plak_site").value = "";
	document.getElementById("plak_image").value = "";
	document.getElementById("plak_wifi").checked = false;
	document.getElementById("plak_wifitype").selectedIndex = 0;
	document.getElementById("plak_wifitype").disabled = true;

	var LatLng = new GLatLng(object[2], object[3]);
	var marker = new createMarker(LatLng, mapIcons[object[1]], object[4], object[0], object[1]);
	markers.push(marker);
	map.addOverlay(marker);
}

function toggleOverlay(flag, index) {
	markerFlags[index] = flag;
	displayMarkers(1);
}

function toggleWiki(show) {
	if (show) {
		map.addOverlay(wikiOverlay);
	} else {
		map.removeOverlay(wikiOverlay);
	}
}

function getWeather(flag) {
	if (flag) {
		document.getElementById("check13").disabled = true;
		var bounds = map.getBounds();
		var ne = bounds.getNorthEast();
		var sw = bounds.getSouthWest();
		weatherCall(ne.lat(), sw.lat(), ne.lng(), sw.lng(), "gotWeather()", 4);
	} else {
		clearWeather();
	}
}

function clearWeather() {
	if (weather.length > 0) {
		for (var n = 0; n < weather.length; n++) {
			map.removeOverlay(weather[n]);
		}
		weather = [];
	}
}

function checkID(id) {
	var retval = true;
	if (id.substring(0, 1) == "M") {
		var regexp  = /^M[A-Z]/;
		retval = regexp.test(id);
	}
	return retval;
}

function gotWeather() {
	clearWeather();
	for (var n = 0; n < weatherStations.length; n++) {
		var country = weatherStations[n]["country"].toLowerCase();
		if ((country == "za" || country == "south africa") && checkID(weatherStations[n]["id"])) {
			var LatLng = new GLatLng(weatherStations[n]["lat"], weatherStations[n]["lon"]);
			var wicon;
			var sweather = weatherStations[n]["weather"].toLowerCase();
			if (sweather.indexOf("light") != -1) {
				sweather = sweather.substring(6);
			}
			if (sweather.indexOf("heavy") != -1) {
				sweather = sweather.substring(6);
			}
			var whtml = "";
			if (sweather == "clear" || sweather == "clr") {
				if (daytime) {
					wicon = weatherIcons[1];
					whtml = "<img src='/img/wlclear.png' style='float: left; width: 32px; height: 32px;' alt='Clear' />";
				} else {
					wicon = weatherIcons[12];
					whtml = "<img src='/img/wlntclear.png' style='float: left; width: 32px; height: 32px;' alt='Clear' />";
				}
			} else if (sweather == "overcast" || sweather == "ovc") {
				wicon = weatherIcons[2];
				whtml = "<img src='/img/wlcloudy.png' style='float: left; width: 32px; height: 32px;' alt='Cloudy' />";
			} else if (sweather == "partly cloudy") {
				if (daytime) {
					wicon = weatherIcons[3];
					whtml = "<img src='/img/wlpcloudy.png' style='float: left; width: 32px; height: 32px;' alt='Partly Cloudy' />";
				} else {
					wicon = weatherIcons[13];
					whtml = "<img src='/img/wlntpcloudy.png' style='float: left; width: 32px; height: 32px;' alt='Partly Cloudy' />";
				}
			} else if (sweather == "mostly cloudy") {
				if (daytime) {
					wicon = weatherIcons[4];
					whtml = "<img src='/img/wlmcloudy.png' style='float: left; width: 32px; height: 32px;' alt='Mostly Cloudy' />";
				} else {
					wicon = weatherIcons[14];
					whtml = "<img src='/img/wlntmcloudy.png' style='float: left; width: 32px; height: 32px;' alt='Mostly Cloudy' />";
				}
			} else if (sweather == "scattered clouds" || sweather == "few" || sweather == "sct") {
				if (daytime) {
					wicon = weatherIcons[5];
					whtml = "<img src='/img/wlscloudy.png' style='float: left; width: 32px; height: 32px;' alt='Scattered Clouds' />";
				} else {
					wicon = weatherIcons[15];
					whtml = "<img src='/img/wlntscloudy.png' style='float: left; width: 32px; height: 32px;' alt='Scattered Clouds' />";
				}
			} else if (sweather == "fog" || sweather == "mist" || sweather == "smoke" || sweather == "fg" || sweather == "br" || sweather == "fu") {
				wicon = weatherIcons[6];
				whtml = "<img src='/img/wlfog.png' style='float: left; width: 32px; height: 32px;' alt='Fog/Mist/Smoke' />";
			} else if (sweather == "haze" || sweather == "hz") {
				if (daytime) {
					wicon = weatherIcons[7];
					whtml = "<img src='/img/wlhaze.png' style='float: left; width: 32px; height: 32px;' alt='Haze' />";
				} else {
					wicon = weatherIcons[16];
					whtml = "<img src='/img/wlnthaze.png' style='float: left; width: 32px; height: 32px;' alt='Haze' />";
				}
			} else if (sweather == "drizzle" || sweather == "dz") {
				wicon = weatherIcons[8];
				whtml = "<img src='/img/wldrizzle.png' style='float: left; width: 32px; height: 32px;' alt='Drizzle' />";
			} else if (sweather == "rain" || sweather == "rain showers" || sweather == "ra") {
				wicon = weatherIcons[9];
				whtml = "<img src='/img/wlrain.png' style='float: left; width: 32px; height: 32px;' alt='Rain' />";
			} else if (sweather == "thunderstorm" || sweather == "thunderstorms and rain" || sweather == "ts") {
				wicon = weatherIcons[10];
				whtml = "<img src='/img/wlstorm.png' style='float: left; width: 32px; height: 32px;' alt='Thunderstorm' />";
			} else if (sweather == "snow" || sweather == "snow showers" || sweather == "hail" || sweather == "hail showers" || sweather == "small hail showers" || sweather == "sn" || sweather == "gr") {
				wicon = weatherIcons[11];
				whtml = "<img src='/img/wlsnow.png' style='float: left; width: 32px; height: 32px;' alt='Snow/Hail' />";
			} else {
				wicon = weatherIcons[0];
			}
			var label;
			if (weatherStations[n]["neighborhood"]) {
				if (weatherStations[n]["neighborhood"].length == 0) {
					label = weatherStations[n]["adm1"];
				} else {
					label = weatherStations[n]["neighborhood"];
				}
			} else {
				label = weatherStations[n]["adm1"];
			}
//label = weatherStations[n]["id"] + " " + label;
			var temp = parseFloat(weatherStations[n]["tempf"]);
			temp = ((temp - 32)/9)*5;
			temp = temp.toFixed(2);
			var mintemp = parseFloat(weatherStations[n]["mintemp"]);
			mintemp = ((mintemp - 32)/9)*5;
			mintemp = mintemp.toFixed(2);
			var maxtemp = parseFloat(weatherStations[n]["maxtemp"]);
			maxtemp = ((maxtemp - 32)/9)*5;
			maxtemp = maxtemp.toFixed(2);
			var html = "<div>" + whtml + "<div style='font-weight: bold; padding-bottom: 5px;'>" + label + "</div><div style='font-size: 9px;'>(" + weatherStations[n]["ageh"] + " h " + weatherStations[n]["agem"] + " m " + weatherStations[n]["ages"] + " s ago)</div>";
			if (weatherStations[n]["tempf"] != "-9999" && weatherStations[n]["tempf"] != "-999.0") {
				html += "<div style='font-size: 18px; font-weight: bold; padding: 5px;'>" + temp + "&deg; C</div>";
			}
			if (weatherStations[n]["weather"] && weatherStations[n]["weather"] != "-999" && weatherStations[n]["weather"] != "Unknown") {
				html += "<div>" + weatherStations[n]["weather"] + "</div>";
			}
			if (!isNaN(mintemp) && weatherStations[n]["maxtemp"] != "-9999") {
				html += "<div>Min = <span style='color: #0000ff; font-weight: bold;'>" + mintemp +"&deg; C</span> Max = <span style='color: #ff0000; font-weight: bold;'>" + maxtemp + "&deg C</span></div>";
			}
			var windspeed = parseFloat(weatherStations[n]["windspeedmph"]);
			if (windspeed != "-999") {
				windspeed = windspeed * 1.609344;
				windspeed = windspeed.toFixed(2);
				if (!isNaN(windspeed)) {
					html += "<div>Wind = " + windspeed + " Km/h";
					if (weatherStations[n]["winddir"] != "-999") {
						html += " @ " + weatherStations[n]["winddir"] + "&deg;</div>";
					} else {
						html += "</div>";
					}
				}
			}
			html += "</div>";
			marker = new createWMarker(LatLng, wicon, label, html);
			weather.push(marker);
			map.addOverlay(marker);
		}
	}
	gettingWeather = false;
	document.getElementById("check13").disabled = false;
}

function toggleDirections(show) {
	if (!show) {
		if (dirStart != null) {
			map.removeOverlay(dirStart);
			dirStart = null;
		}
		if (dirEnd != null) {
			map.removeOverlay(dirEnd);
			dirEnd = null;
		}
		if (dirPoly != null) {
			map.removeOverlay(dirPoly);
			dirPoly = null;
		}
	}
}

function togglesidebar(image) {
	if (document.getElementById("sb_info").style.display == "block") {
		image.src="/img/rightbutton.gif";
		document.getElementById("toggle_img").setAttribute("title", "Maximize Sidebar");
		document.getElementById("sb_info").style.display = "none";
		document.getElementById("plak_map_border").style.width = "752px";
		document.getElementById("plak_map_directions").style.width = "752px";
	} else {
		image.src="/img/leftbutton.gif";
		document.getElementById("toggle_img").setAttribute("title", "Minimize Sidebar");
		document.getElementById("sb_info").style.display = "block";
		document.getElementById("plak_map_border").style.width = "608px";
		document.getElementById("plak_map_directions").style.width = "608px";
	}
	map.checkResize();
	displayMarkers(1);
}

function printDirections() {
	dir_text.focus();
	dir_text.print(); 
}

function checkCaps(text) {
	var retval = false;
	var regexp = /[A-Z]/g;
	var regexp1 = /[A-Za-z]/g;
	var textList = text.match(regexp1);
	var matchList = text.match(regexp);

	if (matchList != null) {
		if (matchList.length == textList.length) {
			retval = true;
		}
	}
	return retval;
}

function checkCountry(text) {
	var retval = true;
	text = text.toLowerCase();
	if (text.indexOf("south africa") == -1) {
		retval = false;
	}
	return retval;
}

function checkProv(text) {
	text = text.toLowerCase();
	if (text.indexOf("gauteng") != -1) {
		return true;
	} else if (text.indexOf("western cape") != -1) {
		return true;
	} else if (text.indexOf("eastern cape") != -1) {
		return true;
	} else if (text.indexOf("northern cape") != -1) {
		return true;
	} else if (text.indexOf("free state") != -1) {
		return true;
	} else if (text.indexOf("mpumalanga") != -1) {
		return true;
	} else if (text.indexOf("limpopo") != -1) {
		return true;
	} else if (text.indexOf("kwazulu-natal") != -1) {
		return true;
	} else if (text.indexOf("north west") != -1) {
		return true;
	} else if (text.indexOf("gauteng") != -1) {
		return true;
	} else {
		return false;
	}
}

function doBlink() {
	var blink = document.getElementById("addrBlink");
	if (blink.style.color == "#ff0000" || blink.style.color =="rgb(255, 0, 0)") {
		blink.style.color = "#F2F8FB";
	} else {
		blink.style.color = "#FF0000";
	}
}

function plak_find_open() {
	document.getElementById("find_lat_deg").value = "";
	document.getElementById("find_lat_min").value = "";
	document.getElementById("find_lat_sec").value = "";

	document.getElementById("find_lng_deg").value = "";
	document.getElementById("find_lng_min").value = "";
	document.getElementById("find_lng_sec").value = "";

	document.getElementById("find_dec_lat").value = "";
	document.getElementById("find_dec_lng").value = "";
	document.getElementById("plak_find").style.display = "block";
}

function plak_find_close() {
	document.getElementById("plak_find").style.display = "none";
}

function findDecLoc() {
	var lat = parseFloat(document.getElementById("find_dec_lat").value);
	var lng = parseFloat(document.getElementById("find_dec_lng").value);

	if (isNaN(lat)) {
		alert("The latitude must be a negative numeric value between -34.8422 and -22.1111");
	} else if (isNaN(lng)) {
		alert("The longitude must be a positive numeric value between 16.4516 and 32.8966");
	} else if (lat > -22.1111 || lat < -35.8422) {
		alert("The latitude must be a negative numeric value between -34.8422 and -22.1111");
	} else if (lng > 32.8966 || lng < 16.4516) {
		alert("The longitude must be a positive numeric value between 16.4516 and 32.8966");
	} else {
		document.getElementById("plak_find").style.display = "none";
		map.setCenter(new GLatLng(lat, lng), 15);
		showX(lat, lng);
	}
}

function findDegLoc() {
	var latDeg = parseInt(document.getElementById("find_lat_deg").value);
	var latMin = parseInt(document.getElementById("find_lat_min").value);
	var latSec = parseFloat(document.getElementById("find_lat_sec").value);

	var lngDeg = parseInt(document.getElementById("find_lng_deg").value);
	var lngMin = parseInt(document.getElementById("find_lng_min").value);
	var lngSec = parseFloat(document.getElementById("find_lng_sec").value);

	if (isNaN(latDeg) || isNaN(latMin) || isNaN(latSec)) {
		alert("The latitude must be fall between S 34° 50' 31.9194\" and S 22° 6' 39.96\"");
	} else if (isNaN(lngDeg) || isNaN(lngMin) || isNaN(lngSec)) {
		alert("The latitude must be fall between E 16° 27' 5.7594\" and E 32° 53' 47.7594\"");
	} else {
		var lat = latDeg + (latMin / 60) + (latSec / 3600);
		lat = lat * -1;
		var lng = lngDeg + (lngMin / 60) + (lngSec / 3600);
		if (lat > -22.1111 || lat < -35.8422) {
			alert("The latitude must be fall between S 34° 50' 31.9194\" and S 22° 6' 39.96\"");
		} else if (lng > 32.8966 || lng < 16.4516) {
			alert("The latitude must be fall between E 16° 27' 5.7594\" and E 32° 53' 47.7594\"");
		} else {
			document.getElementById("plak_find").style.display = "none";
			map.setCenter(new GLatLng(lat, lng), 15);
			showX(lat, lng);
		}
	}
}

function showX(xLat, xLng) {
	if (xMarker != null) {
		map.removeOverlay(xMarker);
	}
	var point = new GPoint(xLng, xLat);
	var markerOptions = { icon:crossIcon };
	xMarker = new GMarker(point, markerOptions);

	map.addOverlay(xMarker);
}

function getFlagBitmap() {
	var retval = "";
	for (var n = 1; n < markerFlags.length; n++) {
		if (markerFlags[n] == 0) {
			retval += "0";
		} else {
			retval += "1";
		}
	}
	return retval;
}

function getNumMarkers() {
	var zoom = map.getZoom();
	var maxmarkers = "0";
	if (zoom < 15) {
		if (ie) {
			maxmarkers = "50";
		} else {
			maxmarkers = "90";
		}
	}
	return maxmarkers;
}