//globals
var tool;

var maps = [];
var currMap;
var mapEnabled = true;
var noMapClick = false;
var submitClicked = false;

var itinValid = [];
var currItinId;
var itinCount;

var locTmpl = [{txt:"",locsPending:0,lat:0,lng:0,landmarkid:0,islocality:"",stops:false,marker:"",circle:"",ready:false}];
var locList = [];

var selectList = [];			//list of data for open select list
var selectMarkers = [];		//list of location or stop select list map markers
var directions = [];			//used by walking dirs
var dirZoomed = false;		//used by walking dirs

var mapObjects = [];
var itinMapObj = [mapObjects];

var printMode = false;

var geoXmlBK;

var prevQuery;
var prevQueryTime;

var thMarkers = []; //transit hub marker objects

function init(fullScreenFlag) {
	fEntry("init");
	var mapCookie;
	currItinId = 0;

	if (!document.getElementById("loc0")) {
		fExit("init","No fields, enabled?");
		return;
	}

	fullScreen(fullScreenFlag);

	// instantiate location objects
	locList[0] = locTmpl.slice();
	locList[1] = locTmpl.slice();

	tool = document.getElementById("tool").value;

	tabSelect('navTab', tool == "TP" ? 0 : (tool == "SI" ? 1 : 2));

	if (tool != "TP")
		setTool(tool,true);

	document.getElementById("advOptChk").checked = false;
	resetLayers();

	var temp = window.location+" ";
	if (temp.search(/[?|&]map=0\D*/i) > 0)
		mapVisible(false);  // checkbox was unset by url parm
	else {
		mapCookie = getCookie("showMap");
		// use cookie, if existing
		if(mapCookie != "") {
			mapVisible(mapCookie == 1);
			if(mapCookie == 0)
				document.getElementById("showMap").checked = false;
		}
		else
			mapVisible(true);
	}

	// load js globals with values gotten from url, if any
	for (i in locList)
		if(document.getElementById("loc"+i).value != 'undefined') {
			locList[i].txt = document.getElementById("loc"+i).value;
			locList[i].locsPending = 0;
			locList[i].lat = document.getElementById("loc"+i+"lat").value;
			locList[i].lng = document.getElementById("loc"+i+"lng").value;
			locList[i].stops = !!(document.getElementById("stopmap").value & (i+1));
			locList[i].ready = false;
		}

	for( var i in locList )
		if (locList[i].txt == "") {
			divShow("divPromo");
			break;
		}

	formLogic();
	validateForm(false);
	document.getElementById("loc"+i).focus();

	//browserCheck();
	fExit("init");
}


function browserCheck() {
	var iecheck = /^.*;\s{1,2}MSIE\s[5-8].*$/

	if(iecheck.test(navigator.userAgent))
		if(getCookie("noBrwMsg") != 1)
			loadShowDiv("browserMsg", "browsermsg.htm");
}


function browserMsgClick() {
	divHide("browserMsg");
	if(document.getElementById("noBrwMsg").checked)
		setCookie("noBrwMsg",1,30);
}


function fullScreen(enabled) {
	var newVal, h = (typeof window.innerHeight != 'undefined' ? window.innerHeight : document.body.offsetHeight);
	//alert("h="+h);

	if (enabled)
		newVal = h-85;
	else
		newVal = 550;

	changecss('.heightFS','height',newVal);
	//changecss('#mapDiv > div','height',newVal);
}

// TRACE support - START
var indent;
function trace( msg ){
	if( typeof( jsTrace ) != 'undefined' ){
		jsTrace.send( msg );
	}
}
function fEntry(func,args) {
	var msg = "";

	if(indent == undefined)
		indent = 0;

	for (var i=0; i<indent; i++)
		msg += ".";

	trace( msg + "Enter: " + func + (args != undefined ? "(" + args + ")" : "") );

	indent += 1;
	//alert("entered "+func);
}
function fInfo(func,info) {
	var msg = "";

	for (var i=0; i<indent; i++)
		msg += ".";

	trace( msg + func +(info != undefined ? ": "+info : "") );
}
function fExit(func,results) {
	var msg = "";

	indent -= 1;

	for (var i=0; i<indent; i++)
		msg += ".";

	trace( msg + "Exit:  " + func + (results != undefined ? " with " + results : ""));

	if(!indent)
		trace('<span style="color:red">--------------------</span>');
}
// TRACE support - END


