/*
These are the implementation-specific parts of the original OptiMap.
*/

var tsp; // The BtTspSolver object which handles the TSP computation.
var mode;
var reasons = new Array();
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

/* Returns a textual representation of time in the format
* "N days M hrs P min Q sec". Does not include days if
* 0 days etc. Does not include seconds if time is more than
* 1 hour.
*/
function formatTime(seconds) {
	var days;
	var hours;
	var minutes;
	days = parseInt(seconds / (24*3600));
	seconds -= days * 24 * 3600;
	hours = parseInt(seconds / 3600);
	seconds -= hours * 3600;
	minutes = parseInt(seconds / 60);
	seconds -= minutes * 60;
	var ret = "";
	if (days > 0)
	ret += days + " days ";
	if (days > 0 || hours > 0)
	ret += hours + " hrs ";
	if (days > 0 || hours > 0 || minutes > 0)
	ret += minutes + " min ";
	if (days == 0 && hours == 0)
	ret += seconds + " sec";
	return(ret);
}

/* Returns textual representation of distance in the format
* "N km M m". Does not include km if less than 1 km. Does not
* include meters if km >= 10.
*/
function formatLength(meters) {
	var km = parseInt(meters / 1000);
	meters -= km * 1000;
	var ret = "";
	if (km > 0)
	ret += km + " km ";
	if (km < 10)
	ret += meters + " m";
	return(ret);
}

/* Returns an HTML string representing the driving directions.
* Icons match the ones shown in the map. Addresses are used
* as headers where available.
*/
function formatDirections(gdir, mode) {
	var addr = tsp.getAddresses();
	var order = tsp.getOrder();
	var retStr = "<table class='gebddir' border=0 cell-spacing=0>\n";
	for (var i = 0; i < gdir.getNumRoutes(); ++i) {
		var route = gdir.getRoute(i);
		var colour = "g";
		var number = i+1;
		if (number == 1)
		colour = "r";
		retStr += "\t<tr class='heading'><td class='heading' width=40>"
		+ "<div class='centered-directions'><img src='/images/googlemap_icons/icon" + colour
		+ number + ".png'></div></td>"
		+ "<td class='heading'><div class='centered-directions'>";
		var headerStr;
		if (addr[order[i]] == null) {
			var prevI = (i == 0) ? gdir.getNumRoutes() - 1 : i-1;
			var latLng = gdir.getRoute(prevI).getEndLatLng();
			headerStr = "(" + gdir.getGeocode(i).Point.coordinates[1] + ", "
			+ gdir.getGeocode(i).Point.coordinates[0] + ")";
		} else {
			headerStr = addr[order[i]];
		}
		retStr += headerStr + "</div></td></tr>\n";
		for (var j = 0; j < route.getNumSteps(); ++j) {
			var classStr = "odd";
			if (j % 2 == 0) classStr = "even";
			retStr += "\t<tr class='text'><td class='" + classStr + "'></td>"
			+ "<td class='" + classStr + "'>"
			+ route.getStep(j).getDescriptionHtml() + "<div class='left-shift'>"
			+ route.getStep(j).getDistance().html + "</div></td></tr>\n";
		}
	}
	if (mode == 0) {
		var headerStr;
		if (addr[order[0]] == null) {
			var prevI = gdir.getNumRoutes() - 1;
			var latLng = gdir.getRoute(prevI).getEndLatLng();
			headerStr = "(" + latLng.lat() + ", " + latLng.lng() + ")";
		} else {
			headerStr = addr[order[0]];
		}
		retStr += "\t<tr class='heading'><td class='heading'>"
		+ "<div class='centered-directions'><img src='/images/googlemap_icons/iconr1.png'></div></td>"
		+ "<td class='heading'>"
		+ "<div class='centered-directions'>"
		+ headerStr + "</div></td></tr>\n";
	} else if (mode == 1) {
		var headerStr;
		if (addr[order[gdir.getNumRoutes()]] == null) {
			var latLng = gdir.getRoute(gdir.getNumRoutes() - 1).getEndLatLng();
			headerStr = "(" + latLng.lat() + ", " + latLng.lng() + ")";
		} else {
			headerStr = addr[order[gdir.getNumRoutes()]];
		}
		retStr += "\t<tr class='heading'><td class='heading'>"
		+ "<div class='centered-directions'><img src='/images/googlemap_icons/icong"
		+ (gdir.getNumRoutes() + 1) + ".png'></div></td>"
		+ "<td class='heading'>"
		+ "<div class='centered-directions'>"
		+ headerStr + "</div></td></tr>\n";
	}
	retStr += "</table>";
	return(retStr);
}

function createTomTomLink(gdir) {
	var addr = tsp.getAddresses();
	var order = tsp.getOrder();
	var addr2 = new Array();
	for (var i = 0; i < order.length; ++i)
	addr2[i] = addr[order[i]];
	var itn = createTomTomItineraryItn(gdir, addr2);
	var retStr = "<form method='GET' action='tomtom.php'>\n";
	retStr += "<input type='hidden' name='itn' value='" + itn + "' />\n";
	retStr += "<input type='submit' value='Send to TomTom' />\n";
	retStr += "</form>\n";
	return retStr;
}

