// JavaScript Document



var trailState;

// Direction variables
var INCREMENT = 1;
var DECREMENT = 2;

// Orientation variables
var FRONT = 1; 
var LEFT = 2;
var RIGHT = 3;

// Vertical Orientation variables
var STRAIGHT = 4;
var UP = 5;

var FORWARD = 0;
var BACKWARD = 1;

// Trail indecies
var LNG_I = 0;
var LAT_I = 1;
var DIR_I = 2;
var FRONT_I = 3;
var BACK_I = 4;
var VER_I = 5;
var MARK_I = 6;

// Comment modes
var DESCRIPTION_MODE = 0;
var REVIEW_MODE = 1;

var DESCRIPTION_START = "%%__%%";
var KEYWORD_SEPERATOR = "__%%%%__";

var currMarker;
var icon;
var shortcuts = new Array();
var waypointMarkers = new Array();
var commentMode = DESCRIPTION_MODE;
var firstLoad = true;
//var colors = new Array("#FFFF00", "#FF0000", "#317602", "#4F0505", "#B63475", "#B63475", "#B63475", "#0000FF");
var colors = new Array("#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00");

var showHints = true;
var wayPointsMenu=new Array();

var muteAvatar = false;
var avatarList = "";

var currentWaypoint = null;
var tooltip = document.createElement("div");

var startHereHidden = true;

function myinit(){
	 if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		//map.addControl(new GMapTypeControl());
	  
		var copyright = new GCopyright(1,new GLatLngBounds(new GLatLng(30.719160227435, -83.815765380859), new GLatLng(50.719160227435, -63.815765380859)), 0, "");
		var copyrightCollection = new GCopyrightCollection('');
		copyrightCollection.addCopyright(copyright);
			
		var tilelayers = [new GTileLayer(copyrightCollection , 9, 11)];
		tilelayers[0].getTileUrl = CustomGetTileUrl;
			
		var custommap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "", {errorMessage:"No chart data available"});
		map.addMapType(custommap);
		map.setMapType(custommap);
	  
	}

	
	initState();
	
	firstPoint = new GLatLng(trailState.route.getTrailPoint(trailState.currentPoint).lat, trailState.route.getTrailPoint(trailState.currentPoint).lng)
    map.setCenter(firstPoint, 10);
	
	createPointer(firstPoint);
	createWaypointsMenu();
	initTrails();
	generalUpdate();
	firstLoad = false;	
	
	GEvent.addListener(map, "zoomend", zoomUpdated);
	// ====== set up marker mouseover tooltip div ======
    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    tooltip.style.visibility="hidden";
    showStartHere();

}

function showStartHere(){
	startHereHidden = false;
	opacity("startherepanel", 0, 100, 1000);
	setTimeout("hideStartHere()", 6000);
}


function hideStartHere(){
	if(!startHereHidden){
		startHereHidden = true;
		opacity("startherepanel", 100, 0, 600);
	}
}

function zoomUpdated(oldLevel, newLevel){
	rebuildMarkers(oldLevel, newLevel);
}

function createWaypointsMenu(){
	var i = 0;
	var j = 0;
	for(j; j < trails.length; j++){
		var waypoints = trails[j].waypoints;		
		for(i = 0; i <waypoints.length; i++){
			if(waypoints[i].main == true){			
				wayPointsMenu.push("<a href=\"javascript:moveToLocation('" + waypoints[i].trail + "'," + waypoints[i].point + "," + 
					waypoints[i].orientation+ ",INCREMENT,STRAIGHT)\">" + waypoints[i].title + "</a>");
			}
		}
	}
}

function initTrails(excludeWaypoints){
	var icon = new GIcon();	
	icon.image = "";
	icon.shadow = "";
	icon.iconSize = new GSize(85, 30);
	icon.shadowSize = new GSize(1, 1);
	icon.iconAnchor = new GPoint(42, 29);
	icon.infoWindowAnchor = new GPoint(5, 1);
	
	var startIcon = new GIcon();	
	startIcon.image = "images/mm_20_green.png";
	startIcon.shadow = "";
	startIcon.iconSize = new GSize(12, 20);
	startIcon.shadowSize = new GSize(11, 15);
	startIcon.iconAnchor = new GPoint(6, 20);
	startIcon.infoWindowAnchor = new GPoint(5, 1);

	var j;
	var i;
	
	
	
	for(j = 0; j < trails.length; j++){
		var trail = trails[j].trail;
		var trailId = trails[j].trailId;
		var points = [];
		var point = null;
		
		var con = trails[j].getConnection(B);
		if(con){
			var t = getRouteObject(con.destTrail);
			var trailPoint = t.trail[t.trail.length-1];
			point = new GLatLng(trailPoint.lat, trailPoint.lng);
			points.push(point);
		}
		
		for(i = 0; i < trail.length; i++){
			point = new GLatLng(trail[i].lat, trail[i].lng)
			//if(trail[i].isShortcut == true){
			//	var shortcut;
			//	if(i == 0){
			//		shortCut = new GMarker(point, startIcon);
			//	}else{
			//		shortCut = new GMarker(point, icon);
			//	}
			//	GEvent.addListener(shortCut, "click", new Function('jumpToLocation(' + i + ', \''+ trailId + '\');'));
			//	shortcuts.push(new Array(trailId, i, shortCut));
			//	//map.addOverlay(shortCut);
			//}
			points.push(point);
		}
		map.addOverlay(new GPolyline(points, colors[j], 5, 0.8));
		
		if(!excludeWaypoints){
			var waypoints = trails[j].waypoints;
			for(i = 0; i < waypoints.length; i++){
				if(waypoints[i].main){
					createWaypointMarker(trails[j], waypoints[i]);		
				}
			}
		}
		
	}
	renderMapShortcuts(shortcuts)
}