//create a map object and add controls
function setupMap(targetDivId,ctrCallback) {
	fEntry("setupMap",targetDivId);

	var map = new GMap2(document.getElementById(targetDivId));

	if(ctrCallback)
		ctrCallback(map);
	else
		setMapCenterAustin(map);

	map.addControl(new GLargeMapControl3D());
	map.addControl(new GHierarchicalMapTypeControl());

	// test start
	//map.enableContinuousZoom();
	// test end

	map.addControl(new GScaleControl());
	//map.addControl(new GOverviewMapControl());

	//map.enableContinuousZoom();
	map.enableScrollWheelZoom();
	//map.addOverlay(new GStreetviewOverlay());

	//if (tool != "TP")
	//map.addControl(new GOverviewMapControl());

	fExit("setupMap");
	return map;
}


//remove all google maps from screen and memory
function removeMap() {
	var targetElm = document.getElementById("plannerDiv");
	divVisible("mapDiv",false);
	mapEnabled = false;
}


function mapVisible(enabled,updateCookie) {
	fEntry("mapVisible",enabled);
	var plDiv = document.getElementById("plannerDiv");
	var iDiv = document.getElementById("itinDiv");
	var lPane = document.getElementById("itDivHolder");
	var rPane = document.getElementById("rightPane");
	var cbSA = document.getElementById("showSA");
	var cbBK = document.getElementById("showBK");
	var cbTH = document.getElementById("showTH");

	loading(false);
	showHelp(false);

	if (enabled) {
		divHide("divPromo");
		divVisible("mapDiv",true);
		lPane.appendChild(iDiv);

		iDiv.style.height = "";
		iDiv.style.overflow = "";

		if(currItinId) {
			fInfo( "mapVisible", "itinValid[currItinId]="+itinValid[currItinId]);
			if(itinMapObj[currItinId])
				fInfo( "mapVisible", "itinMapObj[currItinId].length="+itinMapObj[currItinId].length);
		}

		mapEnabled = true;

		if( !currItinId || !itinMapObj[currItinId] || (itinValid[currItinId] && itinMapObj[currItinId].length == 0) )
			showItin(currItinId);

		noMapClick = false;
	}
	else {
		divVisible("mapDiv",false);
		rPane.appendChild(iDiv);

		iDiv.style.height = "550px";
		//iDiv.style.height = "100%";
		iDiv.style.overflow = "auto";

		divShow("divPromo");
		//cbSA.checked = false;
		//cbBK.checked = false;
		mapEnabled = false;
	}

	if( updateCookie )
		setCookie("showMap",enabled ? 1 : 0,30);

	cbSA.disabled = !enabled;
	cbBK.disabled = !enabled;
	cbTH.disabled = !enabled;
	fExit("mapVisible");
}

//opts: type,label,content,title,onDblClick,stopId,setAsOpt
function addMapMarker(map,point,opts) {
	//fEntry("addMapMarker",opts.type+","+opts.stopId);
	var icon = new GIcon(G_DEFAULT_ICON);
	var marker, content, custIcon = true;

	if (opts.label >= "A" && opts.label <= "Z" && opts.label.length == 1)
		icon.image = 'http://maps.google.com/mapfiles/marker'+opts.label+'.png';
	else
		icon.shadow = '';
		switch(opts.type) {
			case "start":
				icon.image = 'http://www.google.com/mapfiles/dd-start.png';
				break;
			case "end":
				icon.image = 'http://www.google.com/mapfiles/dd-end.png';
				break;
			case "yellow":
				icon.image = 'http://maps.google.com/mapfiles/icon_yellow.png';
				break;
			case "onbus":
				icon.image = 'images/onbus.gif';
				icon.iconSize = new GSize(26,26);
				icon.iconAnchor = new GPoint(0,13);
				break;
			case "ontrain":
				icon.image = 'images/ontrain.gif';
				icon.iconSize = new GSize(26,26);
				icon.iconAnchor = new GPoint(0,13);
				break;
			case "offbus":
				icon.image = 'images/offbus.gif';
				icon.iconSize = new GSize(26,26);
				icon.iconAnchor = new GPoint(24,13);
				break;
			case "offtrain":
				icon.image = 'images/offtrain.gif';
				icon.iconSize = new GSize(26,26);
				icon.iconAnchor = new GPoint(24,13);
				break;
			case "walk":
				icon.image = 'images/walkmap2.gif';
				icon.iconSize = new GSize(32,32);
				icon.iconAnchor = new GPoint(0,0);
				break;
			case "transfer":
				icon.image = 'images/transfer3.gif';
				icon.iconSize = new GSize(26,26);
				icon.iconAnchor = new GPoint(13,13);
				break;
			case "stop":
				icon.image = 'images/stop.gif';
				icon.iconSize = new GSize(12,12);
				icon.iconAnchor = new GPoint(6,6);
				icon.title = opts.title;
				break;
			case "arrow":
				icon.image = 'http://www.google.com/mapfiles/arrow.png';
				break;
			case "pnr":
				icon.image = 'images/hub_pr.gif';
				icon.iconSize = new GSize(24,24);
				icon.iconAnchor = new GPoint(8,8);
				break;
			case "rst":
				icon.image = 'images/hub_rs.gif';
				icon.iconSize = new GSize(24,24);
				icon.iconAnchor = new GPoint(16,16);
				break;
			case "trc":
				icon.image = 'images/hub_tc.gif';
				icon.iconSize = new GSize(24,24);
				icon.iconAnchor = new GPoint(12,12);
				break;
			default:
				custIcon = false;
				break;
		}

	markerOptions = { icon:icon };
	markerOptions.title = opts.title;

	if (custIcon)
		marker = new GMarker(point, markerOptions);
	else
		marker = new GMarker(point);

	map.addOverlay(marker);

	if (content = opts.content)  //assign
		if (content.substr(0,4) == "div:")
			GEvent.addListener(marker, "click",
				function() {
					if (!printMode)
						marker.openInfoWindowHtml(document.getElementById(content.substr(4)).innerHTML);
				}
			);
		else {
			//content += '<div class="markerLinks">'+ getMarkerLinks(opts.setAsOpt,point,opts.stopId,opts.title) + '</div>';
			content = '<img src="'+icon.image+'" class="imgBullet"/>'+content+'<div class="markerLinks">'
				+ getMarkerLinks(opts.setAsOpt,point,opts.stopId,opts.title) + '</div>';

			GEvent.addListener(marker, "click",
				function() {
					if (!printMode)
						marker.openInfoWindowHtml( content );
				}
			);
		}

	if (opts.onDblClick)
		GEvent.addListener(marker, "dblclick", opts.onDblClick);

	//fExit("addMapMarker");
	return marker;
}