function drawMarker(latlng, num) {
	var icon;
	var letter = num == 1 ? 'r' : 'b';
	icon = new GIcon(G_DEFAULT_ICON, "/images/googlemap_icons/icon" + letter + num + ".png");
	icon.printImage = "/images/googlemap_icons/icon" + letter + num + ".png";
	icon.mozPrintImage = "/images/googlemap_icons/icon" + letter + num + ".gif";
	gebMap.addOverlay(new GMarker(latlng, {icon: icon }));
}

function setViewportToCover(waypoints) {
	var bounds = new GLatLngBounds();
	for (var i = 0; i < waypoints.length; ++i) {
		bounds.extend(waypoints[i]);
	}
	gebMap.setCenter(bounds.getCenter());
	gebMap.setZoom(gebMap.getBoundsZoomLevel(bounds));
}

function loadAtStart(lat, lng, zoom) {
	if (GBrowserIsCompatible()) {
		gebMap = new GMap2(document.getElementById("map"), {draggableCursor:"crosshair"});
		directionsPanel = document.getElementById("my_textual_div");

		gebMap.setCenter(new GLatLng(lat, lng), zoom);
		gebMap.addControl(new GLargeMapControl());
		gebMap.addControl(new GMapTypeControl());
//		map = new GMap2(container, {draggableCursor:"crosshair"});
		
		tsp = new BpTspSolver(gebMap, directionsPanel);
		gebDirections = tsp.getGDirections();
		GEvent.addListener(gebDirections, "error", function() {
			alert("Request failed: " + reasons[gebDirections.getStatus().code]);
		});

		GEvent.addListener(gebMap, "click", function(marker, latLng) {
			if (marker == null) {
				tsp.addWaypoint(latLng);
				drawMarker(latLng, tsp.getWaypoints().length);
			} else {
				tsp.removeWaypoint(marker.getPoint());
				gebMap.removeOverlay(marker);
			}
		});
	}
	else {
		alert('Your browser is not compatible with this technology.\nPlease consider upgrading.');
	}
	// This loads the dragable routes
	// Uncomment the line below
//	loadDragable();
}

function addAddress(addr) {
	tsp.addAddress(addr, addAddressSuccessCallback);
}

function clickedAddAddress() {
	tsp.addAddress(document.address.addressStr.value, addAddressSuccessCallback2);
}

function clickedFromTo() {
	tsp.addAddress(document.address.driveTo.value, addAddressSuccessCallback2);
	tsp.addAddress(document.address.driveFrom.value, addAddressSuccessCallback2);

}

function addAddressSuccessCallback(address, latlng) {
	if (latlng)
	drawMarker(latlng, tsp.getWaypoints().length);
	else
	alert('Failed to geocode: ' + address);
}

function addAddressSuccessCallback2(address, latlng) {
	if (latlng) {
		drawMarker(latlng, tsp.getWaypoints().length);
		setViewportToCover(tsp.getWaypoints());
	}
	else
	alert('Failed to geocode: ' + address);
}

function startOver() {
	document.getElementById("my_textual_div").innerHTML = "";

	//  document.getElementById("path").innerHTML = "";
	gebMap.clearOverlays();
	tsp.startOver(); // doesn't clearOverlays or clear the directionsPanel
}

function directions(m, walking, avoid) {
	startOver();
	clickedFromTo();
	clickedAddList();
	gebMap.clearOverlays();
	mode = m;
	tsp.setAvoidHighways(avoid);
	if (walking)
	tsp.setTravelMode(G_TRAVEL_MODE_WALKING);
	else
	tsp.setTravelMode(G_TRAVEL_MODE_DRIVING);
	gebMap.clearOverlays();
	if (m == 0)
	tsp.solveRoundTrip(onSolveCallback);
	else
	tsp.solveAtoZ(onSolveCallback);






}