function createWaypointMarker(trail, waypoint){
	var icon = new GIcon();	
	icon.image = "";
	icon.shadow = "";
	icon.shadowSize = new GSize(1, 1);
	icon.infoWindowAnchor = new GPoint(5, 1);
	
	var point = null;
	if (!waypoint.enableTourLoc) {
		var trailPoint = trail.getTrailPoint(waypoint.point);
		point = new GLatLng(trailPoint.lat, trailPoint.lng);
	}else{
		point = new GLatLng(waypoint.tourlat, waypoint.tourlng);
	}
	var wayMarker;
	var image = "images/waypoints/" + waypoint.college + "/" + waypoint.trail + "/" + waypoint.icon;
	if(map.getZoom() == 9){
		icon.iconSize = new GSize(8, 9);
		icon.iconAnchor = new GPoint(4, 4);
		icon.image = "images/spotwaypoint.png";
		wayMarker = new GMarker(point, icon);
		wayMarker.overImage = image;
		wayMarker.origImage = icon.image;
		GEvent.addListener(wayMarker, "mouseover", 
				new Function ("updateWaypointMarker(" + (waypointMarkers.length) + ", '" + wayMarker.overImage + "')")); 
		GEvent.addListener(wayMarker, "mouseout", 
		        new Function ("updateWaypointMarker(" + (waypointMarkers.length) + ", '')")); 
	}else{
		icon.iconSize = new GSize(85, 30);
		icon.iconAnchor = new GPoint(42, 29);
		icon.image = image;
		wayMarker = new GMarker(point, icon);
	}	
	GEvent.addListener(wayMarker, "click", new Function("moveToLocation('" + waypoint.trail + "'," + waypoint.point + "," + 
			waypoint.orientation+ ",INCREMENT,STRAIGHT);"));
	waypointMarkers.push(wayMarker);
	map.addOverlay(wayMarker);
}

var mouseOverWaypointMarker;
function updateWaypointMarker(index, url){
	if(url == ""){
		map.removeOverlay(mouseOverWaypointMarker);
	}else{
		var icon = new GIcon();	
		icon.image = url;
		icon.shadow = "";
		icon.shadowSize = new GSize(1, 1);
		icon.infoWindowAnchor = new GPoint(5, 1);
		icon.iconSize = new GSize(85, 30);
		icon.iconAnchor = new GPoint(42, 29);
		mouseOverWaypointMarker = new GMarker(waypointMarkers[index].getLatLng(), icon);
		map.addOverlay(mouseOverWaypointMarker);
	}
	//waypointMarkers[index].setImage(url);
}

function rebuildMarkers(oldLevel, newLevel){
	var i = 0;
	var updateWaypointMarkers = oldLevel == 9 || newLevel == 9
	if(updateWaypointMarkers){
		for(i = 0; i < waypointMarkers.length; i++){
			map.removeOverlay(waypointMarkers[i]);
		}
		waypointMarkers = new Array();
	}
	hoverMarkers = new Array();
	for (j = 0; j < trails.length; j++) {
		var waypoints = trails[j].waypoints;
		for (i = 0; i < waypoints.length; i++) {
			if (waypoints[i].main){
				if(updateWaypointMarkers){
					createWaypointMarker(trails[j], waypoints[i]);
				}
			}
		}
	}
}

function renderMapShortcuts(){
	var newShortcutList = new Array();
	for(i = 0; i < shortcuts.length; i++){
		if(shortcuts[i][1] == 0){
			map.addOverlay(shortcuts[i][2]);
		}else if (mainTrail == shortcuts[i][0]){
			map.addOverlay(shortcuts[i][2]);
		}else{
			newShortcutList.push(shortcuts[i]);
		}
	}
	shortcuts = newShortcutList;
}

function changeResolution(lowRes){
	trailState.lowResolution = lowRes;
	updateVirtualPanel();
}

function switchHints(show, src){
	if(show == false){
		if(confirm("By unchecking the \"Side Hints\" you won't be able to view the left and right hint boxes as you\nmove forward/backward in the trail. Do you want to proceed?") == false){
			src.checked = true;
			return;
		}
	}
	showHints = show;
	updateVirtualPanel();
}
	

function moveForward(trailId, point, orientation, direction, vOrientation){
	move(FORWARD, trailId, point, orientation, direction, vOrientation);
}

function moveBackward(trailId, point, orientation, direction, vOrientation){
	move(BACKWARD, trailId, point, orientation, direction, vOrientation);
}

function jumpToLocation(loc, trailId){
	moveToLocation(trailId, loc, FRONT, trailState.direction, STRAIGHT);
}

function moveToLocation(trailId, point, orientation, direction, vOrientation){
	if(setTrail(trailId, point, orientation, direction) == false){
		trailState.direction = direction;
		trailState.currentPoint = point;
		trailState.orientation = orientation;
		trailState.vOrientation = vOrientation;
	}	
	moveToCurrentPoint();
	generalUpdate();
}

function setTrail(trailId, point, orientation, direction, vOrientation){
	if(trailId != trailState.route.trailId){
		trailState.route = getRouteObject(trailId);
		mainTrail = trailId;
		if(window.changeTrailListener != null){
			changeTrailListener(trailId, point);
		}
		trailState.direction = direction;
		trailState.currentPoint = point;
		trailState.orientation = orientation;
		trailState.vOrientation = STRAIGHT;
		renderMapShortcuts();
		return true;
	}
	return false;
}