function getMarkerLinks(setAsOpt,point,stopId,txt) {
	var ret = "";

	if (setAsOpt == undefined || setAsOpt) {
		//var func = point && !stopId ? "setLocToMapPoint" : "setLoc";
		var func = point && (!stopId && !txt) ? "setLocToMapPoint" : "setLoc";
		var args = stopId ? stopId : (txt ? '"'+txt+'"' : point.lat()+","+point.lng());

		ret += "<p>Set as:</p>"
			+ "<a href='#' onClick='"+func+"(0,"+args+")'>Starting location</a>";

		if (tool == "TP")
			ret += "<a href='#' onClick='"+func+"(1,"+args+")'>Ending location</a>";
	}

	//ret += "<p>Search for nearby:</p>"
	//	+ '<a href="">Service</a><a href="">Stops</a><a href="">Landmarks</a>';

	return ret;
}


function addStopMarker(map,sType,lat,lng,stopId,stopName,route,isStartEnd) {
	var content, locText;

	switch (sType) {
		case "stop":
			content = "Transit stop along route "+route;
			break;
		case "onbus":
			content = "Get on the bus";
			break;
		case "offbus":
			content = "Get off the bus";
			break;
		case "ontrain":
			content = "Get on the train";
			break;
		case "offtrain":
			content = "Get off the train";
			break;
	}
	/*
	content = "<div class='stopIW'><img src='images/" + sType + ".gif' alt='Stop Marker' /><p>"
		+ content + ":</p><br/><br/><a href='/gismaps/stops/"
		+ stopId + ".html' target='_blank' title='Stop Details'>"
		+ stopName + "</a></div>";
	*/

	content += ":<br/><br/>&nbsp;&nbsp;<a href='/gismaps/stops/"
		+stopId+".html' target='_blank' title='Stop Details'><small>"+stopName+"</small></a>";

	return addMapMarker(map,new GLatLng(lat,lng),{type:sType,content:content,title:stopName,stopId:stopId,setAsOpt:!isStartEnd});
}


function addClickListener (map) {
	GEvent.addListener(map,"click",
		function(overlay, latlng) {
			if (latlng && !noMapClick && !printMode) {
				var content = '<div class="markerLinks"><b>Map point:</b><br/>'
					+ "<p style='margin-left:15px'>"+roundToPlaces(latlng.lat(),6)+","+roundToPlaces(latlng.lng(),6)+"</p>";

				content += getMarkerLinks(true,latlng);

				//content += "zoom=" + currMap.getZoom();

				content +=
					'</div><div class="iwFooter"><input type="checkbox" name="noMapClick" ' +
					'onclick="mapClick();">' +
					"<span onclick='mapClick();'>Don't ask (click to zoom only)</span></div>";

				map.openInfoWindow(latlng, content);
			}
		}
	);
}