function onSolveCallback(myTsp) {
	var dir = tsp.getGDirections();
	// Print shortest roundtrip data:
	var pathStr = "<p>Trip duration: " + formatTime(dir.getDuration().seconds) + "<br>";
	pathStr += "Trip length: " + formatLength(dir.getDistance().meters) + "</p>";
	pathStr += "<input type='button' value='Toggle raw path output' onClick='toggle(\"exportData\");'>";
	document.getElementById("path").innerHTML = pathStr;
	document.getElementById("my_textual_div").innerHTML = formatDirections(dir, mode);
	//  document.getElementById("tomtom").innerHTML = createTomTomLink(dir);

	// Remove the standard google maps icons:
	for (var i = 0; i < gebDirections.getNumGeocodes(); ++i) {
		gebMap.removeOverlay(gebDirections.getMarker(i));
	}

	// Add nice, numbered icons instead:
	if (mode == 1) {
		var myPt1 = gebDirections.getRoute(0).getStep(0).getLatLng();
		var myIcn1 = new GIcon(G_DEFAULT_ICON,"/images/googlemap_icons/iconr1.png");
		myIcn1.printImage = "/images/googlemap_icons/iconr1.png";
		myIcn1.mozPrintImage = "/images/googlemap_icons/iconr1.gif";
		gebMap.addOverlay(new GMarker(myPt1,myIcn1));
	}
	for (var i = 0; i < gebDirections.getNumRoutes(); ++i) {
		var route = gebDirections.getRoute(i);
		var myPt1 = route.getEndLatLng();
		var myIcn1;
		if (i == gebDirections.getNumRoutes()-1 && mode == 0) {
			myIcn1 = new GIcon(G_DEFAULT_ICON,"/images/googlemap_icons/iconr1.png");
			myIcn1.printImage = "/images/googlemap_icons/iconr1.png";
			myIcn1.mozPrintImage = "/images/googlemap_icons/iconr1.gif";
		} else {
			myIcn1 = new GIcon(G_DEFAULT_ICON,"/images/googlemap_icons/icong" + (i+2) + ".png");
			myIcn1.printImage = "/images/googlemap_icons/icong" + (i+2) + ".png";
			myIcn1.mozPrintImage = "/images/googlemap_icons/icong" + (i+2) + ".gif";
		}
		gebMap.addOverlay(new GMarker(myPt1,myIcn1));
	}

	// Replace driving directions with custom made design:
	document.getElementById("my_textual_div").innerHTML
	= formatDirections(gebDirections, mode);

	var bestPathLatLngStr = "";
	for (var i = 0; i < gebDirections.getNumGeocodes(); ++i) {
		bestPathLatLngStr += "(" + gebDirections.getGeocode(i).Point.coordinates[1]
		+ ", " + gebDirections.getGeocode(i).Point.coordinates[0] + ")\n";
	}
	document.getElementById("exportData_hidden").innerHTML =
	"<textarea name='outputList' rows='10' cols='40'>"
	+ bestPathLatLngStr + "</textarea><br>";
}

function clickedAddList() {
	addList(document.address.inputList.value);
}