function move(action, trailId, point, orientation, direction, vOrientation){
	setCurrentLocation(trailId, point, orientation, direction, vOrientation);
	if(action == BACKWARD && trailState.direction == DECREMENT){
		action = FORWARD;
	}
	else if(action == FORWARD && trailState.direction == DECREMENT){
		action = BACKWARD;
	}
	if(action == FORWARD){
		if(trailState.currentPoint < trailState.route.trail.length - 1){
			trailState.currentPoint += 1;
		}
	}else{
		if(trailState.currentPoint > 0){
			trailState.currentPoint -= 1;
		}
	}
	
	generalUpdate();
}

var topImage = "virtualPhoto";
function updateVirtualPanel(){
	hideStartHere();
	var file = getFileForRoute(trailState.route, trailState.currentPoint, trailState.orientation, trailState.direction, trailState.vOrientation);
	var image = file + "_sm.jpg";
	var lowResImage = file + ".jpg";
	var descriptionFile = file + ".htm";
	
	document.getElementById("picNum").innerHTML = trailState.route.trailId + "-" + (trailState.currentPoint+1);
		
	width = document.getElementById("virtualPhoto").clientWidth;
	//height = Math.ceil((width / 1024) * 768);
	height = vtourPhotoHeight;
	
	var increment = 1;
	if(trailState.direction == DECREMENT){
		increment = -1;
	}
	var preloadedPoint = trailState.route.getTrailPoint(trailState.currentPoint+increment);
	if(preloadedPoint != null){
		createPreloadedImage(trailState.route, trailState.currentPoint+increment, 
			trailState.orientation, trailState.direction, trailState.vOrientation, 0);
	}
		
	trailState.currentImage = lowResImage;
	trailState.currentDescriptionFile = descriptionFile;	
	
	if(trailState.lowResolution){
		image = lowResImage;
	}
	var currentImage = document.getElementById("virtualPhoto_img");
	if(currentImage){
		document.getElementById(topImage).style.zIndex = 0;
		topImage = topImage=="virtualPhoto"?"virtualPhotoTrans":"virtualPhoto";
		document.getElementById(topImage).style.zIndex = 1;
		
		document.getElementById(topImage).innerHTML = "<img id=" + topImage +"_img style=display:none border=\"1\" width=\""+ width +"\" height=\""+height+"\" src=" + image + ">";
		document.getElementById("frontNavBlanket").style.display = "";
		opacity(topImage + "_img", 0, 100, 800);
	}else{
		topImage = "virtualPhoto";
		document.getElementById(topImage).innerHTML = "<img id=\"virtualPhoto_img\" border=\"1\" width=\""+ width +"\" height=\""+height+"\" src=" + image + ">";
		document.getElementById(topImage).style.zIndex = 1;
	}
	
	var timer = new Timer();
	timer.setTimeout("updateDescription", 100, trailState.route, trailState.currentPoint, trailState.orientation, trailState.direction, trailState.vOrientation);
}

function opacityCompleted(){
	document.getElementById("frontNavBlanket").style.display = "none";
}

function updateHints(descriptionObj, route, point, orientation, direction){
	var width = document.getElementById("virtualPhoto").clientWidth;
	var rightHint = document.getElementById("rightHint");
	var leftHint = document.getElementById("leftHint");
	
	leftHint.style.display="none";
	rightHint.style.display="none";
	
	if(orientation == FRONT && showHints){
		
		if(descriptionObj.leftHint != ""){
			leftHint.style.display="block";
			correctPNG("leftHintPanel", true);
			if(descriptionObj.leftHint.length > 25){
				descriptionObj.leftHint = descriptionObj.leftHint.substring(0, 26) + "...";
			}
			document.getElementById("leftHintText").innerHTML = "&lt;&lt;&nbsp;" + descriptionObj.leftHint;
			document.getElementById("leftHintText").href = createHrefForCurrentLocation("turnLeft");
		}
		if(descriptionObj.rightHint != ""){
			rightHint.style.display="block";
			correctPNG("rightHintPanel", true);
			if(descriptionObj.rightHint.length > 25){
				descriptionObj.rightHint = descriptionObj.rightHint.substring(0, 26) + "...";
			}
			document.getElementById("rightHintText").innerHTML = descriptionObj.rightHint + "&nbsp;&gt;&gt;";
			document.getElementById("rightHintText").href = createHrefForCurrentLocation("turnRight");
		}
	}
}

function updateLanguage(dropdown){
	language = dropdown.value;
	avatarList = "";
	stopSpeech();
	updateDescription(trailState.route, trailState.currentPoint, trailState.orientation, trailState.direction, trailState.vOrientation);
}

function getFile(trailId, point, orientation, direction, vOrientation){
	var route = getRouteObject(trailId);
	return getFileForRoute(route, point, orientation, direction, vOrientation);
}

function getFileForRoute(route, point, orientation, direction, vOrientation){
	var tPoint = route.getTrailPoint(point);
	var dir = tPoint.dir;
	var file = getOrientationText(orientation, direction).toLowerCase();
	if(vOrientation == UP){
		file = file + "_up";
	}
	return "photos/" + dir + "/" + file;
}

//function updateDescription(descFile){
//	var html = loadHtmlDoc(descFile);
//	
//	if(html.substring(0, DESCRIPTION_START.length) == DESCRIPTION_START){
//		html = html.substring(DESCRIPTION_START.length + 1);
//	}else{
//		html = "";
//	}
//	document.getElementById("description").innerHTML = html;
//}