function mapClick() {
	noMapClick = !noMapClick;
	if(noMapClick)
		alert("This can be re-enabled by toggling Show Map or with a browser refresh.");
	currMap.closeInfoWindow();
}


// set center and zoom according to specified bounds
function setZoomCenter(map, bounds, maxZoom, pan) {
	//fEntry("setZoomCenter");
	var zoomLevel = map.getBoundsZoomLevel(bounds);
	map.checkResize();

	//alert ("BEFORE:\ntop margin: "+map.fromLatLngToContainerPixel(bounds.getNorthEast()).y+"\n"
	//	+ "left margin: "+map.fromLatLngToContainerPixel(bounds.getSouthWest()).x);

	//map.addOverlay(new GPolyline([bounds.getNorthEast(),bounds.getSouthWest()], "#000000", 2, 1));

	if (zoomLevel < 9)
		zoomLevel = 9;

	if (pan) {
		map.setZoom(zoomLevel);
		map.panTo(bounds.getCenter());
	}
	else
		map.setCenter(bounds.getCenter(), zoomLevel);

	// if map overlays don't have sufficient margin, zoom out one level
	if (map.fromLatLngToContainerPixel(bounds.getNorthEast()).y < 30
		|| map.fromLatLngToContainerPixel(bounds.getSouthWest()).x < 15) {
		map.zoomOut();
		//alert ("AFTER:\ntop margin: "+map.fromLatLngToContainerPixel(bounds.getNorthEast()).y+"\n"
		//	+ "left margin: "+map.fromLatLngToContainerPixel(bounds.getSouthWest()).x);
	}

	//enforce max zoom level, if specified (higher number = more zoom)
	if (parseInt(maxZoom) > 0 && map.getZoom() > maxZoom)
		map.setZoom( maxZoom );

	map.savePosition();
	//fExit("setZoomCenter");
}


//function putCircle(map,center,radius,origDest) {
function putCircle(map,center,radius,color,opacity) {
	var max = 2*Math.PI;
	var inc = max/48, pts = [];
	var mult = 0.0144570, yadj = 1.157319;
	var dfltColor = "#FF0000";

	for(var t = max; t >= 0; t -= inc)
		pts[pts.length] =
			new GLatLng(
				Math.cos(t)*radius*mult+parseFloat(center.lat()),
				Math.sin(t)*radius*mult*yadj+parseFloat(center.lng())
			);

	var overlay = new GPolygon(pts, color ? color : dfltColor, 1, .3, color ? color : dfltColor, opacity, {clickable:false});
	map.addOverlay(overlay);

	return overlay;
}


// plot location marker and walking circle for given locId
function putLocMarker(locId,interactive) {
	fEntry("putLocMarker",locId);
	var loc = locList[locId];
	var gPnt = new GLatLng(loc.lat,loc.lng);

	//if (tool != "SN")
	//	putWalkDistCircle(currMap, locId);

	fInfo("putLocMarker",2);
	loc.marker = addMapMarker(currMap, gPnt, {type:"yellow",content:loc.txt});

	if( interactive )
		if (locReadyCount() > 0) {
			var bounds = new GLatLngBounds;
			for ( var i = 0; i < locList.length; i++ )
				if (locList[i].lat != undefined && locList[i].lat != 0)
					bounds.extend(new GLatLng(locList[i].lat, locList[i].lng));

			setZoomCenter(currMap,bounds,13);
		}
		else
			currMap.panTo(gPnt);

	fExit("putLocMarker");
}


function putWalkDistCircle(map,locId) {
	fEntry("putWalkDistCircle",locId);
	var loc = locList[locId];
	var gPnt = new GLatLng(loc.lat,loc.lng);

	if(loc.circle != undefined)
		map.removeOverlay(loc.circle);

	loc.circle = putCircle(map,gPnt,document.getElementById("maxwalk").value,(locId == 0) ? "green" : "red", 0.15);

	fExit("putWalkDistCircle");
	return loc.circle;
}


function walkTrace(walkId) {
	fEntry("walkTrace",walkId);
	var label = "walk" + walkId;
	var directionsPanel = document.getElementById(label+"div");
	var query = "from:"+ document.getElementById(label+"from").value +	" to:" + document.getElementById(label+"to").value;
	var flag = (directionsPanel.innerHTML == "");
	var map = maps[document.getElementById(label+"map").value];

	if (directions[walkId]) {
		directions[walkId].clear();
		directions[walkId] = null;
		if (mapEnabled) {
			map.returnToSavedPosition();
			dirZoomed = false;
		}
	}

	if (flag) {
		if (mapEnabled && !dirZoomed)
			map.savePosition();
		directions[walkId] = new GDirections(map, directionsPanel);
		directions[walkId].load(query,{travelMode:G_TRAVEL_MODE_WALKING /*,getSteps:!mapEnabled */});
		if (mapEnabled) {
			map.zoomOut();
			dirZoomed = true;
		}
	}
	fExit("walkTrace");
}