function addList(listStr) {
	var listArray = listStr.split("\n");
	for (var i = 0; i < listArray.length; ++i) {
		var listLine = listArray[i];
		if (listLine.match(/\(?\s*\-?\d+\s*,\s*\-?\d+/) ||
		listLine.match(/\(?\s*\-?\d+\s*,\s*\-?\d*\.\d+/) ||
		listLine.match(/\(?\s*\-?\d*\.\d+\s*,\s*\-?\d+/) ||
		listLine.match(/\(?\s*\-?\d*\.\d+\s*,\s*\-?\d*\.\d+/)) {
			// Line looks like lat, lng.
			var cleanStr = listLine.replace(/[^\d.,-]/g, "");
			var latLngArr = cleanStr.split(",");
			if (latLngArr.length == 2) {
				var lat = parseFloat(latLngArr[0]);
				var lng = parseFloat(latLngArr[1]);
				var latLng = new GLatLng(lat, lng);
				tsp.addWaypoint(latLng);
				drawMarker(latLng, tsp.getWaypoints().length);
			}
		} else if (listLine.match(/\S+/)) {
			// Non-empty line that does not look like lat, lng. Interpret as address.
			tsp.addAddress(listLine, addAddressSuccessCallback);
		}
	}
}
//
//
//
//
//////////////////////////##########//
/////////////////////////////////////
//
//
//
//var IE = document.all ? true : false;
//var map;
//var detailmap;
//var dirObj;
////var container; 	
//var opacity = 1;
//var clckTimeOut = null;
//var loading = false;
//var saveState = false;
//var directionsInfoDiv;
//var iw;
//var polyline;
//var pLine;
//var startMarker;
//var endMarker;
//var dragMarker;
//var pLinePoints = Array();
//var midRouteMarkers = Array();
//var markerDragging = false;
//var typeChanging = false;
//var baseIcon = new GIcon();
//baseIcon.iconSize=new GSize(16,16);
//baseIcon.iconAnchor=new GPoint(8,8);
//baseIcon.infoWindowAnchor=new GPoint(10,0);
//
//
//var yellowIcon = (new GIcon(baseIcon, "/images/yellowSquare.png", null, ""));
//var greenIcon = (new GIcon(baseIcon, "/images/greenCircle.png", null, ""));
//var redIcon = (new GIcon(baseIcon, "/images/redCircle.png", null, ""));
//var orangeIcon = (new GIcon(baseIcon, "/images/orangeCircle.png", null, ""));
//var blueIcon = (new GIcon(baseIcon, "/images/blueCircle.png", null, ""));
//var violetIcon = (new GIcon(baseIcon, "/images/violetCircle.png", null, ""));
//
//var baseIcon2 = new GIcon();
//baseIcon2.iconSize=new GSize(8,8);
//baseIcon2.iconAnchor=new GPoint(4,4);
//baseIcon2.infoWindowAnchor=new GPoint(4,0);
//var redIcon8 = (new GIcon(baseIcon2, "/images/redSquare_8.png", null, ""));
//
//
//
//
//
//var NormalLayer = G_NORMAL_MAP.getTileLayers()[0]
//var TerrainLayer = G_PHYSICAL_MAP.getTileLayers()[0]
//var SatelliteLayer = G_SATELLITE_MAP.getTileLayers()[0]
//var satProj = G_SATELLITE_MAP.getProjection();	
//var normalProj = G_NORMAL_MAP.getProjection();	
//
//	
//
//
//
//var cRight = new GCopyrightCollection('Cascade');
//var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, " Cascade Software ©2009");
//cRight.addCopyright(copyright);
//
//
//// Defaults --------------------------------------------
//var zoom = 8;
//var centerPoint = new GLatLng(51.54,0.0);
//var mType = 0;
//
//
//var USstates = Array('Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming')
//var pattern = '(' + USstates.join('|') + ')';
//
//
//function load() {
//	doLoad();
//}
//
//
//function loadDragable() {
//	if (GBrowserIsCompatible()) {
//		container = gebMap 		//document.getElementById("map");
//		//resizePage();
////		map = new GMap2(container, {draggableCursor:"crosshair"});
//		gebMap.addMapType(G_PHYSICAL_MAP)
//		TerrainLayer.getOpacity = function () {return opacity;};
//		var layers = [NormalLayer,TerrainLayer];
//		//addCustomMapType("Terrain N",layers,17,0);
//
//		directionsInfoDiv = document.getElementById("my_textual_div");
//		dirObj = new GDirections();
//
//		var mapState = getMapState();
//		if (typeof(mapState) != 'undefined') {
//			if (mapState['lat'] && mapState['lon']) {
//				centerPoint = new GLatLng(parseFloat(mapState['lat']), parseFloat(mapState['lon']));
//			}	
//			if (mapState['z']) {
//				zoom = parseInt(mapState['z']);
//			}
//			if (mapState['mType']) {
//				mType = parseInt(mapState['mType']);
//
//				if (mType == 4) {
//					opacity = 0.4;
//				}
//			}
//
//			
//			if (mapState['driveFrom']) {
//				var oDriveFrom = document.getElementById('driveFrom').value = mapState['driveFrom'];
//			}
//			if (mapState['driveTo']) {
//				var oDriveFrom = document.getElementById('driveTo').value = mapState['driveTo'];
//			}
//			if (mapState['driveVia']) {
//				var oDriveFrom = document.getElementById('driveVia').value = mapState['driveVia'];
//			}
//			if (mapState['locale']) {
//				var oDriveFrom = document.getElementById('locale').value = mapState['locale'];
//			}
//		}
//
//		gebMap.setCenter(centerPoint, zoom, gebMap.getMapTypes()[mType]);
//
////		map.addControl(new GScaleControl());
////		map.addControl(new GLargeMapControl());
////		map.addControl(new GMapTypeControl());
////map.addControl(new DragZoomControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(-10,10)));
//
////		map.enableDoubleClickZoom(); 
//		gebMap.enableContinuousZoom();
//		gebMap.enableScrollWheelZoom();
//
//		GEvent.addListener(gebMap, 'mousemove', mouseMove);
//		GEvent.addListener(gebMap, "moveend", moveEnd);
//		GEvent.addListener(gebMap, "zoomend", zoomEnd);
//		GEvent.addListener(gebMap, "maptypechanged", mapTypeChenged);
//		GEvent.addListener(gebMap, 'click', mapClick);
//
//		GEvent.addListener(dirObj, "load", onDirectionsLoad);
//		GEvent.addListener(dirObj, "error", onDirectionsError);
//
//		var ovcontrol = new GOverviewMapControl(new GSize(165,165));
//		gebMap.addControl(ovcontrol);
//		var ov_map = ovcontrol.getOverviewMap();
//		GEvent.addListener(gebMap, 'maptypechanged', function(){
////			ov_map.setMapType(G_NORMAL_MAP);
//		}); 
//
//		updateLink();
//
//		if (mapState['driveFrom'] && mapState['driveTo']) {
//			getDirections();
//		}
//
//	}
//}
//
//
//
//
//function addCustomMapType(mName,layers,maxRes,minRes) {
//	var TerrainN = new GMapType(layers, normalProj, mName, {maxResolution:maxRes, minResolution:minRes, errorMessage:'Boom!'}); 
//	gebMap.addMapType(TerrainN);
//}
//
//
//
//function mouseMove(mousePt) {
//	mouseLatLng = mousePt;
//	
//	var zoom = gebMap.getZoom();
//	var mousePx = normalProj.fromLatLngToPixel(mousePt, zoom);
//	var oStatusDiv = document.getElementById("mouseTrack")	
//	if (oStatusDiv) {
//		oStatusDiv.innerHTML = 'Mouse LatLng: ' + mousePt.y.toFixed(6) + ', ' + mousePt.x.toFixed(6) ;
//		oStatusDiv.innerHTML += '<br> ';
//		oStatusDiv.innerHTML += 'Mouse Px: ' + mousePx.x + ', ' + mousePx.y;
//		oStatusDiv.innerHTML += '<br>';
//		oStatusDiv.innerHTML += 'Tile: ' + Math.floor(mousePx.x / 256) + ', ' + Math.floor(mousePx.y / 256);
//	}
//
//getNearestVertex(mouseLatLng);
//
//}
//
//
//
//function mapTypeChenged() {
//	if (typeChanging) {
//		return;
//	}
//	typeChanging = true;
//
//	var mtype = gebMap.getCurrentMapType().getName();
//	if (mtype == 'Terrain N') {
//		opacity = 0.4;
//	}
//	else {
//		opacity = 1;
//	}
//	var currentType = gebMap.getCurrentMapType();
//	gebMap.setMapType(G_NORMAL_MAP);
//	gebMap.setMapType(currentType);
//	typeChanging = false;
//
//	updateLink();
//}
//
//function moveEnd() {
//	updateLink();
//}
//
//function zoomEnd(oldZ,zoom) {
//	updateLink();
//}
//
//
//
//function updateLink() {
//	var center = gebMap.getCenter();
//	var zoom = gebMap.getZoom();
//	var mTypes = gebMap.getMapTypes();
//	for (var n = 0 ; n < mTypes.length ; n++ ) {
//		if (mTypes[n] == gebMap.getCurrentMapType()) {
//			mType = n;
//		}
//	}
//
//	var bounds = gebMap.getBounds();
//	var SW = bounds.getSouthWest();
//	var NE = bounds.getNorthEast();
//
//	var oCoords = document.getElementById("coords");
//	oCoords.innerHTML = 'Map center: (' + center.lat().toFixed(6) + ',' + center.lng().toFixed(6) + ') - zoom: ' + zoom;
//	oCoords.innerHTML += '<br> ';
//	oCoords.innerHTML += 'SW: ' + SW.y.toFixed(6) + ', ' + SW.x.toFixed(6);
//	oCoords.innerHTML += '<br> ';
//	oCoords.innerHTML += 'NE: ' + NE.y.toFixed(6) + ', ' + NE.x.toFixed(6);
//
//	var oDriveFrom = document.getElementById('driveFrom');
//	var oDriveTo = document.getElementById('driveTo');
//	var oDriveVia = document.getElementById('inputList');
//	var oLocale = document.getElementById('locale');
//	
//	var link = window.location.pathname + '?lat=' + center.lat() + '&lon=' + center.lng() + '&z=' + zoom + '&mType=' + mType;
//	link += '&driveFrom=' + oDriveFrom.value;
//	link += '&driveTo=' + oDriveTo.value;
//	link += '&inputList=' + oDriveVia.value;
//	link += '&locale=' + oLocale.value;
//	
//	
///*
//	var oLink = document.getElementById("link");
//	oLink.innerHTML = '<a href="' + link + '">Link to this page</a>';
//*/
//}
//
//
//
//
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//
//function mapClick(marker, point) {
//	if (clckTimeOut) {
//		window.clearTimeout(clckTimeOut);
//		clckTimeOut = null;
//		doubleClick(marker, point);
//	}
//	else {
//		clckTimeOut = window.setTimeout(function(){singleClick(marker, point)},500);
//	}
//}
//
//function doubleClick(marker, point) {
//
//}
//
//function singleClick(marker, point) {
//	window.clearTimeout(clckTimeOut);
//	clckTimeOut = null;
//
//	if (point) {
//		if (!startMarker) {
//			var oDriveFrom = document.getElementById('driveFrom');
//			startMarker = new GMarker(point,{icon:greenIcon,draggable:true,bouncy:false});
//			startMarker.formField = oDriveFrom;
//			GEvent.addListener(startMarker,'drag',markerDrag);
//			GEvent.addListener(startMarker,'dragend',getDirections);
//			gebMap.addOverlay(startMarker);
//			oDriveFrom.value = startMarker.getPoint().lat().toFixed(6) + ',' + startMarker.getPoint().lng().toFixed(6);
//			return;
//		}
//		else if (!endMarker) {
//			var oDriveTo = document.getElementById('driveTo');
//			endMarker = new GMarker(point,{icon:redIcon,draggable:true,bouncy:false});
//			endMarker.formField = oDriveTo;
//			GEvent.addListener(endMarker,'drag',markerDrag);
//			GEvent.addListener(endMarker,'dragend',getDirections);
//			gebMap.addOverlay(endMarker);
//			oDriveTo.value = endMarker.getPoint().lat().toFixed(6) + ',' + endMarker.getPoint().lng().toFixed(6);
//			return;
//		}
//	}
//} 
//
//
//
//function markerDrag() {
//	this.formField.value = this.getPoint().lat().toFixed(5) + ',' + this.getPoint().lng().toFixed(5);
//}
//
//
//function indicateLoading() {
//	loading = true;
//	displayLoadingMsg();
//}
//
//function displayLoadingMsg() {
//	var oLMsg = document.getElementById('loadingMessage');
//	oLMsg.style.display = '';
//	oLMsg.style.left = container.offsetLeft + (container.clientWidth / 2) - (oLMsg.clientWidth / 2) + 'px';
//	oLMsg.style.top = container.offsetTop + (container.clientHeight / 2) - (oLMsg.clientHeight / 2) + 'px';
//	oLMsg.style.filter="alpha(opacity=70)";
//
//	if (loading){
//		var to = window.setTimeout('displayLoadingMsg()',100);
//	}
//	else {
//		oLMsg.style.display = 'none';
//	}
//}
//
//
//
//
//
//
//// Map state -------------------------------------------
//function getMapState() {
//	var qString = window.location.search;
//	qString = qString.substring(1, qString.length);
//
//	var cValues = new Array();
//	var separator = '&';
////	return cValues;
//
//	if (!qString) {
//		qString = getCookie('map2');
//		separator = ',';
//	}
//
//	if (qString) {
//		var nvPairs = qString.split(separator);
//
//		for (var n = 0 ; n < nvPairs.length ; n++ )	{
//			var nvPair = nvPairs[n];
//			var nv = nvPair.split('=');
//
//			cValues[nv[0]] = unescape(nv[1]);
//			
//		}
//	}
//	return cValues;
//}
//
//
//function getCookie(cookieName) {
//	if (document.cookie.length > 0) {
//		var cIndex = document.cookie.indexOf(cookieName+"=");
//		if (cIndex != -1) {
//			cIndex += cookieName.length + 1;
//			var cLength = document.cookie.indexOf(";", cIndex);
//			if (cLength == -1) {
//				cLength = document.cookie.length;
//			}
//			return unescape(document.cookie.substring(cIndex, cLength)); 
//		}
//	}
//	return null;
//}
//
//
//
//function setCookie(cookieName, value, expiredays) {
//	var exp = "";
//	if (expiredays) {
//		var ExpireDate = new Date ();
//		ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
//		exp = ExpireDate.toGMTString();
//	}
//	document.cookie = cookieName + "=" + escape(value) + "; expires=" + exp + "; path=/";
//}
//
//
//
//function delCookie (cookieName) {
//	if (getCookie(cookieName)) {
//		document.cookie = cookieName + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
//	}
//}
//
//// End Map state -------------------------------------------
//
//
//
//function resizePage() {
//
//	var oTable = document.getElementById("outerTable");
//	var dDiv = document.getElementById("directions_info");
//	
//	//oTable.style.width = document.body.clientWidth  + 'px';
//	var veHeight = 230;
//	//container.style.height = document.body.clientHeight - veHeight  + 'px';
//	//dDiv.style.height = document.body.clientHeight - veHeight + 65 + 'px';
//
//	if (gebMap) {
//		var center = gebMap.getCenter();
//		var zoom = gebMap.getZoom();
//		//map.checkResize();
//		//map.setCenter(center,zoom);
//	}
//}
//
//
//
//
//
//function unload() {
//	doUnload(0);
//}
//
//function doUnload(mReset) {
//	if (mReset) {
//		delCookie('map3');
//		saveState = false;
//		window.location = window.location.pathname;
//	}
//
//	if (saveState) {
//		var cookieStr = '';
//		var center = map.getCenter();
//
//		cookieStr += 'lat=' + center.lat() + ',';
//		cookieStr += 'lon=' + center.lng() + ',';
//		cookieStr += 'z=' + map.getZoom() + ',';
//		cookieStr += 'mType=' + mType + ',';
//		cookieStr += 'mapMode=' + mapMode;
//
//		setCookie('map3', cookieStr, 365);
//	}
//	GUnload();
//}
//
//function rmOverlays() {
//	directionsInfoDiv.innerHTML = '';
//	gebMap.clearOverlays();
//	//resizePage();
//	startMarker = null;
//	endMarker = null;
//}
//
//
//
//function getDirections() {
//	var oDriveFrom = document.getElementById('driveFrom');
//	var oDriveTo = document.getElementById('driveTo');
//	var oDriveVia = document.getElementById('inputList');
//	var oLocale = document.getElementById('locale');
//
//	directionsInfoDiv.style.display = '';
//
//	var loadStr;
//
//	if (oDriveFrom.value && oDriveTo.value) {
//		loadStr = 'from:' + oDriveFrom.value.replace(/\s/g,"+");
//		
//		if (oDriveVia.value) {
//			var viaValue = oDriveVia.value.replace(/[\n\r]+/,"");
//			var viaSteps = viaValue.split(';');
//			for (var n = 0 ; n < viaSteps.length ; n++ ) {
//				loadStr += ' to: ' + viaSteps[n];
//			}
//		}
//		loadStr += ' to: ' + oDriveTo.value;
//	}
//	if (loadStr) {
//	alert(loadStr);
//		indicateLoading();
//		dirObj.load(loadStr,{locale:oLocale.value,getPolyline:true,getSteps:true});
//		updateLink();
//	}
//
//}
//
//
//
//
//function onDirectionsLoad() {
//	var html = '';
//	var status = dirObj.getStatus();
//	var bounds = dirObj.getBounds();
//
//
//	gebMap.clearOverlays();
//
//	var copyrightHTML = dirObj.getCopyrightsHtml();
//	var summaryHTML = dirObj.getSummaryHtml();
//	var distance = dirObj.getDistance();
//	var duration = dirObj.getDuration();
//	var numRoutes = dirObj.getNumRoutes();
//	var oDriveFrom = document.getElementById('driveFrom');
//	var oDriveTo = document.getElementById('driveTo');
//	var startLatLng = dirObj.getRoute(0).getStep(0).getLatLng();
//	var endLatLng = dirObj.getRoute(numRoutes-1).getEndLatLng();
//
//	polyline = dirObj.getPolyline();
//	pLine = copyPolyline(polyline);
//	gebMap.addOverlay(polyline);
//
//	var numGeoCodes = dirObj.getNumGeocodes();
//	var startPoint = dirObj.getGeocode(0);
//	var endPoint = dirObj.getGeocode(numGeoCodes-1);
//	addDragMarker(startPoint);
//	
//	if (startMarker) {
//		var clickStartPoint = startMarker.getPoint();
//		if (clickStartPoint.distanceFrom(startLatLng) > 0) {
//			//html += 'WARNING: The route starts some distance away from the point clicked.<br>';
//		}
//	}
//
//	if (endMarker) {
//		var clickEndPoint = endMarker.getPoint();
//		if (clickEndPoint.distanceFrom(endLatLng) > 0) {
//			//html += 'WARNING: The route ends some distance away from the point clicked.<br>';
//		}
//	}
//
//	var realStartMarker = new GMarker(startLatLng,{icon:greenIcon,draggable:true,bouncy:false});
//	realStartMarker.formField = oDriveFrom;
//	GEvent.addListener(realStartMarker,'drag',markerDrag);
//	GEvent.addListener(realStartMarker,'dragend',getDirections);
//	gebMap.addOverlay(realStartMarker);
//
//	var realEndMarker = new GMarker(endLatLng,{icon:redIcon,draggable:true,bouncy:false});
//	GEvent.addListener(realEndMarker,'drag',markerDrag);
//	GEvent.addListener(realEndMarker,'dragend',getDirections);
//	realEndMarker.formField = oDriveTo;
//	gebMap.addOverlay(realEndMarker);
//
//
//	html += '<div class="globalSummaryDiv">';
//	html += '<table cellspacing="0" cellpadding="2" width="100%">';
//	html += '<tr><td valign="top"> <b>' + startPoint.address + '</b> to <b>' + endPoint.address + '</b></td></tr>';
//	html += '<tr><td valign="top"> '+summaryHTML+'</td></tr>';
//	html += '</table></div>';
//	
//	
//	for (var r = 0 ; r < numRoutes ; r++ ) {
//		var route = dirObj.getRoute(r);
//		var startGeoCode = dirObj.getGeocode(r);//route.getStartGeocode();
//		var endGeoCode = dirObj.getGeocode(r+1);//route.getEndGeocode();
//		var endLatLng = route.getEndLatLng();
//		var routeSummaryHTML = route.getSummaryHtml();
//		var routeDistance = route.getDistance();
//		var routeDuration = route.getDuration();
//		html += '<div class="routeSummaryDiv" onclick="toggleSteps('+r+')" title="Click to view steps">';
//		html += '<table cellspacing="0" cellpadding="2" width="100%">';
//		html += '<tr>';
//		
//		if (numRoutes == 1) {
//			html += '<td valign="top"><img src="/images/greenCircle.png"><br><img src="/images/redCircle.png"></td>';
//		}
//		else {
//			if (r == 0) {
//				html += '<td valign="top"><img src="/images/greenCircle.png"><br><img src="/images/yellowSquare.png"></td>';
//				var midMarker = new GMarker(endLatLng,{icon:yellowIcon});
//				gebMap.addOverlay(midMarker);
//			}
//			else if (r == numRoutes - 1) {
//				html += '<td valign="top"><img src="/images/yellowSquare.png"><br><img src="/images/redCircle.png"></td>';
//			}
//			else {
//				html += '<td valign="top"><img src="/images/yellowSquare.png"><br><img src="/images/yellowSquare.png"></td>';
//				var midMarker = new GMarker(endLatLng,{icon:yellowIcon});
//				gebMap.addOverlay(midMarker);
//			}
//		}
//		
//		html += '<td valign="top"><b>' + startGeoCode.address + '</b> to<br> <b>' + endGeoCode.address + '</b><br>'+routeDistance.html+ ' (' + routeDuration.html +  ')</td>';
//		html += '</table></div>';
//
//		var numSteps = route.getNumSteps();
//		html += '<table cellspacing="0" cellpadding="0" id="routeTable_'+r+'" style="display:none" width="100%">';
//		for (var s = 0 ; s < numSteps ; s++ ) {
//			var step = route.getStep(s);
//			var stepLatLng = step.getLatLng();
//			bounds.extend(stepLatLng);
//
//			var stepPolylineIndex = step.getPolylineIndex();
//			var stepDescriptionHTML = step.getDescriptionHtml();
//			var re = new RegExp(pattern,'g');
//			stepDescriptionHTML = stepDescriptionHTML.replace(re,'<b style="color:#CA0039">$1</b>')
//			var stepDistance = step.getDistance();
//			var stepDuration = step.getDuration();
//			html += '<tr class="stepRow" onclick="showStep('+r+','+s+')"><td>&nbsp;&nbsp;' + (s+1) + '.</td><td> ' + stepDescriptionHTML + '</td><td>' + stepDistance.html + '</td></tr>';
//		}
//		html += '</table>';
//	}
//	
//	directionsInfoDiv.innerHTML = html;
//	document.getElementById('dir_output').value = html;
//	loading = false;
//
//	gebMap.setCenter(bounds.getCenter(gebMap), gebMap.getBoundsZoomLevel(bounds)); 
//}
//
//
//function copyPolyline(p) {
//	pLinePoints = Array();
//	for (var n = 0 ; n < p.getVertexCount() ; n++ ) {
//		pLinePoints.push(p.getVertex(n));
//
//	}
//	var pLine = new GPolyline(pLinePoints,'#F7098A');
//	return pLine;
//}
//
//
//function addDragMarker(placemark) {
//	markerDragging = false;
//
//	var point = new GLatLng(placemark.Point.coordinates[1],placemark.Point.coordinates[0])
//
//	dragMarker = new GMarker(point, {icon:redIcon8,draggable:true,bouncy:false});
//	GEvent.addListener(dragMarker, 'dragend', function(){
//		var oDriveVia = document.getElementById('inputList');
//		if (oDriveVia.value) {
//			oDriveVia.value += ';\n';
//		}
//		oDriveVia.value += dragMarker.getPoint().lat().toFixed(5) + ',' + dragMarker.getPoint().lng().toFixed(5);
//		if (dragMarker) {
//			gebMap.removeOverlay(dragMarker);
//		}
//		getDirections();
//
//	});
//
//	GEvent.addListener(dragMarker, 'dragstart', function(){
//		markerDragging = true;
//	});
//
//	gebMap.addOverlay(dragMarker);
//	dragMarker.hide();
//}
//
//
//
//
//
//function getNearestVertex(mouseLatLng) {
//	if (markerDragging) {
//		return;
//	}
//	if (!dragMarker) {
//		return;
//	}
//
//	if (pLinePoints.length > 1){
//		var bounds = gebMap.getBounds();
//		var SW = bounds.getSouthWest();
//		var NE = bounds.getNorthEast();
//		var diag = SW.distanceFrom(NE);
//		threshold = diag / 100;
//		var minDist = 9999999999;
//		var intermediateIndex = Math.round(pLinePoints.length / 100);
//
//		for (var n = 0 ; n < pLinePoints.length-intermediateIndex ; n+= intermediateIndex ) {
//			if (mouseLatLng.distanceFrom(pLinePoints[n]) < minDist) {
//				minDist = mouseLatLng.distanceFrom(pLinePoints[n]);
//				if (minDist < threshold) {
//					dragMarker.show();
//					dragMarker.setLatLng(pLinePoints[n]);
//				}
//				else {
//					dragMarker.hide();
//				}
//			}
//		}
//	}
//}
//
//
//
//
//function onDirectionsError() {
//	loading = false;
//	directionsInfoDiv.innerHTML = 'Error: ' + dirObj.getStatus().code;
//}
//
//function toggleSteps(routeNo) {
//	oRouteTable = document.getElementById('routeTable_' + routeNo);
//	oRouteTable.style.display = oRouteTable.style.display == 'none' ? '' : 'none';
//}
//
//function showStep(r,s) {
//	gebMap.closeInfoWindow();
//	var step = dirObj.getRoute(r).getStep(s);
//	var stepLatLng = step.getLatLng();
//	var stepDescriptionHTML = step.getDescriptionHtml();
//	var re = new RegExp(pattern,'g');
//	stepDescriptionHTML = stepDescriptionHTML.replace(re,'<b style="color:#CA0039">$1</b>')
//	var stepDistance = step.getDistance();
//	var stepDuration = step.getDuration();
//
//	var infoHTML = '<div id="tab1" class="bubble">';
//	infoHTML += '<table>';
//	infoHTML += '<tr class="stepRow"><td>&nbsp;&nbsp;' + (s+1) + '.</td><td> ' + stepDescriptionHTML + '</td><td>' + stepDistance.html + '</td></tr>';
//	infoHTML += '<tr class="stepRow"><td>&nbsp;&nbsp;</td colspan="2"><td> ' + stepLatLng + '</td></tr>';
//	infoHTML += '</table>';
//	infoHTML += '</div>';
//
//
//
//	var tab1 = new GInfoWindowTab("Location", '<div id="detailmap"></div>');
//	var tab2 = new GInfoWindowTab("Info", infoHTML);
//	var infoTabs = [tab1,tab2];
//
//	gebMap.openInfoWindowTabsHtml(stepLatLng,infoTabs);
//
////	detailmap = null;
//// Minimap for driving directions
//	var dMapDiv = document.getElementById("detailmap");
//	detailmap = new GMap2(dMapDiv);
//	detailmap.setCenter(stepLatLng,15);
//
//	detailmap.addOverlay(pLine);
//
//	var CopyrightDiv = dMapDiv.firstChild.nextSibling;
//	var CopyrightImg = dMapDiv.firstChild.nextSibling.nextSibling;
//	CopyrightDiv.style.display = "none"; 
//	CopyrightImg.style.display = "none"; 
//
//	detailmap.addControl(new GSmallMapControl());
//
//
//}