function updateDescription(route, point, orientation, direction, vOrientation){
	var tPoint = route.getTrailPoint(point);
	var url = "";
	var hints = "";
	if(commentMode == DESCRIPTION_MODE){
		url = "description.php?point="+(point+1)+"&orientation="+orientation+"&direction="+direction+
			"&vOrientation="+vOrientation+"&trailId="+route.trailId+"&collegeId="+route.collegeId + "&language=" + language;
	}
	
	var keywords = "";
	var html = loadHtmlDoc(url);
	html = trim(html);
	
	var descriptionObj = eval(html);
	
	// We have disabled the title for the descrption for now
	//document.getElementById("descriptionText").innerHTML = "<div class=panel_h1>" +descriptionObj.title + "</div>"  + descriptionObj.description;

	document.getElementById("descriptionText").innerHTML = "<div class=panel_h1></div>"  + descriptionObj.description;
	document.getElementById("keywordsText").innerHTML = descriptionObj.title;

	updateAvatar(descriptionObj);
	updateHints(descriptionObj, route, point, orientation, direction);
}

var waitingAvatarAudio = "";
function updateAvatar(descriptionObj){
	if(descriptionObj.avatar != "" && !muteAvatar && avatarList.indexOf(descriptionObj.avatar + ";") < 0){
		stopSpeech();
		if(descriptionObj.avatarScene != currentAvatarScene){
			//preloadScene(descriptionObj.avatarScene);
			setTimeout("loadNewScene()", 200);
			currentAvatarScene = descriptionObj.avatarScene;
			waitingAvatarAudio = descriptionObj.avatar;
		}else{
			sayAudio(descriptionObj.avatar);
			avatarList = avatarList + descriptionObj.avatar + ";";
		}
	}else{
		//stopSpeech();
	}
}

function loadNewScene(){
	loadScene(currentAvatarScene);
}

function vh_sceneLoaded (sceneIndex){
	if(waitingAvatarAudio != ""){
	//loadScene(currentAvatarScene);
		sayAudio(waitingAvatarAudio);
		avatarList = avatarList + waitingAvatarAudio + ";";
		waitingAvatarAudio = "";
	}
}

function createMediaInfoObject(type){
	return "new MediaInfo(" + type + ",'" + trailState.route.collegeId + "'," + currentWaypoint.id + "," + currentWaypoint.hasVideo + "," + currentWaypoint.hasPanorama + "," + currentWaypoint.hasPicture + ",'" + currentWaypoint.title.replace("'", "\\'") + "')";
}
	

function switchCommentMode(newMode){
	if(newMode == commentMode)return;
	
	if(newMode == DESCRIPTION_MODE){
		document.getElementById("descriptionLink").className = "selectedComment";
		document.getElementById("reviewLink").className = "unselectedComment";
		document.getElementById("commentUpdateLink").href = "javascript:editDescription();";
		document.getElementById("commentUpdateLink").innerHTML = "Edit";
		document.getElementById("commentEnlarge").style.display="block";
		commentMode = DESCRIPTION_MODE;
	}else{
		document.getElementById("descriptionLink").className = "unselectedComment";
		document.getElementById("reviewLink").className = "selectedComment";
		document.getElementById("commentUpdateLink").href = "javascript:addReview();";
		document.getElementById("commentUpdateLink").innerHTML = "Add Review";
		document.getElementById("commentEnlarge").style.display="none";
		commentMode = REVIEW_MODE;
	}
	updateDescription(trailState.route, trailState.currentPoint, trailState.orientation, trailState.direction, trailState.vOrientation);
}

function enlarge(includeImage){
	if(trailState.currentImage != ""){
		var tPoint = trailState.route.getTrailPoint(trailState.currentPoint);
		var url = "enlargeImage.php?";
		if(includeImage){
			url = url + "file=" + escape(trailState.currentImage) + "&";
		}
		url = url + "sequence="+tPoint.sequence+"&orientation="+trailState.orientation+ 
					"&direction="+trailState.direction+"&vOrientation="+trailState.vOrientation+"&trailId="+trailState.route.trailId;
		window.open(url, "_blank", "width=930,resizable=yes,scrollbars=yes");
	}
}

function setCurrentLocation(trailId, point, orientation, direction, vOrientation){
	if(setTrail(trailId, point, orientation, direction, vOrientation) == false){
		trailState.direction = direction;
		trailState.currentPoint = point;
		trailState.orientation = orientation;
		trailState.vOrientation = vOrientation;
	}
}
	

function resetToFront(trailId, point, orientation, direction, vOrientation){
	setCurrentLocation(trailId, point, FRONT, direction, vOrientation);
	generalUpdate();
}

function turnLeft(trailId, point, orientation, direction, vOrientation){
	if(trailState.orientation == FRONT){
		setCurrentLocation(trailId, point, LEFT, direction, vOrientation);
	}else if(trailState.orientation == LEFT){
		setCurrentLocation(trailId, point, FRONT, (trailState.direction == INCREMENT?DECREMENT:INCREMENT), vOrientation);
	}else if(trailState.orientation == RIGHT){
		setCurrentLocation(trailId, point, FRONT, direction, vOrientation);
	}
	
	generalUpdate();
}

function turnRight(trailId, point, orientation, direction, vOrientation){
	if(trailState.orientation == FRONT){
		setCurrentLocation(trailId, point, RIGHT, direction, vOrientation);
	}else if(trailState.orientation == RIGHT){
		setCurrentLocation(trailId, point, FRONT, (trailState.direction == INCREMENT?DECREMENT:INCREMENT), vOrientation);
	}else if(trailState.orientation == LEFT){
		setCurrentLocation(trailId, point, FRONT, direction, vOrientation);
	}
	generalUpdate();
}	

function lookUp(trailId, point, orientation, direction, vOrientation){
	setCurrentLocation(trailId, point, orientation, direction, UP);
	generalUpdate();
}

function lookStraight(trailId, point, orientation, direction, vOrientation){
	setCurrentLocation(trailId, point, orientation, direction, STRAIGHT);
	generalUpdate();
}