// make sure at least one mode is checked
function modesClicked(elem) {
	var x = document.getElementsByName("itMode");
	var flag = false;

	for (var i = 0; i < x.length; i++)
		if(x[i].style.display != 'none' && (flag = x[i].checked))
			break;

	if (!flag) {
		elem.checked = true;
		alert("At least one transit method must be selected.");
	}
}


function setupPlannerMap(targetDivId,matchZoom) {
	fEntry("setupPlannerMap",targetDivId);
	var map;

	if (mapEnabled) {
		map = setupMap(targetDivId,
			function (m) {
				if (matchZoom && maps[0])
					m.setCenter(maps[0].getCenter(),maps[0].getZoom());
				else
					setMapCenterAustin(m);
			});

		if (tool != "TP")
			map.addControl(new GOverviewMapControl());

		addClickListener(map);
	}
	fExit("setupPlannerMap");
	return map;
}


function setMapCenterAustin(map) {
	map.setCenter(new GLatLng(30.268713,-97.745206), 11);
}


function showItin( itinId ) {
	fEntry("showItin",itinId);
	var mapElem = document.getElementById("mapCanvas"+itinId);

	for( var i=0; i<itinCount; i++ )
		divVisible("itinDataDiv"+i, i == itinId);

	currItinId = itinId;

	if (mapEnabled && mapElem)
		try {
			if (GBrowserIsCompatible()) {
				divVisible("helpDiv",false);
				for( var i=0; i<itinCount; i++ )
					divVisible("mapCanvas"+i, i == itinId);

				if (itinValid[itinId] && itinMapObj[itinId] && itinMapObj[itinId].length > 0) {
					fExit("showItin","already done");
					return;
				}

				if (maps[itinId] == undefined)
					maps[itinId] = setupPlannerMap("mapCanvas"+itinId,true);
				else
					clearMap(maps[itinId]);

				currMap = maps[itinId];

				//for (var i in locList)
				//	putWalkDistCircle(currMap,i);

				if(itinCount > 0) {
					loading(true);
					if (tool == "TP")
						mapTrace(itinId);
					else
						mapService();
				}
			}
			else
				mapElem.innerHTML = "Browser not compatible with Google Maps";
		}
		catch (err) {
			logAppend("map_fail:"+err);
			alert("An unexpected error is preventing the map from being displayed.\n\nWe apologize for the inconvenience.  Please try again soon.");
			//alert(err);
			mapVisible(false,false);
		}

	itinValid[itinId] = true;
	fExit("showItin");
}


function getToolName (tool) {
	switch (tool) {
		case "TP":
			return "Trip Planner";
		case "SN":
			return "Service Nearby";
		case "SI":
			return "Schedule Info";
		case "NB":
			return "Next Trip";
	}
}


function getToolDesc (tool) {
	switch (tool) {
		case "TP":
			return "Get step by step travel directions for using Capital Metro routes";
		case "SN":
			return "Find all routes that serve a specific location";
		case "SI":
			return "Find routes and schedules that serve a specific location and time";
		case "NB":
			return "Find the nearest transit stop to a location for a selected route and the time of the next trip for that route";
	}
}


function getLegTraceColor (legNo) {
	// set leg trace and legend color
	switch ( legNo ) {
		case 1:
			return "#0000FF";		// blue
		case 2:
			return "#00FF00";		// green
		case 3:
			return "#FF00FF";		// magenta
		case 4:
			return "#008000";		// dark green
		case 5:
			return "#00FFFF";		// cyan
		default:
			return "#666666";		// gray
	}
}


function mapTrace (itinId) {
	fEntry("mapTrace",itinId);
	fInfo("mapTrace","Itintrace (ASYNC)");

	soapRequest('s_itintrace.asp?Traceinfo=' + document.getElementById("Traceinfo"+itinId).value,
		function (rData) {
			fInfo("mapTrace","back from Itintrace");
			var data = rData.ItintraceResponse;

			if (data)
				mapTrace1 ( data, itinId );
		}
	);
	fExit("mapTrace");
}


// load the specified div with map of specified itinerary
function mapTrace1 ( trace, itinId ) {
	fEntry("mapTrace1", itinId);
	var tMode, vType, pSegDest;
	var stpCnt, sIcon, sPoint;
	var polyline = new GPolyline;
	var pOrig = new GLatLng(locList[0].lat, locList[0].lng);
	var pDest = new GLatLng(locList[1].lat, locList[1].lng);
	var thruRoute, trPrev = false, trCurr;
	var elm, fromLL;
	var iMO = itinMapObj[itinId];

	if (iMO == undefined) {
		itinMapObj[itinId] = mapObjects.slice();
		iMO = itinMapObj[itinId];
	}

	for (var i in trace.Legs.Leg) {
		var Leg, legCount = trace.Legs.Leg.length;

		if (legCount != undefined)
			Leg = trace.Legs.Leg[i];
		else {
			i = 0;
			Leg = trace.Legs.Leg;
			legCount = 1;
		}

		if (Leg.Route == "550") {
			tMode = "T";
			vType = "train";
		}
		else {
			tMode = "B";
			vType = "bus";
		}

		var Points = Leg.Points.Point;
		pointCount = Points.length;

		pSegDest = Points[pointCount-1];

		var points2 = [];
		for (var j in Points)
			if (Points[j] != "")
				points2[j] = new GLatLng(Points[j].split(",")[0],Points[j].split(",")[1]);

		polyline = new GPolyline(points2, ((tMode == "B") ? getLegTraceColor(i*1+1) : "#FF0000"), 6, 0.7, {clickable:false});

		currMap.addOverlay(iMO[iMO.length] = polyline);

		//plot stops
		var Stops = Leg.Stops.Stop;
		stpCnt = Stops.length;

		trCurr = document.getElementById("thruRoute"+itinId+"_"+(i-0+1)) != undefined;

		for (var k in Stops) {
			thruRoute = false;
			if (k == 0 || k == stpCnt-1) {
				thruRoute = legCount > 1 && ((k == 0 && trPrev) || (k == stpCnt-1 && trCurr));
				//fInfo("mapTrace1","leg="+i+"/"+legCount+" stop="+k+"/"+stpCnt+" trPrev="+trPrev+" trCurr="+trCurr+" --> "+thruRoute);
			}

			if (k == 0 && !thruRoute)
				sIcon = "on" + vType;
			else if (k == stpCnt-1 && !thruRoute)
				sIcon = "off" + vType;
			else
				sIcon = "stop";

			sPoint = Stops[k].Point;

			var startEnd = !((i > 0 || k > 0) && (i < trace.Legs.Leg.length-1 || k < stpCnt-1));

			iMO[iMO.length] = addStopMarker(currMap, sIcon, sPoint.split(",")[0],
				sPoint.split(",")[1], Stops[k].Stopid, Stops[k].Description,Leg.Route,startEnd);
		}
		trPrev = trCurr;
	}

	// plot walk markers
	/*
	for(var i = 0; i < 20; i++)
		if ((elm = document.getElementById("walk"+i+"map")) && elm.value == itinId) {
			fromLL = document.getElementById("walk"+i+"from").value;
			iMO[iMO.length] = addMapMarker(currMap,new GLatLng(fromLL.split(",")[0],fromLL.split(",")[1]),
				{type:"walk",setAsOpt:false});  // ,content:"<img src='images/walk2.gif' class='imgBullet' alt='Walk'/> Start of walk"}
		}
	*/

	iMO[iMO.length] = addMapMarker(currMap, pOrig, {type:"start",title:"Starting Location",setAsOpt:false,
		//content:"<img src='images/cir-start.gif' class='imgBullet' alt='Start'/> Starting Location:<br><br>&nbsp;&nbsp;&nbsp;" + locList[0].txt});
		content:"Starting Location:<br><br>&nbsp;&nbsp;&nbsp;" + locList[0].txt});

	iMO[iMO.length] = addMapMarker(currMap, pDest, {type:"end",title:"Ending Location",setAsOpt:false,
		//content:"<img src='images/cir-end.gif' class='imgBullet' alt='End'/> Ending Location:<br><br>&nbsp;&nbsp;&nbsp;" + locList[1].txt});
		content:"Ending Location:<br><br>&nbsp;&nbsp;&nbsp;" + locList[1].txt});

	fInfo("mapTrace1","iMO.length="+iMO.length);

	mapRecenter( itinId, false );

	itinGenerated();

	fExit("mapTrace1");
}