function turnAround(trailId, point, orientation, direction, vOrientation){
	
	if(trailState.direction == INCREMENT){
		setCurrentLocation(trailId, point, orientation, DECREMENT, vOrientation);
	}else{
		setCurrentLocation(trailId, point, orientation, INCREMENT, vOrientation);
	}
	generalUpdate();
}

function generalUpdate(){
	moveToCurrentPoint();
	updateVirtualPanel();
	setTimeout("updateNavPanel()", 400);
	updateWaypointsPanel();
	updateMediaPanel();
	//if(window.generalUpdateListener){	
	//	generalUpdateListener();
	//}
}

function updateWaypointsPanel(){
	var i = 0;
	var prevMain = -1;
	var nextMain = -1;
	var title = "";
	currentWaypoint = null;
	
	var waypoints = trailState.route.waypoints;
	
	for(i = 0; i < waypoints.length; i++){
		if(waypoints[i].point == trailState.currentPoint && waypoints[i].orientation == trailState.orientation){
			title = waypoints[i].title;
			currentWaypoint = waypoints[i];
			break;
		}else if (waypoints[i].point > trailState.currentPoint && waypoints[i].heading){
			title = "Walking to " + waypoints[i].title;
			break;
		}else if(waypoints[i].point <= trailState.currentPoint && waypoints[i].main == true){
			prevMain = i;
		}
		
	}
	for(i=prevMain+1; i < waypoints.length; i++){
		if(waypoints[i].point >= trailState.currentPoint && waypoints[i].main && title != waypoints[i].title){
			nextMain = i;
			break;
		}
	}
	
	
	if(nextMain != -1){
		document.getElementById("nextWayPoint").style.display="";
		document.getElementById("nextWayPoint").href = "javascript:moveToLocation('" + waypoints[nextMain].trail + "'," + waypoints[nextMain].point + "," + waypoints[nextMain].orientation+ ",INCREMENT,STRAIGHT)";
	}else {
		var nextTrail = getNextRouteWithWaypoint(true);
		if(nextTrail != null){
			var w = nextTrail.waypoints;
			for(i = 0; i < w.length; i++){
				if(w[i].main){
					document.getElementById("nextWayPoint").style.display="";
					document.getElementById("nextWayPoint").href = "javascript:moveToLocation('" + nextTrail.trailId + "'," + w[i].point + "," + w[i].orientation+ ",INCREMENT,STRAIGHT)";
					if(title == ""){
						title = "Walking to " + w[i].title;
					}
					break;
				}
			}
		}else{
			document.getElementById("nextWayPoint").style.display="none";
		}
	}
	
	if(title.length > 31){
		title = title.substring(0, 31) + "...";
	}
	document.getElementById("currentWayPoint").innerHTML = title;
	
	if(prevMain != -1){
		document.getElementById("prevWayPoint").style.display="";
		document.getElementById("prevWayPoint").href = "javascript:moveToLocation('" + waypoints[prevMain].trail + "'," + waypoints[prevMain].point + "," + waypoints[prevMain].orientation + ",INCREMENT,STRAIGHT)";
	}else{
		var prevTrail = getPreviousRouteWithWaypoint(true);
		if(prevTrail != null){
			var w = prevTrail.waypoints;
			for(i = w.length-1; i >= 0; i--){
				if(w[i].main){
					document.getElementById("prevWayPoint").style.display="";
					document.getElementById("prevWayPoint").href = "javascript:moveToLocation('" + prevTrail.trailId + "'," + w[i].point + "," + w[i].orientation + ",INCREMENT,STRAIGHT)";
					break;
				}
			}
		}else{
			document.getElementById("prevWayPoint").style.display="none";
		}
	}
}

function enableSubPanel(panel1, panel2){
	document.getElementById("connectionsNavPanel").style.display = "none";
	document.getElementById("lastPointNavPanel").style.display = "none";
	document.getElementById("frontNavPanel").style.display = "none";
	document.getElementById("sideNavPanel").style.display = "none";
	document.getElementById(panel1).style.display = "";
	if(panel2){
		document.getElementById(panel2).style.display = "";
	}
}