//show map objects for Service Nearby, Next Trip, and Schedule Info
function mapService() {
	fEntry("mapService");
	var map = maps[0];
	var elm, lat, label;
	var iMO = itinMapObj[0];
	var pOrig = new GLatLng(locList[0].lat, locList[0].lng);

	iMO[iMO.length] = addMapMarker(map, pOrig, {type:"start",title:"Starting Location",setAsOpt:false,
		content:"<img src='images/cir-start.gif' class='imgBullet' alt='Start'/> Starting Location:<br><br>&nbsp;&nbsp;&nbsp;" + locList[0].txt});

	for (var i=0; i<26; i++) {
		if ( (elm = document.getElementById("Stoplat"+i)) == undefined )
			break;
		lat = elm.value;
		label = String.fromCharCode(i+65);
		point = new GLatLng(lat,document.getElementById("Stoplong"+i).value);
		iMO[iMO.length] = addMapMarker(map,point,{label:label,content:'div:divStop'+label});
	}

	mapRecenter( 0, false );

	itinValid[0] = true;
	itinGenerated();

	fExit("mapService");
}


function mapRecenter( itinId, pan ) {
	fEntry("mapRecenter", itinId+","+pan);
	var bounds = new GLatLngBounds;
	var iMO = itinMapObj[itinId];

	currMap.checkResize();

	if( locList[0].lat-0 != 0)
		bounds.extend(new GLatLng(locList[0].lat, locList[0].lng));

	if( tool == "TP" && locList[1].lat-0 != 0)
		bounds.extend(new GLatLng(locList[1].lat, locList[1].lng));

	for (var i in iMO)
		try {
			// assume it's a marker
			bounds.extend(iMO[i].getLatLng());
		}
		catch(e) {
			// assume it's a polyline
			bounds.extend(iMO[i].getBounds().getSouthWest());
			bounds.extend(iMO[i].getBounds().getNorthEast());
		}

	setZoomCenter(currMap,bounds,15,pan);
	fExit("mapRecenter");
}


function toggleHelp() {
	if (!divIsVisible("helpDiv")) {
		if(mapEnabled)
			divHide("mapDiv");
		else
			divHide("itinDiv");

		logAppend("help");
	}

	//loadToggleDiv("helpDiv","doc/plannerFAQ.asp");
	loadToggleDiv("helpDiv","help.htm");

	if (!divIsVisible("helpDiv"))
		if(mapEnabled)
			divShow("mapDiv");
		else
			divShow("itinDiv");



	return false;
}


function showHelp(enabled) {
	if (enabled && !divIsVisible("helpDiv") || !enabled && divIsVisible("helpDiv"))
		toggleHelp();
}


function enablePrint(enabled) {
	fEntry("enablePrint",enabled);
	document.getElementById("printIcon").style.opacity = enabled ? "1.0" : "0.5";
	document.getElementById("printIcon").style.filter = enabled ? "alpha(opacity=100)" : "alpha(opacity=50)";
	document.getElementById("printIcon").value = enabled ? "1" : "0";

	document.getElementById("bmIcon").style.opacity = enabled ? "1.0" : "0.5";
	document.getElementById("bmIcon").style.filter = enabled ? "alpha(opacity=100)" : "alpha(opacity=50)";
	document.getElementById("bmIcon").value = enabled ? "1" : "0";
	fExit("enablePrint");
}


function itinGenerated() {
	fEntry("itinGenerated");
	loading(false);

	document.getElementById("bmLink").href = createUrl(true);
	enablePrint(true);

	fExit("itinGenerated");
}


// RESET functions  START

function resetPage() {
	fEntry("resetPage");

	resetHeader();
	resetForm();
	divShow("divPromo");

	currItinId = 0;
	itinCount = 0;

	if (mapEnabled) {
		maps = [];
		maps[0] = setupPlannerMap("mapCanvas0");
		currMap = maps[0];
	}

	resetLayers();

	fExit("resetPage");
}


function resetLayers() {
	document.getElementById("showSA").checked = false;
	document.getElementById("showBK").checked = false;
	document.getElementById("showTH").checked = false;
}


function resetHeader() {
	fEntry("resetHeader");
	document.title = getToolName(tool);

	document.getElementById("mainHeader").innerHTML =
		"<b>" + document.title + ": </b>" + getToolDesc(tool);
	fExit("resetHeader");
}


function resetForm() {
	fEntry("resetForm");

	hideSelectors();

	resetLoc(0);
	resetLoc(1,true);

	locList[0].txt = "";
	locList[1].txt = "";

	document.getElementById("loc0").value = "";
	document.getElementById("stopmap").value = "0";

	if (tool == "TP") {
		document.getElementById("loc1").value = "";
		setSelected("arrdep","N");
	}

	resetAdvOpts();
	divHide("advOpt");
	document.getElementById("advOptChk").checked = false;

	var now = new Date();

	if (tool != "SN") {
		//if (document.getElementById("datepicker1"))
		document.getElementById("datepicker1").value = now.format("m/d/yyyy");

		//if (document.getElementById("timepicker1"))
		document.getElementById("timepicker1").value = now.format("h:MM TT");
	}

	document.getElementById("loc0").focus();
	formLogic();

	fExit("resetForm");
}