function buildEndOfTrailPanel(){
	var nextRoutes = new Array();
	
	if (trailState.route.connections.length > 0) {
		if (document.getElementById("connectionsNavPanel").style.display == "none") {
			enableSubPanel("connectionsNavPanel", "frontNavPanel");
			hideConnection("connectionFront");
			hideConnection("connectionBearLeft");
			hideConnection("connectionBearRight");
			hideConnection("connectionLeft");
			hideConnection("connectionRight");
			resetCorner(document.getElementById("frontNavTop"));
		}
		var i = 0;
		for (i; i < trailState.route.connections.length; i++) {
			con = trailState.route.connections[i];
			destTrail = getRouteObject(con.destTrail);
			if (con.connection == F) {
				createConnection("connectionFront", destTrail);
			}
			if (con.connection == F_BL) {
				createConnection("connectionBearLeft", destTrail);
			}
			if (con.connection == F_BR) {
				createConnection("connectionBearRight", destTrail);
			}
			if (con.connection == L) {
				createConnection("connectionLeft", destTrail);
			}
			if (con.connection == R) {
				createConnection("connectionRight", destTrail);
			}
			if (con.connection != B && con.connection != END) {
				nextRoutes[nextRoutes.length] = destTrail;
			}
		}
	}
	if (nextRoutes.length == 0) {
		if (document.getElementById("lastPointNavPanel").style.display == "none") {
			enableSubPanel("lastPointNavPanel");
			correctPNG("replayBtnImgId", true);
			correctPNG("skipBtnImgId", true);
			correctPNG("stepBackBtnImgId", true);
		}
		
		var nextRoute = null;
		if (trailState.route.connections.length > 0) {
			var i = 0;
			for (i; i < trailState.route.connections.length; i++) {
				con = trailState.route.connections[i];
				destTrail = getRouteObject(con.destTrail);
				if (con.connection == END) {
					nextRoute = destTrail;
					break;
				}
			}
		}
		if (nextRoute == null) {
			nextRoute = getNextRoute(true);
		}
		if (nextRoute == null) {
			document.getElementById("skipToNextRoute").style.display = "none";
		}
		else {
			nextRoutes[nextRoutes.length] = nextRoute;
			document.getElementById("skipToNextRoute").style.display = "";
			document.getElementById("lastPointNavSkip_href").href = "javascript:jumpToLocation(0, '" + nextRoute.trailId + "');";
			document.getElementById("lastPointNavSkip_href").innerHTML = "To " + nextRoute.name;
		}
		if(trailState.route.trail.length > 1){
			document.getElementById("lastPointNavReplay_href").style.display="";
			document.getElementById("lastPointNavStepBack_href").style.display="";
			document.getElementById("lastPointNavReplay_href").href = "javascript:jumpToLocation(0, '" + trailState.route.trailId + "');";
			document.getElementById("lastPointNavStepBack_href").href = createHrefForCurrentLocation("moveBackward");
		}else{
			document.getElementById("lastPointNavReplay_href").style.display="none";
			document.getElementById("lastPointNavStepBack_href").style.display="none";
		}
	}
	var i;
	for (i = 0; i < nextRoutes.length; i++) {
		createPreloadedImage(nextRoutes[i], 0, FRONT, INCREMENT, STRAIGHT, i);
	}
}

function createPreloadedImage(trail, point, orientation, direction, vOrientation, index){
	var preLoadedImage = getFileForRoute(trail, point, orientation, direction, vOrientation);
	if (trailState.lowResolution) {
		document.getElementById("preloadedimage" + index).src = preLoadedImage + ".jpg";
	}
	else {
		document.getElementById("preloadedimage" + index).src = preLoadedImage + "_sm.jpg";
	}
}

function hideConnection(panelId){
	document.getElementById(panelId + "_img").style.display = "none";
	document.getElementById(panelId + "_panel").style.display = "none";
}

function createConnection(panelId, trailId){
	document.getElementById(panelId + "_img").style.display = "";
	document.getElementById(panelId + "_panel").style.display = "";
	document.getElementById(panelId + "_img").style.cursor = "pointer";
	document.getElementById(panelId + "_img").onclick = function() {jumpToLocation(0, trailId.trailId);};
	document.getElementById(panelId + "_txt").innerHTML = "To " + trailId.name;
}

function buildFrontNavPanel(enableFrontArrow)
{
	var tPoint = trailState.route.getTrailPoint(trailState.currentPoint);
	if (enableFrontArrow) {
		setCorner(document.getElementById("frontNavTop"), getDirectionImage(tPoint.frontDir, tPoint.backDir, trailState.direction));
		document.getElementById("frontNavTop_href").href = createHrefForCurrentLocation("moveForward");
	}
	
	if(tPoint.hasLeft(trailState.direction)){
		setCorner(document.getElementById("frontNavLeft"),createNavigationArrow(createPngImage("images/turn_left_front_arrow"), "Look Left"));
		document.getElementById("frontNavLeft_href").href = createHrefForCurrentLocation("turnLeft");
	}else{
		resetCorner(document.getElementById("frontNavLeft"));
	}
	
	if(tPoint.hasRight(trailState.direction)){
		setCorner(document.getElementById("frontNavRight"),createNavigationArrow(createPngImage("images/turn_right_front_arrow"), "Look Right"));
		document.getElementById("frontNavRight_href").href = createHrefForCurrentLocation("turnRight");
	}else{
		resetCorner(document.getElementById("frontNavRight"));
	}
	
	setCorner(document.getElementById("frontNavBottom"), getDirectionImage(tPoint.backDir, tPoint.frontDir, trailState.direction));
	document.getElementById("frontNavBottom_href").href = createHrefForBackArrow();
}

function updateNavPanel(){
	
	
	if(trailState.orientation == FRONT && trailState.route.isLastPoint(trailState.currentPoint)){
		buildEndOfTrailPanel();
		buildFrontNavPanel(false);
	}
	else if(trailState.orientation == FRONT){
		if(document.getElementById("frontNavPanel").style.display=="none" || 
		   document.getElementById("connectionsNavPanel").style.display == ""){
			enableSubPanel("frontNavPanel");
			correctPNG("perspectiveImgId", true);
		}
		buildFrontNavPanel(true);
	}
	if(trailState.orientation == LEFT){
		if(document.getElementById("sideNavPanel").style.display=="none"){
			enableSubPanel("sideNavPanel");
			correctPNG("backBtnImgId", true);
		}
		
		document.getElementById("sideNavBack_href").href = createHrefForCurrentLocation("resetToFront");
	}
	if(trailState.orientation == RIGHT){
		if(document.getElementById("sideNavPanel").style.display=="none"){
			enableSubPanel("sideNavPanel");
			correctPNG("backBtnImgId", true);
		}
		
		document.getElementById("sideNavBack_href").href = createHrefForCurrentLocation("resetToFront");
	}
}