function resetAdvOpts() {
	setSelected("maxwalk","0.75");
	document.getElementById("modeB").checked = true;
	document.getElementById("modeT").checked = true;

	if (tool == "TP") {
		setSelected("minimize","X");
		setSelected("firstroute","");
		setSelected("lastroute","");
	}
	else if (tool == "SI")
		setSelected("itRoute","");
}


function resetLoc(locId,noResetItin) {
	fEntry("resetLoc",locId);
	var loc = locList[locId];

	if(locId == 0)
		setLocIcon(0,"cir-start.gif","Starting location");
	else if(locId == 1)
		setLocIcon(1,"cir-end.gif","Ending location");

	if ( mapEnabled ) {
		if (loc.marker != undefined && loc.marker != "")
			currMap.removeOverlay(loc.marker);

		if (loc.circle != undefined && loc.circle != "")
			currMap.removeOverlay(loc.circle);
	}

	loc.lat 		= 0;
	loc.lng 		= 0;
	loc.stops		= false;
	loc.marker	= "";
	loc.circle	= "";
	loc.ready		=	false;

	document.getElementById("loc"+locId+"lat").value = "";
	document.getElementById("loc"+locId+"lng").value = "";
	document.getElementById("stopmap").value &= ~(locId+1);

	if(!noResetItin)
		resetItineraries();

	fExit("resetLoc");
}


function resetItineraries() {
	fEntry("resetItineraries");
	var flag = false;
	try {
		document.getElementById("itinDiv").innerHTML = "";
	}
	catch(err) {
		return;
	}

	resetHeader();

	if(mapEnabled && currMap)
		clearMap(currMap);

	for (var i in itinValid)
		itinValid[i] = false;

	// if other locations are blank, recenter map

	for (var i in locList)
		if(locList[i].txt != "")
			flag = true;

	if(mapEnabled && !flag)
		setMapCenterAustin(currMap);

	submitClicked = false;

	itinCleared();
	fExit("resetItineraries");
}


function clearMap(map) {
	map.closeInfoWindow();
	clearItinMapObjects();
	map.clearOverlays();

	for (i in directions)
		try {
			directions[i].clear();
		}
		catch(err) {}

	directions = [];

	resetLayers();
}


function clearItinMapObjects() {
	fEntry("clearItinMapObjects", currItinId);
	var iMO;

	for(var i in itinMapObj) {
		//var i = currItinId;
		iMO = itinMapObj[i];
		for(var j in iMO)
			currMap.removeOverlay(iMO[j]);

		itinMapObj[i].splice(0,itinMapObj[i].length);  // clear array items for this itin
	}

	fExit("clearItinMapObjects");
}


function itinCleared() {
	document.getElementById("bmLink").href = "javascript:void(0)";
	enablePrint(false);
}


// RESET functions  END


function fixRetry(optId) {
	var temp, form = document.forms[0];

	if (optId == 1) {  // resubmit with all modes
		//for (var i in form.itMode)
		//	form.itMode[i].checked = true;

		var x = document.getElementsByName("itMode");
		for (var i = 0; i < x.length; i++)
			x[i].checked = true;

		prevQuery = "";
		validateForm(true);
	}
	else if (optId == 4 || optId == 5) { // set depart/arrive time
		form.itType.value = (optId == 4 ? "D" : "A");
		formLogic();
		form.itStTime.select();
	}
	else if (optId == 6) // set start loc
		form.itOrig.select();
	else if (optId == 7) // set end loc
		form.itDest.select();
	else if (optId == 8) { // increase walk dist
		temp = form.itMaxWalk.value - 0;

		if ((temp += .25) > 0.999)
			temp = 0.999;

		setSelected("maxwalk",temp);

		if (temp != .75) {
			document.getElementById("advOptChk").checked = true;
			divVisible("advOpt",true);
		}

		walkChanged();
		validateForm(true);
	}
	else if (optId == 9)  // change start time
		form.itStTime.select();
	else if (optId == 10) { // allow all routes
		setSelected("firstroute","");
		setSelected("lastroute","");
		validateForm(true);
	}
	else
		alert("Retry request with option "+optId);

	return false;
}


function loading(status) {
	divVisible("imgWait",status);
}