function createHrefForBackArrow(){
	if (!trailState.route.isFirstPoint(trailState.currentPoint)) {
		return createHrefForCurrentLocation("moveBackward");
	}
	if (trailState.route.connections.length > 0) {
		var i = 0;
		for (i; i < trailState.route.connections.length; i++) {
			con = trailState.route.connections[i];
			destTrail = getRouteObject(con.destTrail);
			if (con.connection == B) {
				return "javascript:jumpToLocation(" + (destTrail.trail.length - 1) + ", '" + destTrail.trailId + "')";
			}
		}
		var route = getPreviousRoute(true);
		if(route != null){
			return "javascript:jumpToLocation(" + (route.trail.length - 1) + ", '" + route.trailId + "')";
		}
	}
	return "#";
}

function createHrefForCurrentLocation(functionName){
	return "javascript:"+functionName + "('" + trailState.route.trailId + "'," +  trailState.currentPoint + "," + trailState.orientation + ","  +
							trailState.direction + "," + trailState.vOrientation + ");";
}

function activateArrow(image){
	var url = image.src;
	var pos = url.lastIndexOf('.');
	image.src = url.substring(0, pos) + "_a" + url.substring(pos);
}		

function deactivateArrow(image){
	var url = image.src;
	var pos = url.lastIndexOf('_a.');
	image.src = url.substring(0, pos) + url.substring(pos + 2);
}

function createNavigationArrow(src, alt){
	var txt = "";
	if(alt){
		txt = alt;
	}
	return "<img src=" + src + " onMouseOut='deactivateArrow(this);' onMouseOver='activateArrow(this);' title='" + txt + "'>";
}

function getDirectionImage(current, inverse, direction){
	if(direction == DECREMENT){
		current = 9 - inverse;
	}
	if(current == F_L){
		return createNavigationArrow(createPngImage("images/front_left_arrow"));
	}
	if(current == F){
		return createNavigationArrow(createPngImage("images/front_arrow1"));
	}
	if(current == F_R){
		return createNavigationArrow(createPngImage("images/front_right_arrow"));
	}
	if(current == B_L){
		return createNavigationArrow(createPngImage("images/back_left_arrow"));
	}
	if(current == B){
		return createNavigationArrow(createPngImage("images/back_arrow"));
	}
	if(current == B_R){
		return createNavigationArrow(createPngImage("images/back_right_arrow"));
	}
	if(current == B_BR){
		return createNavigationArrow(createPngImage("images/back_bear_right"));
	}
	if(current == B_BL){
		return createNavigationArrow(createPngImage("images/back_bear_left"));
	}
	if(current == F_BR){
		return createNavigationArrow(createPngImage("images/front_bear_right"));
	}
	if(current == F_BL){
		return createNavigationArrow(createPngImage("images/front_bear_left"));
	}
	if(current == F_B){
		return createNavigationArrow(createPngImage("images/front_turnaround_arrow"));
	}
	if(current == B_F){
		return createNavigationArrow(createPngImage("images/back_arrow"));
	}
}

function setCorner(corner, html){
	if(corner.htmlTempValue == null || corner.htmlTempValue.toLowerCase() != html.toLowerCase()){
		var hrefhtml = "<a class=\"navArrow\" id=\""+corner.id + "_href\" href=\"void(0);\" >" + html + "</a>";
		corner.innerHTML = hrefhtml;
		corner.htmlTempValue = html;
		corner.style.cursor = "Hand";
	}
}
	
function resetCorner(corner){
	corner.innerHTML = "&nbsp;";
	corner.onclick = "";
	corner.htmlTempValue = "";
	corner.style.cursor="default";
}

function resetNavigationPanel(){
	var i;
	for(i = 1; i < 10; i++){
		resetCorner(document.getElementById("cell" + i));
	}
}

function getOrientationText(orientation, direction){
	if(orientation == FRONT && direction == INCREMENT){
		return "FRONT";
	}else if(orientation == FRONT && direction == DECREMENT){
		return "BACK";
	}else if(orientation == LEFT && direction == INCREMENT){
		return "LEFT";
	}else if(orientation == RIGHT && direction == INCREMENT){
		return "RIGHT";
	}else if(orientation == LEFT && direction == DECREMENT){
		return "RIGHT";
	}else if(orientation == RIGHT && direction == DECREMENT){
		return "LEFT";
	}
}

function trim(str){
   return str.replace(/^\s*|\s*$/g,"");
}

	

function initState(){
	trailState = new Object();
	trailState.route = getRouteObject(mainTrail);
	if(startOrientation != -1){
		trailState.orientation = startOrientation;
	}else{
		trailState.orientation = trailState.route.startOrientation;
	}
	if(startPoint != -1){
		trailState.currentPoint = startPoint;
	}else{
		trailState.currentPoint = trailState.route.startPoint;
	}
	if(startDirection != -1){
		trailState.direction = startDirection;
	}else{
		trailState.direction = trailState.route.startDirection;
	}
	trailState.vOrientation = STRAIGHT;
	trailState.currentImage = "";
	trailState.currentDescriptionFile = "";
	trailState.lowResolution = true;
}

function getRouteObject(trailId){
	var i;
	for(i = 0; i < trails.length; i++){
		if(trails[i].trailId == trailId){
			return trails[i];
		}
	}
}

function getNextRouteWithWaypoint(loop){
	var currentTrail = getNextRouteAfter(trailState.route.trailId, loop);
	if(currentTrail == null){
		return null;
	}
	while(currentTrail.trailId != trailState.route.trailId){
		if(currentTrail.waypoints.length > 0){
			return currentTrail;
		}
		currentTrail = getNextRouteAfter(currentTrail.trailId, loop);
		if(currentTrail == null){
			return null;
		}
	}
	if(loop){
		return currentTrail;
	}else{
		return null;
	}
}

function getNextRoute(loop){
	return getNextRouteAfter(trailState.route.trailId, loop);
}

function getNextRouteAfter(currentTrailId, loop){
	if(trails.length == 1){
		return null;
	}
	var i = 0;
	for(i = 0; i < trails.length; i++){
		if(trails[i].trailId == currentTrailId){
			if(i == trails.length-1 && loop){
				return trails[0];
			}
			return trails[i+1];
		}
	}
	return null;
}

function getPreviousRoute(loop){
	return getPreviousRouteBefore(trailState.route.trailId, loop);
}

function getPreviousRouteBefore(currentTrailId, loop){
	if(trails.length == 1){
		return null;
	}
	var i = 0;
	for(i = 0; i < trails.length; i++){
		if(trails[i].trailId == currentTrailId){
			if(i == 0 && loop){
				return trails[trails.length-1];
			}
			return trails[i-1];
		}
	}
	return null;
}

function getPreviousRouteWithWaypoint(loop){
	var currentTrail = getPreviousRouteBefore(trailState.route.trailId, loop);
	if(currentTrail == null){
		return null;
	}
	while(currentTrail.trailId != trailState.route.trailId){
		if(currentTrail.waypoints.length > 0){
			return currentTrail;
		}
		currentTrail = getPreviousRouteBefore(currentTrail.trailId, loop);
		if(currentTrail == null){
			return null;
		}
	}
	if(loop){
		return currentTrail;
	}else{
		return null;
	}
}
	

function createPointer(location){
	if(!icon){
	  icon = new GIcon();
	  icon.image = "images/man.png";
	  icon.shadow = "";
	  icon.iconSize = new GSize(24, 38);
	  icon.shadowSize = new GSize(24, 38);
	  icon.iconAnchor = new GPoint(12, 38);
	  icon.infoWindowAnchor = new GPoint(5, 1);
	  currMarker = new GMarker(location, icon);
	  map.addOverlay(currMarker);
	  moveToCurrentPoint();
	}
}

function moveToCurrentPoint(){
	var trailPoint = trailState.route.getTrailPoint(trailState.currentPoint);
	var p = new GLatLng(trailPoint.lat, trailPoint.lng);
	map.removeOverlay(currMarker);
	currMarker = new GMarker(p, icon);
	//currMarker.redraw(true);
	map.addOverlay(currMarker);
	map.panTo(p);
}


function Route(name, trailId, collegeId, trail, waypoints, 
			description, startPoint, startOrientation, startDirection, connections){
	this.name = name;
	this.trailId = trailId;
	this.trail = trail;
	this.collegeId = collegeId;
	this.description = description;
	this.startPoint = startPoint;
	this.startOrientation = startOrientation;
	this.startDirection = startDirection;
	this.waypoints = waypoints;
	this.connections = connections;
}
Route.prototype.getTrailPoint = function(index){
	if(index >= this.trail.length || index < 0){
		return null;
	}
	return this.trail[index];
}
Route.prototype.isFirstPoint = function(index){
	return index == 0;
}
Route.prototype.isLastPoint = function(index){
	return index == this.trail.length-1;
}
Route.prototype.getConnection = function(type){
	var i = 0;
	for (i; i < this.connections.length; i++) {
		if (this.connections[i].connection == type) {
			return this.connections[i];
		}
	}
}

function TrailPoint(lat, lng, trailId, collegeId, sequence, frontDirection, backDirection, vOrientation, shortCut, availableSides){
	this.lng = lng;
	this.lat = lat;
	this.dir = collegeId +'/trails/' + trailId + '/' +sequence;
	this.sequence = sequence;
	this.frontDir = frontDirection;
	this.backDir= backDirection;
	this.vOrientation = vOrientation;
	this.isShortcut = shortCut;
	this.availableSides = availableSides
	
	TrailPoint.prototype.hasLeft = function(direction){
		if(direction==DECREMENT) return this.hasRight(INCREMENT);
		return this.availableSides.indexOf("L")>-1;
	}
	TrailPoint.prototype.hasRight = function(direction){
		if(direction==DECREMENT) return this.hasLeft(INCREMENT);
		return this.availableSides.indexOf("R")>-1;
	}
	TrailPoint.prototype.hasBack = function(direction){
		if(direction==DECREMENT) return true;
		return this.availableSides.indexOf("B")>-1;
	}
	TrailPoint.prototype.hasFront = function(direction){
		if(direction==INCREMENT) return true;
		return this.hasBack(INCREMENT);
	}
}

function Description(title, description, leftHint, rightHint, avatar, avatarScene){
	this.title = title;
	this.description = description;
	this.leftHint = leftHint; 
	this.rightHint = rightHint;
	this.avatar = avatar;
	this.avatarScene = avatarScene;
}

function Waypoint(id, title, college, trail, point, orientation, main, heading, 
        icon, hasVideo, hasPanorama, hasPicture, enableHover, shape, tourlat, tourlng, enableTourLoc, fullMapDescription){
	this.title = title;
	this.trail = trail;
	this.college = college;
	this.point = point-1;
	this.main = main;
	this.id = id;
	this.hasPanorama = hasPanorama;
	this.hasPicture = hasPicture;
	this.hasVideo = hasVideo;
	this.heading = heading;
	this.icon = icon;
	this.shape = shape;
	this.enableHover = enableHover;
	this.tourlat = tourlat;
	this.tourlng = tourlng;
	this.enableTourLoc = enableTourLoc;
	this.fullMapDescription = fullMapDescription;
	if(orientation == "FRONT"){
		this.orientation = FRONT;
	}else if(orientation == "LEFT"){
		this.orientation = LEFT;
	}else if(orientation == "RIGHT"){
		this.orientation = RIGHT;
	}
}

function Connection(srcTrail, destTrail, connection){
	this.srcTrail = srcTrail;
	this.destTrail = destTrail;
	this.connection = connection;
}

