var trailState,
    // Direction variables
    INCREMENT = 1,
    DECREMENT = 2,

    // Orientation variables
    FRONT = 1,
    LEFT = 2,
    RIGHT = 3,

    // Vertical Orientation variables
    STRAIGHT = 4,
    UP = 5,

    FORWARD = 0,
    BACKWARD = 1,

    // Trail indices
    LNG_I = 0,
    LAT_I = 1,
    DIR_I = 2,
    FRONT_I = 3,
    BACK_I = 4,
    VER_I = 5,
    MARK_I = 6,

    // Comment modes
    DESCRIPTION_MODE = 0,
    REVIEW_MODE = 1,

    DESCRIPTION_START = "%%__%%",
    KEYWORD_SEPERATOR = "__%%%%__",
    FULL_PANEL,
    currMarker,
    icon,
    shortcuts = [],
    waypointMarkers = [],
    commentMode = DESCRIPTION_MODE,
    firstLoad = true,
    // colors = new Array("#FFFF00", "#FF0000", "#317602", "#4F0505", "#B63475", "#B63475", "#B63475", "#0000FF"),
    colors = ["#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00", "#FFFF00"],

    showHints = true,
    wayPointsMenu = [],

    avatarTalking = false,
    avatarPaused = false,
    muteAvatar = false,
    avatarList = "",

    currentWaypoint = null,
    tooltip = document.createElement("div"),

    startHereHidden = true,
    videoGuideEnabled = false,
    videoGuidePlaying = false,
    videoGuideAvailable = false,
    currentDescriptionObj = null,
    pendingPlayers = new PendingPlayers(),
    debug = false,
    walkingTourContainerInitialized = false;
    arrowSize = "0",
    mediaHelpDisabled = Cookie.get("mediahelpdisabled")=="1",
    virtualTourImagePrefix = "m_";
    
    

function myinit() {

	var mapOptions = {
    	zoom: 10,
    	navigationControl:true,
    	mapTypeControl:false,
    	streetViewControl:false,
    	rotateControl:false,
    	mapTypeControlOptions: {
    		mapTypeIds: ['coordinate', google.maps.MapTypeId.ROADMAP],
    		style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
		},
		zoomControl:true,
		zoomControlOptions: {
			style:google.maps.ZoomControlStyle.SMALL
		}
	};
	map = new google.maps.Map(document.getElementById("map"), mapOptions);
	
	var coordinateMapType = new CoordMapType();
	map.mapTypes.set('coordinate',coordinateMapType);
    map.setMapTypeId('coordinate');

    initState();
    
    firstPoint = new google.maps.LatLng(trailState.route.getTrailPoint(trailState.currentPoint).lat, trailState.route.getTrailPoint(trailState.currentPoint).lng)
    map.setCenter(firstPoint);

    createPointer(firstPoint);
    createWaypointsMenu();
    initTrails();
    generalUpdate();
    firstLoad = false;

    google.maps.event.addListener(map, "zoom_changed", zoomUpdated);
    
    // ====== set up marker mouseover tooltip div ======
    //map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    //tooltip.style.visibility="hidden";
    if (!videoGuideEnabled || FULL_PANEL) {
        showStartHere();
    }
    if (debug) {
        var debugWindow = document.getElementById("devwin");
        debugWindow.className = "debugWindow";
        debugWindow.style.display = "";
    }
    
    // Remove the "Loading..." h4
    var vPhoto = document.getElementById('virtualPhoto');
    vPhoto.removeChild(vPhoto.children[0]);

    if(FULL_PANEL){
	    $("#tourSelectionNavPanel").click(function(e) {
	        $("#tourSelectionNavPanel").hide();
	    });
    }
}

// Classic Tour Only
function switchTour(url){
	var selectedTour = document.getElementById("tour_selection").value;
	window.location = appendTourParams(url+"&tourid="+selectedTour);
}

function log(text) {
    if (debug) {
        var debugWindow = document.getElementById("devwin");
        debugWindow.innerHTML = debugWindow.innerHTML + "<br>" + text;
    }
}

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() {
    rebuildMarkers();
}

function createWaypointsMenu() {
    var i = 0;
    var j = 0;
    var list = new Array();
    for (j; j < trails.length; j++) {
        var waypoints = trails[j].waypoints;
        for (i = 0; i <waypoints.length; i++) {
            if (waypoints[i].main == true) {
                list.push(waypoints[i]);
            }
        }
    }
    list.sort(waypointCompare);
   	for (i=0;i<list.length;i++) {
   		wayPointsMenu.push("<a href='javascript:void(0);' onclick=\"javascript:moveToLocation('" + list[i].trail + "'," + list[i].point + "," +
   			list[i].orientation+ ",INCREMENT,STRAIGHT)\">" + list[i].title + "</a>");
    }
}

function waypointCompare(a, b) {
    if (a.title<b.title)return -1;
    if (a.title==b.title)return 0;
    return 1;
}

function initTrails(excludeWaypoints) {
    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 google.maps.LatLng(trailPoint.lat, trailPoint.lng);
            points.push(point);
        }

        for (i = 0; i < trail.length; i++) {
            point = new google.maps.LatLng(trail[i].lat, trail[i].lng)
            points.push(point);
        }
        var polyline = new google.maps.Polyline({
        	path:points,
        	strokeColor:"#ffff00",
        	strokeOpacity:0.8,
        	strokeWeight: 5
        });
        polyline.setMap(map);

        if (!excludeWaypoints) {
            var waypoints = trails[j].waypoints;
            for (i = 0; i < waypoints.length; i++) {
                if (waypoints[i].main) {
                    createWaypointMarker(trails[j], waypoints[i]);
                }
            }
        }

    }
}



function createWaypointMarker(trail, waypoint) {
    var point = null;
    if (!waypoint.enableTourLoc) {
        var trailPoint = trail.getTrailPoint(waypoint.point);
        point = new google.maps.LatLng(trailPoint.lat, trailPoint.lng);
    } else {
        point = new google.maps.LatLng(waypoint.tourlat, waypoint.tourlng);
    }
    var wayMarker;
    var image = "/images/waypoints/" + waypoint.college + "/" + waypoint.icon;
    if (map.getZoom() == 9) {
    	var icon = new google.maps.MarkerImage("/images/spotwaypoint.png", 
    			new google.maps.Size(8, 9),
    			new google.maps.Point(0, 0),
    			new google.maps.Point(4, 4));
        wayMarker = new google.maps.Marker({position:point, icon:icon});
        wayMarker.overImage = image;
        wayMarker.origImage = "/images/spotwaypoint.png";
        google.maps.event.addListener(wayMarker, "mouseover",
            new Function ("updateWaypointMarker(" + (waypointMarkers.length) + ", '" + wayMarker.overImage + "')"));
        google.maps.event.addListener(wayMarker, "mouseout",
            new Function ("updateWaypointMarker(" + (waypointMarkers.length) + ", '')"));
    } else {
    	var icon = new google.maps.MarkerImage(image, 
    			new google.maps.Size(85, 30),
    			new google.maps.Point(0, 0),
    			new google.maps.Point(42, 29));
        wayMarker = new google.maps.Marker({position:point, icon:icon});
    }
    google.maps.event.addListener(wayMarker, "click", new Function("moveToLocation('" + waypoint.trail + "'," + waypoint.point + "," +
        waypoint.orientation+ ",INCREMENT,STRAIGHT);"));
    waypointMarkers.push(wayMarker);
    wayMarker.setMap(map);
}

var mouseOverWaypointMarker;
function updateWaypointMarker(index, url) {
    if (url == "") {
        mouseOverWaypointMarker.setMap(null);
    } else {
    	var icon = new google.maps.MarkerImage(url, 
    			new google.maps.Size(85, 30),
    			new google.maps.Point(0, 0),
    			new google.maps.Point(42, 29));
    	mouseOverWaypointMarker = new google.maps.Marker({position:waypointMarkers[index].getPosition(), icon:icon});
    	mouseOverWaypointMarker.setMap(map);
    }
//waypointMarkers[index].setImage(url);
}

function rebuildMarkers() {
    var i = 0;
    var updateWaypointMarkers = map.getZoom()==9||previousZoom==9;
    previousZoom = map.getZoom();
    if (updateWaypointMarkers) {
        for (i = 0; i < waypointMarkers.length; i++) {
            waypointMarkers[i].setMap(null);
        }
        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 oneStepForward() {
    if (trailState.route.isLastPoint(trailState.currentPoint)) {
        var trail = getNextRoute(true);
        jumpToLocation(0, trail.trailId);
    } else {
        moveForward(trailState.route.trailId, trailState.currentPoint, trailState.orientation, trailState.direction, trailState.vOrientation);
    }
}


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);
        if (window.changeTrailListener != null) {
            changeTrailListener(trailId, point);
        }
        trailState.direction = direction;
        trailState.currentPoint = point;
        trailState.orientation = orientation;
        trailState.vOrientation = STRAIGHT;
        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),
        image = file + "_sm.jpg",
        lowResImage = file + ".jpg",
        descriptionFile = file + ".htm";
        //width = document.getElementById("virtualPhoto").clientWidth,
        //height = Math.ceil((width / 1024) * 768);
        //height = vtourPhotoHeight;

    document.getElementById("picNum").innerHTML = trailState.route.trailId + "-" + (trailState.route.getTrailPoint(trailState.currentPoint).sequence);

    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);
    }

    if(!FULL_PANEL){
    	trailState.currentImage = lowResImage;
        image = lowResImage;
    }else{
    	var pos = file.lastIndexOf("/");
    	image = file.substring(0, pos+1) + virtualTourImagePrefix + file.substring(pos+1) + ".jpg";
    	trailState.currentImage = file;
    }
    trailState.currentDescriptionFile = descriptionFile;

    
    var currentImage = document.getElementById("virtualPhoto_img");
    if (currentImage) {
        document.getElementById(topImage).style.zIndex = 0;
        var oldImage = topImage;
        topImage = topImage == "virtualPhoto" ? "virtualPhotoTrans" : "virtualPhoto";
        document.getElementById(topImage + '_img').src = "";
        document.getElementById(topImage + '_img').style.display = "";
        document.getElementById(topImage + '_img').style.opacity = 0;
        document.getElementById(topImage + '_img').src = image;
        document.getElementById(topImage).style.zIndex = 1;
        

        //document.getElementById(topImage).innerHTML = '<img id="' + topImage + '_img" style="display:none" src="' + image + '" />';
        // Inserting a new image element breaks the fullscreen mode because we have already set the height and width
        
        
        document.getElementById("frontNavBlanket").style.display = "";
        var clearTime = 1000;
        if(isIE8() || isIE7()){
        	document.getElementById(topImage + '_img').style.opacity = 1;
        	document.getElementById(oldImage + '_img').display = "none";
        }else{
        	$("#" + topImage + '_img').fadeTo(clearTime, 1);
	        setTimeout(function(){
	        	if(document.getElementById(oldImage + '_img').zIndex==0){
		        	document.getElementById(oldImage + '_img').src = "";
		        	document.getElementById(oldImage + '_img').display = "none";
	        	}
	        }, clearTime);
        }
    } else {
        topImage = "virtualPhoto";
        //document.getElementById(topImage).innerHTML = '<img id="virtualPhoto_img" src="' + image + '">';
        document.getElementById(topImage + '_img').src = image;
        document.getElementById(topImage).style.zIndex = 1;
    }
    
    var img;
    if (img = document.getElementById(topImage + '_img')) {
        addEvent(img, 'load', function() {
            virtualImageLoaded(this);
        });
    }
}

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";
            if (descriptionObj.leftHint.length > 25) {
                descriptionObj.leftHint = descriptionObj.leftHint.substring(0, 26) + "...";
            }
            document.getElementById("leftHintText").innerHTML = "&lt;&lt;&nbsp;" + descriptionObj.leftHint;
            setClickEvent(document.getElementById("leftHintText"), createHrefForCurrentLocation("turnLeft"));
        }
        if (descriptionObj.rightHint != "") {
            rightHint.style.display="block";
            if (descriptionObj.rightHint.length > 25) {
                descriptionObj.rightHint = descriptionObj.rightHint.substring(0, 26) + "...";
            }
            document.getElementById("rightHintText").innerHTML = descriptionObj.rightHint + "&nbsp;&gt;&gt;";
            setClickEvent(document.getElementById("rightHintText"), createHrefForCurrentLocation("turnRight"));
        }
    }
}

function updateLanguage(dropdown) {
    language = dropdown.value;
    getDescriptionObject(trailState.route, trailState.currentPoint, trailState.orientation, trailState.direction, trailState.vOrientation);

    if (playingAvatarAudio !="") {
        avatarEmbed().stopSpeech();
    }

    var prevVideoGuideEnabled = videoGuideEnabled;
    if (videoGuideAvailable && getLanguage(language).isVideoGuide) {
        if (!videoGuideEnabled) {
            avatarEmbed().stopSpeech();
            setupAvatarVideoPanels(true);
        }
    } else if (videoGuideAvailable) {
    	launchAvatarPanelWithCurrentDescription();
    }
    currentVideoGuide = "";
    playingAvatarAudio = "";
    avatarList = "";

    //Only if we are changing from videoGuide to avatar and vice versa.
    if ((prevVideoGuideEnabled && !videoGuideEnabled) || (!prevVideoGuideEnabled && videoGuideEnabled)) {
        var time = 10;
        if (videoGuideEnabled==false) {
            time = 1200;
        }

        setTimeout("updateDescriptionFromTrailState()", time);
    } else {
        updateDescriptionFromTrailState();
    }
}

function updateDescriptionFromTrailState() {
    updateDescriptionRelatedPanels(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(route, point, orientation, direction, vOrientation) {
    getDescriptionObject(route, point, orientation, direction, vOrientation);
    updateDescriptionRelatedPanels(route, point, orientation, direction, vOrientation);
}

function getDescriptionObject(route, point, orientation, direction, vOrientation) {
    var tPoint = route.getTrailPoint(point);
    var params = "";
    var hints = "";
    if (commentMode == DESCRIPTION_MODE) {
        params = "sequence="+tPoint.sequence+"&orientation="+orientation+"&direction="+direction+
        "&vOrientation="+vOrientation+"&trailId="+route.trailId+"&collegeId="+route.collegeId + "&language=" + language;
    }

    var keywords = "";
    var html = ajaxRequest({
        url : "/description.php",
        params : params,
        async : false
    });
    var descriptionObj = eval(trim(html));
    currentDescriptionObj = descriptionObj;
}

function updateDescriptionRelatedPanels(route, point, orientation, direction, vOrientation) {
    document.getElementById("descriptionText").innerHTML = "<div class=panel_h1></div>"  + currentDescriptionObj.description;
    document.getElementById("keywordsText").innerHTML = currentDescriptionObj.title;
    if(FULL_PANEL){
    	fleXenv.updateScrollBars();
    	if(currentDescriptionObj.description==""){
    		//minimizeDescription(false);
    		$("#descriptionPanel").fadeOut();
    	}else{
    		//maximizeDescription(false);
    		$("#descriptionPanel").fadeIn();
    	}
    }

    if (videoGuideEnabled) {
        updateVideoGuide(currentDescriptionObj);
    } else {
        updateAvatar(currentDescriptionObj);
    }
    updateHints(currentDescriptionObj, route, point, orientation, direction);
}

var waitingAvatarAudio = "";
var playingAvatarAudio = "";
function updateAvatar(descriptionObj) {
    if (descriptionObj.avatar != "" && descriptionObj.avatar!=playingAvatarAudio) {
        if (playingAvatarAudio!="") {
            avatarEmbed().stopSpeech();
        }
        if (currentAvatarScene==-1) {
            waitingAvatarAudio = descriptionObj.avatar;
            currentAvatarScene = descriptionObj.avatarScene;
        } else if (descriptionObj.avatarScene != currentAvatarScene) {
            //preloadScene(descriptionObj.avatarScene);
            setTimeout("loadNewScene()", 200);
            currentAvatarScene = descriptionObj.avatarScene;
            waitingAvatarAudio = descriptionObj.avatar;
        } else {
            startPlayingAudio(descriptionObj.avatar, descriptionObj.avatarScene);
        }
    }
}

function avatarEmbed() {
    if (document.getElementById("avatarEmbed")) {
        return document.getElementById("avatarEmbed").contentWindow;
    } else {
        return window;
    }

}

function vh_talkStarted () {
    if (avatarPaused) {
        // if the avatar is supposed to be paused but started talking then
        // pause it
        //avatarEmbed().freezeToggle();
        setTimeout("delayedAvatarPause()", 20);
    }
    avatarTalking = true;
    updatePlayPauseButton();
}
function vh_talkEnded () {
    avatarTalking = false;
    updatePlayPauseButton();
}

function updatePlayPauseButton() {
    if (avatarPaused) {
        document.getElementById("avatarPlayPauseLink").innerHTML = '<img alt="Play" src="/images/playbuttonavatar.gif">';
    } else if (avatarTalking) {
        document.getElementById("avatarPlayPauseLink").innerHTML = '<img alt="Pause" src="/images/pausebutton.gif">';
    } else {
        document.getElementById("avatarPlayPauseLink").innerHTML = '<img alt="Play" src="/images/playbuttonavatar.gif">';
    }
}

function toggleAvatarTalk() {
    if (avatarPaused) {
        avatarPaused = false;
        avatarEmbed().freezeToggle();
        updatePlayPauseButton();
    } else if (avatarTalking) {
        avatarPaused = true;
        avatarEmbed().freezeToggle();
        updatePlayPauseButton();
    } else {
        if (currentDescriptionObj && currentDescriptionObj.avatar!="") {
            avatarEmbed().stopSpeech();
            startPlayingAudio(currentDescriptionObj.avatar, currentDescriptionObj.avatarScene);
        }
    // No need to call the updatePlayPauseButton because it will be called by
    // Avatar events
    }
}

function toggleAvatarSound() {
    muteAvatar = !muteAvatar;
    if (muteAvatar) {
        avatarEmbed().setPlayerVolume(0);
    } else {
        avatarEmbed().setPlayerVolume(7);
    }
    updateAvatarMuteButton();
}

function updateAvatarMuteButton() {
    if (muteAvatar) {
        document.getElementById("avatarSoundLink").innerHTML = "<img alt=\"Unmute\" src=\"/images/unmutebutton.gif\" onMouseOver=\"this.src='/images/unmutebutton-h.gif'\" onMouseOut=\"this.src='/images/unmutebutton.gif'\">";
    } else {
        document.getElementById("avatarSoundLink").innerHTML = "<img alt=\"Mute\" src=\"/images/mutebutton.gif\" onMouseOver=\"this.src='/images/mutebutton-h.gif'\" onMouseOut=\"this.src='/images/mutebutton.gif'\">";
    }
}

var currentVideoGuide;
function updateVideoGuide(descriptionObj) {
    if (descriptionObj.videoGuide != "" && !muteAvatar && descriptionObj.videoGuide!=currentVideoGuide) {
        if (collegeParams.introVideoToPlay!="") {
            playVideoGuide('objmainvideo', college + "/" + collegeParams.introVideoToPlay);
            collegeParams.introVideoToPlay = "";
        } else {
            hideMainVideoPanel();
            playVideoGuide("objvideo", college + "/" + descriptionObj.videoGuide);
        }
        currentVideoGuide = descriptionObj.videoGuide;
        avatarList = avatarList + currentVideoGuide + ";";
    }
}


function wthLoaded() {
    //console.log("WTHLoaded() Called");
    pendingPlayers.remove();
}

function playVideoGuide(objvideo, url) {
    if (Dialog.isOpen) {
        Dialog.addCallback(function() {
        	playVideoGuide(objvideo, url);
        });
    } else {
        //console.log("playVideoGuide:" + objvideo + ":" + url);
        if (pendingPlayers.isReady(objvideo, "playVideoGuide('" + objvideo + "','" + url + "')")) {
        	thisMovie(objvideo).playWTH(url);
        	videoGuidePlaying = true;
    	}
    }
}

function showMainVideoPanel() {
    document.getElementById("wthmainvideocontainer").style.display="";
    drawVideoGuideLayer("wthmainvideo", "objmainvideo");
}

function hideMainVideoPanel() {
    var container = document.getElementById("wthmainvideocontainer");
    if (container && isVisible(container)) {
        container.style.display="none";
        clearVideoGuideLayer("wthmainvideo");
        return true;
    }
    return false;
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function wthComplete() {
    hideMainVideoPanel();
    videoGuidePlaying = false;
    if (instructionsVideoRunning) {
    	closeInstructionsVideo();
    	hideModalDialog(null, FULL_PANEL);
    }
}

function startPlayingAudio(avatarAudio, scene) {
    if (Dialog.isOpen) {
        Dialog.addCallback(function() {
            startPlayingAudio(avatarAudio, scene);
        });
    } else {
        avatarEmbed().sayAudio(avatarAudio);
        avatarList = avatarList + avatarAudio + ";";
        playingAvatarAudio = avatarAudio;
        currentAvatarScene = scene;
        waitingAvatarAudio = "";
    }
}

function delayedAvatarPause() {
    avatarEmbed().freezeToggle();
}

function loadNewScene() {
    setAvatarLoadingMessage(true);
    avatarEmbed().loadScene(currentAvatarScene);
}

function vh_sceneLoaded (sceneIndex) {
    setAvatarLoadingMessage(false);
    if (waitingAvatarAudio != "") {
        startPlayingAudio(waitingAvatarAudio, currentAvatarScene);
    }
}

function createMediaInfoObject(type) {
    return "new MediaInfo(" + type + ",'" + trailState.route.collegeId + "'," + currentWaypoint.id + "," + currentWaypoint.hasVideo + "," + currentWaypoint.hasPanorama + "," + currentWaypoint.hasPicture + ",'" + currentWaypoint.title.replace("'", "\\'") + "')";
}

function setAvatarLoadingMessage(visible) {
    if (visible) {
        document.getElementById("avatarLoading").style.display="block";
    } else {
        document.getElementById("avatarLoading").style.display="none";
    }
}

function switchCommentMode(newMode) {
    if (newMode == commentMode)return;

    if (newMode == DESCRIPTION_MODE) {
        document.getElementById("descriptionLink").className = "selectedComment";
        document.getElementById("reviewLink").className = "unselectedComment";
        setClickEvent(document.getElementById("commentUpdateLink"), "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";
        setClickEvent(document.getElementById("commentUpdateLink"), "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(function(){
    	updateDescription(trailState.route, trailState.currentPoint, trailState.orientation, trailState.direction, trailState.vOrientation);
    },100);
    setTimeout("updateNavPanel()", 400);
    updateWaypointsPanel();
    if (FULL_PANEL) {
        updateFullPanelMedia();
    } else {
        updateMediaPanel();
    }
    updateMediaHelpPanel();
}

var prevWaypoint = null,
	wpCounter = 0;
function updateMediaHelpPanel(){
	if(currentWaypoint == null){
		var obj = getMediaHelpPanel();
		if(isVisible(obj)){
			hideMediaHelpPanel(false, obj);
		}
		return;
	}
	 if(mediaHelpDisabled){
		 return;
	 }
	
	if(prevWaypoint == null){
		prevWaypoint = currentWaypoint;
	}
	if(prevWaypoint.id == currentWaypoint.id){
		wpCounter++;
	}else{
		wpCounter = 1;
	}
	prevWaypoint = currentWaypoint;
	
	if(wpCounter>2 && currentWaypoint.hasMultimedia()){
		showMediaHelpPanel();
	}
}

function getMediaHelpPanel(){
	var obj = document.getElementById("media_help_panel");
	if(obj){
		return obj;
	}
	return null;
}

function waypointChanged(prevWP, newWP){
	// Show Help Panel
	if(prevWP!= null && newWP.hasMultimedia()){
		showMediaHelpPanel(newWP);
	}else{
		var obj = getMediaHelpPanel();
		if(isVisible(obj) && !newWP.hasMultimedia()){
			hideMediaHelpPanel(false, obj);
		}
	}
}

function hideMediaHelpPanel(permenant, obj){
	if(obj!=null){
		document.getElementById("optionsPanel").removeChild(obj);
	}
	if(permenant){	
		mediaHelpDisabled = true;
		
		// Write value to cookie
		Cookie.set("mediahelpdisabled", "1", 30);
	}else{
		mediaHelpDisabled = false;
	}
}

function _showMediaHelpPanel(){
	document.getElementById("media_help_panel").style.display="block";
}

function showMediaHelpPanel(wp){
	if(mediaHelpDisabled || isIE7())return;
	
	mediaHelpDisabled = true;
	var panel = document.createElement("div");
	panel.id = "media_help_panel";
	panel.className = "main_tooltip";
	panel.innerHTML = "Click on the icons above to explore this location in more detail through Panoramas, Photos and Videos";
	panel.style.display="none";
	document.getElementById("optionsPanel").appendChild(panel);
	setTimeout("_showMediaHelpPanel()", 600);
	panel.onclick = function(){
		hideMediaHelpPanel(true, this);
	};
}

var _lastwaypoint = null;
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];
            if(_lastwaypoint == null || _lastwaypoint.id != currentWaypoint.id){
            	waypointChanged(_lastwaypoint, currentWaypoint);
            	_lastwaypoint = currentWaypoint;
            }
            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="";
        setClickEvent(document.getElementById("nextWayPoint"), "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="";
                    setClickEvent(document.getElementById("nextWayPoint"), "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="";
        setClickEvent(document.getElementById("prevWayPoint"), "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="";
                    setClickEvent(document.getElementById("prevWayPoint"), "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";
    if(document.getElementById("tourSelectionNavPanel")){
    	document.getElementById("tourSelectionNavPanel").style.display = "none";
    }
    document.getElementById(panel1).style.display = "";
    if (panel2) {
        document.getElementById(panel2).style.display = "";
    }
}

function buildEndOfTrailPanel() {
    if (trailState.route.lastTrail && collegeParams.isMultiTour()){
    	if (document.getElementById("tourSelectionNavPanel").style.display == "none") {
    		enableSubPanel("tourSelectionNavPanel");
    	}
    	return;
    }
    
	var nextRoutes = new Array();
    if (trailState.route.connections.length > 0) {
        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) {
        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) {
        	// Only circle loop through existing trails if the college does not have multiple tours
        	// Otherwise, we will prompt the user to select a tour from a list
            nextRoute = getNextRoute(!collegeParams.isMultiTour());
        }
        if (nextRoute == null && collegeParams.isMultiTour()){
        	if (document.getElementById("tourSelectionNavPanel").style.display == "none") {
        		enableSubPanel("tourSelectionNavPanel");
        	}
        } else {
        	if (document.getElementById("lastPointNavPanel").style.display == "none") {
                enableSubPanel("lastPointNavPanel");
            }
        	if (nextRoute == null) {
	            document.getElementById("skipToNextRoute").style.display = "none";
	            document.getElementById("lastPointNavStepBack_href").style.display="none";
	        } else {
	            nextRoutes[nextRoutes.length] = nextRoute;
	            document.getElementById("skipToNextRoute").style.display = "";
	            setClickEvent(document.getElementById("lastPointNavSkip_href"), "jumpToLocation(0, '" + nextRoute.trailId + "');");
	            document.getElementById("lastPointNavSkip_href").innerHTML = "Next: " + nextRoute.name;
	        }
	        if (trailState.route.trail.length > 1) {
	            document.getElementById("lastPointNavStepBack_href").style.display="";
	            setClickEvent(document.getElementById("lastPointNavStepBack_href"), createHrefForCurrentLocation("moveBackward"));
	        } else {
	            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(!FULL_PANEL){
	    if (trailState.lowResolution) {
	        document.getElementById("preloadedimage" + index).src = preLoadedImage + ".jpg";
	    }
	    else {
	        document.getElementById("preloadedimage" + index).src = preLoadedImage + "_sm.jpg";
	    }
    }else{
    	var pos = preLoadedImage.lastIndexOf("/");
    	preLoadedImage = preLoadedImage.substring(0, pos+1) + virtualTourImagePrefix + preLoadedImage.substring(pos+1) + ".jpg";
    	document.getElementById("preloadedimage" + index).src = preLoadedImage;
    }
}

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;
    if(FULL_PANEL){
    	document.getElementById(panelId + "_txt").style.opacity = 1;
    	document.getElementById(panelId + "_txt").style.display = "none";
    	//setTimeout(function(){$(".connectionsBox").fadeOut(200);}, 3000);
    }
}

function buildFrontNavPanel(enableFrontArrow)
{
    var tPoint = trailState.route.getTrailPoint(trailState.currentPoint);
    if (enableFrontArrow) {
        setCorner(document.getElementById("frontNavTop"), getDirectionImage(tPoint.frontDir, tPoint.backDir, trailState.direction));
        setClickEvent(document.getElementById("frontNavTop_href"), createHrefForCurrentLocation("moveForward"));
    }

    if (tPoint.hasLeft(trailState.direction)) {
        setCorner(document.getElementById("frontNavLeft"),createNavigationArrow("/images/turn_left_front_arrow.png", "Look Left"));
        setClickEvent(document.getElementById("frontNavLeft_href"), createHrefForCurrentLocation("turnLeft"));
    } else {
        resetCorner(document.getElementById("frontNavLeft"));
    }

    if (tPoint.hasRight(trailState.direction)) {
        setCorner(document.getElementById("frontNavRight"),createNavigationArrow("/images/turn_right_front_arrow.png", "Look Right"));
        setClickEvent(document.getElementById("frontNavRight_href"), createHrefForCurrentLocation("turnRight"));
    } else {
        resetCorner(document.getElementById("frontNavRight"));
    }

    if (trailState.route.trailId != mainTrail || !trailState.route.isFirstPoint(trailState.currentPoint)) {
        setCorner(document.getElementById("frontNavBottom"), getDirectionImage(tPoint.backDir, tPoint.frontDir, trailState.direction));
        setClickEvent(document.getElementById("frontNavBottom_href"), createHrefForBackArrow());
    } else {
        resetCorner(document.getElementById("frontNavBottom"));
    }

}

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" ||
            isVisible(document.getElementById("connectionsNavPanel"))) {
            enableSubPanel("frontNavPanel");
        }
        buildFrontNavPanel(true);
    }
    if (trailState.orientation == LEFT) {
        if (document.getElementById("sideNavPanel").style.display=="none") {
            enableSubPanel("sideNavPanel");
        }

        setClickEvent(document.getElementById("sideNavBack_href"), createHrefForCurrentLocation("resetToFront"));
    }
    if (trailState.orientation == RIGHT) {
        if (document.getElementById("sideNavPanel").style.display=="none") {
            enableSubPanel("sideNavPanel");
        }

        setClickEvent(document.getElementById("sideNavBack_href"), createHrefForCurrentLocation("resetToFront"));
    }
}

function setupAvatarVideoPanels(enableVideoGuide, avatarSceneIndex) {
	// Dont switch the mode if the instructions video guide is running because it is temporary
	if(!instructionsVideoRunning){
		videoGuideEnabled = enableVideoGuide;
	}
    var avatarContainer = document.getElementById("avatarContainer");
    var videoGuidePanel = document.getElementById("wthvideocontainer");
    var actionsPanel = document.getElementById("actionsPanel");
    var descriptionPanel = document.getElementById("descriptionPanel");
    var helpPanel = document.getElementById("navigationhelp");
    var avatariFrame = document.getElementById("avatarEmbed");
    if (enableVideoGuide) {
        drawVideoGuideLayer("wthvideo", "objvideo");
        avatarContainer.style.display = "none";
        try{avatariFrame.src="";}catch(e){} // In case oddcast is down
        videoGuidePanel.style.display="";
        if(!FULL_PANEL){
        	addClass(document.getElementById("tour_panel"), "video_guide_mode");
        	removeClass(document.getElementById("tour_panel"), "avatar_mode");
	        descriptionPanel.className = "descriptionPanelVideoGuide";
	        helpPanel.className = "navigationhelpVideoGuide";
	        var img = collegeParams.actionsPanel.replace(".gif", "vertical.gif");
	        actionsPanel.style.backgroundImage="url(" + img + ")";
        }
    } else {
        hideMainVideoPanel();
        clearVideoGuideLayer("wthvideo");

        muteAvatar =false;
        updateAvatarMuteButton();
        avatarPaused = false;
        updatePlayPauseButton();

        avatarContainer.style.display = "";
        setAvatarLoadingMessage(true);
        try{
        	avatariFrame.src="/avatarembed.php?avatar_num=" + collegeParams.avatarNum + "&avatarSceneIndex=" + avatarSceneIndex +
        		"&h=" + collegeParams.avatarHeight + "&w=" + collegeParams.avatarWidth;
        }catch(e){} // In case sitepad is down
        
        if(!FULL_PANEL){
        	removeClass(document.getElementById("tour_panel"), "video_guide_mode");
        	addClass(document.getElementById("tour_panel"), "avatar_mode");
        }

        // These items only available with Video Guide Compatible panels
        if (videoGuidePanel!=null) {
            videoGuidePanel.style.display="none";
            if(!FULL_PANEL){
	            helpPanel.className = "navigationhelpAvatar";
	            descriptionPanel.className = "descriptionPanelAvatar";
	            actionsPanel.style.backgroundImage="url(" + collegeParams.actionsPanel + ")";
            }
        }
    }
}


var instructionsVideoRunning = false;
function launchInstructionsVideo() {
	instructionsVideoRunning = true; 	// THIS LINE MUST ALWAYS BE FIRST
    if (videoGuideEnabled) {
        thisMovie('objvideo').stopWTH();
    }
    if(FULL_PANEL){
    	createMaskLayer("instructions_fullpanel", false, closeInstructionsVideo, true);
    	if(videoGuideEnabled){
    		playVideoGuide('objvideo', "chantelyourcampus3603497.flv");
    	}else{
    		setupAvatarVideoPanels(true);
    		playVideoGuide('objvideo', "chantelyourcampus3603497.flv");
    	}
    }else{
    	createMaskLayer("instructions", false, closeInstructionsVideo, false);
    	showMainVideoPanel();
    	setTimeout("playInstructionsVideo()", 1200);
    }
}

function playInstructionsVideo() {
	playVideoGuide('objmainvideo', "chantelyourcampus3603497.flv");
}

function closeInstructionsVideo() {
	if(FULL_PANEL){
        if(!videoGuideEnabled){
        	launchAvatarPanelWithCurrentDescription();
        }else{
        	setTimeout(function(){
        		thisMovie('objvideo').stopWTH();
        	},500);
        }
	}else{
		hideMainVideoPanel();
	}
    instructionsVideoRunning = false;
}

function launchAvatarPanelWithCurrentDescription(){
	if (currentDescriptionObj== null || currentDescriptionObj.avatarSceneIndex=="") {
        setupAvatarVideoPanels(false, collegeParams.introAvatarSceneIndex);
    } else {
        setupAvatarVideoPanels(false, currentDescriptionObj.avatarSceneIndex);
    }
}

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 "jumpToLocation(" + (destTrail.trail.length - 1) + ", '" + destTrail.trailId + "')";
            }
        }
        var route = getPreviousRoute(true);
        if (route != null) {
            return "jumpToLocation(" + (route.trail.length - 1) + ", '" + route.trailId + "')";
        }
    }
    return "#";
}

function createHrefForCurrentLocation(functionName) {
    return 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("/images/front_left_arrow" + arrowSize + ".png");
    }
    if (current == F) {
        return createNavigationArrow("/images/front_arrow" + arrowSize + ".png");
    }
    if (current == F_R) {
        return createNavigationArrow("/images/front_right_arrow" + arrowSize + ".png");
    }
    if (current == B_L) {
        return createNavigationArrow("/images/back_left_arrow.png");
    }
    if (current == B) {
        return createNavigationArrow("/images/back_arrow.png");
    }
    if (current == B_R) {
        return createNavigationArrow("/images/back_right_arrow.png");
    }
    if (current == B_BR) {
        return createNavigationArrow("/images/back_bear_right.png");
    }
    if (current == B_BL) {
        return createNavigationArrow("/images/back_bear_left.png");
    }
    if (current == F_BR) {
    	return createNavigationArrow("/images/front_bear_right" + arrowSize + ".png");
    }
    if (current == F_BL) {
        return createNavigationArrow("/images/front_bear_left" + arrowSize + ".png");
    }
    if (current == F_B) {
        return createNavigationArrow("/images/front_turnaround_arrow1.png");
    }
    if (current == B_F) {
        return createNavigationArrow("/images/back_arrow.png");
    }
}

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 = {};
    trailState.route = getRouteObject(mainTrail);

    // This scenario will occur if the college has a number of tours defined. Each
    // tour has a number of trail
    if (trailState.route==null) {
        trailState.route = trails[0];
    }
    if (collegeParams.startOrientation != -1) {
        trailState.orientation = collegeParams.startOrientation;
    } else {
        trailState.orientation = trailState.route.startOrientation;
    }
    if (collegeParams.startPoint != -1) {
        trailState.currentPoint = collegeParams.startPoint;
    } else {
        trailState.currentPoint = trailState.route.startPoint;
    }
    if (collegeParams.startDirection != -1) {
        trailState.direction = collegeParams.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];
        }
    }
    return null;
}

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 google.maps.MarkerImage("/images/man.png", 
    			new google.maps.Size(24, 38),
    			new google.maps.Point(0, 0),
    			new google.maps.Point(12, 38));
    	currMarker = new google.maps.Marker({position:location, icon:icon});
    	currMarker.setMap(map);
        moveToCurrentPoint();
    }
}

function moveToCurrentPoint() {
    var trailPoint = trailState.route.getTrailPoint(trailState.currentPoint);
    var p = new google.maps.LatLng(trailPoint.lat, trailPoint.lng);
    currMarker.setMap(null);
    currMarker = new google.maps.Marker({position:p, icon:icon});
    currMarker.setMap(map);
    map.panTo(p);
}

function isVisible(obj) {
    return obj!=null && (obj.style.display=="" || obj.style.display=="block");
}

function menuEventListener(opened){
	if(document.getElementById("avatarPanel") && opened){
		document.getElementById("avatarPanel").style.visibility = "hidden";
	}
	if(document.getElementById("avatarPanel") && !opened){
		document.getElementById("avatarPanel").style.visibility = "visible";
	}
}

function prepareWalkingTourPanel(){
	if(FULL_PANEL){
		if(!doesPanelExist("#loading_panel")){
			walkingTourContainerInitialized = false;
			if(document.getElementById("avatarEmbed")){
		        document.getElementById("avatarEmbed").style.visibility = "hidden";
			}
			$("#tour_container").append("<div id=loading_panel></div>");
		}
	}
}

var flexEnvInitialized = false;
function walkingTourPanelInitialized(){
	if(FULL_PANEL){
		//map.savePosition();
		if(flexEnvInitialized){
			fleXenv.updateScrollBars(); 
		}else{
			fleXenv.fleXcrollMain("descriptionTextContainer");
			flexEnvInitialized = true;
		}
		google.maps.event.trigger(map, 'resize');
	    //map.setCenter(new google.maps.LatLng(0,0));
	    //map.returnToSavedPosition();
    	$("#loading_panel").fadeOut(400, function(){$(this).remove()});
    	if(document.getElementById("avatarEmbed")){
            document.getElementById("avatarEmbed").style.visibility = "visible";
    	}
    }
	walkingTourContainerInitialized = true;
}

function virtualImageLoaded(image) {
	if(walkingTourContainerInitialized == false && FULL_PANEL){
		setTimeout(function() {
        	document.getElementById('tour_content').style.width = image.clientWidth + 'px';
        	walkingTourPanelInitialized();
		}, 100);
    }
}

var modalDialogPausedAvatar = false;
function modalMaskWillDisplay(){
	if(document.getElementById("avatarEmbed")){
        document.getElementById("avatarEmbed").style.visibility = "hidden";
        if(!avatarPaused && avatarTalking){
            modalDialogPausedAvatar = true;
            toggleAvatarTalk();
        }
    }
    if(typeof videoGuideEnabled !== "undefined" && videoGuidePlaying) {
        try {
            thisMovie('objvideo').pauseWTH();
            if(document.getElementById("objmainvideo")){
            	thisMovie('objmainvideo').pauseWTH();
            }
        } catch(err){}
    }
}

function modalMaskWillHide(){
	if (document.getElementById("avatarEmbed")) {
        document.getElementById("avatarEmbed").style.visibility = "visible";
        if(modalDialogPausedAvatar){
            toggleAvatarTalk();
            modalDialogPausedAvatar = false;
        }
    }
    if (typeof videoGuideEnabled !== "undefined" && videoGuidePlaying) {
        try {
            thisMovie('objvideo').unpauseWTH();
            if(document.getElementById("objmainvideo")){
            	thisMovie('objmainvideo').unpauseWTH();
            }
        } catch(err) {}
    }
}

function drawVideoGuideLayer(divname, videoname) {
    pendingPlayers.add(videoname);
    var video = document.getElementById(divname);
    video.style.display="";   
    
    var markUp = '';
    markUp += '  <object id="'+videoname+'" style="outline:none;" type="application/x-shockwave-flash" width="100%" height="100%" data="/avatar/c360player.swf">';
    markUp += '    <param name="movie" value="/avatar/c360player.swf" />';
    markUp += '    <param name="quality" value="high" />';
    markUp += '    <param name="wmode" value="transparent" />';
    markUp += '    <param name="allowscriptaccess" value="always" />';
    markUp += '    <param name="swfversion" value="9.0.45.0" />';
    markUp += '    <param name="FlashVars" value="fadein=1&fadeout=0.5" />'; 
    markUp += '  </object>';

    video.innerHTML = markUp;
}


function Route(name, trailId, collegeId, trail, waypoints,
    description, startPoint, startOrientation, startDirection, connections, lastTrail) {
    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;
    this.lastTrail = lastTrail;

    // Create a relative indexing for points on a trail
    var i = 0;
    for (i=0;i<this.trail.length;i++) {
        this.trail[i].index = i;
    }

    // Associate each waypoint with its relative location on the trail
    var i = 0;
    for (i=0;i<this.waypoints.length;i++) {
        var tPoint = this.getTrailPointBySequence(this.waypoints[i].sequence);
        this.waypoints[i].point = tPoint.index;
    }
}
Route.prototype.getTrailPoint = function(index) {
    if (index >= this.trail.length || index < 0) {
        return null;
    }
    return this.trail[index];
}
Route.prototype.getTrailPointBySequence = function(sequence) {
    var i = 0;
    for (i=0; i<this.trail.length;i++) {
        if (sequence==this.trail[i].sequence) {
            return this.trail[i];
        }
    }
    return null;
}
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
    this.index = -1;

    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, videoGuide, avatarSceneIndex) {
    this.title = title;
    this.description = description;
    this.leftHint = leftHint;
    this.rightHint = rightHint;
    this.avatar = avatar;
    this.avatarScene = avatarScene;
    this.videoGuide = videoGuide;
    this.avatarSceneIndex = avatarSceneIndex;
}

function Waypoint(id, title, college, trail, sequence, orientation, main, heading,
    icon, videoThumb, panoThumb, photoThumb, tourlat, tourlng, enableTourLoc) {
    this.title = title;
    this.trail = trail;
    this.college = college;
    this.sequence = sequence;
    this.main = main;
    this.id = id;
    this.hasPanorama = panoThumb!="";
    this.hasPicture = photoThumb!="";
    this.hasVideo = videoThumb!="";
    this.videoThumb = videoThumb;
    this.photoThumb = photoThumb;
    this.panoThumb = panoThumb;
    this.heading = heading;
    this.icon = icon;
    this.tourlat = tourlat;
    this.tourlng = tourlng;
    this.enableTourLoc = enableTourLoc;
    this.point = -1;
    if (orientation == "FRONT") {
        this.orientation = FRONT;
    } else if (orientation == "LEFT") {
        this.orientation = LEFT;
    } else if (orientation == "RIGHT") {
        this.orientation = RIGHT;
    }
    
    Waypoint.prototype.hasMultimedia = function(){
    	return this.hasPanorama || this.hasVideo || this.hasPicture;
    }
}

function Connection(srcTrail, destTrail, connection) {
    this.srcTrail = srcTrail;
    this.destTrail = destTrail;
    this.connection = connection;
}

function PendingPlayers() {
    this.players = "";
    this.total = 0;
    this.callbacks = new Array();
}

PendingPlayers.prototype.add = function(name) {
    //console.log("PendingPlayers.add:" + name);
    this.players = this.players + ":" + name;
    this.total++;
}

PendingPlayers.prototype.remove = function(name) {
    //console.log("PendingPlayers.remove:" + name);
    if (--this.total<=0) {
        this.players = "";
        var i = 0;
        for (i;i<this.callbacks.length;i++) {
            eval(this.callbacks[i]);
        }
        this.callbacks = [];
        this.total = 0;
    }
}

PendingPlayers.prototype.isReady = function(name, callback) {
    var playerPending = this.players.indexOf(name)>-1;
    //console.log("PendingPlayers.isReady:" + !playerPending);
    if (playerPending) {
        this.callbacks.push(callback);
        return false;
    }
    return true;
}

function clearVideoGuideLayer(divname) {
    var video = document.getElementById(divname);
    if (video) {
        video.style.display = "none";
        video.innerHTML = "";
    }
}

function CollegeParams() {
    this.collegeid;
    this.actionsPanel;
    this.startPoint;
    this.startOrientation;
    this.startDirection;
    this.avatarNum;
    this.avatarHeight;
    this.avatarWidth;
    this.introVideoToPlay="";
    this.introAvatarSceneIndex="";
    this.fullPanelCompatible = true;
    this.tourListIds = "";
    this.currentTourId = "";
    
    CollegeParams.prototype.isMultiTour = function(){
    	return this.tourListIds!= "" && this.tourListIds.length > 0;
    }
}

function getLanguage(language) {
    var i = 0;
    for (i = 0; i < languages.length; i++) {
        if (languages[i].language == language)return languages[i];
    }
    return null;
}

function Language(language, isVideoGuide) {
    this.language = language;
    this.isVideoGuide = isVideoGuide;
}


function CoordMapType() {
	CoordMapType.prototype.tileSize = new google.maps.Size(256,256);
	CoordMapType.prototype.maxZoom = 11;
	CoordMapType.prototype.minZoom = 9;

	var tileCache; 

    CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
    	var id = "id" + coord.x + coord.y + zoom;
    	var div = ownerDocument.getElementById(id);
    	if(div){
    		return div;
    	}
    	div = ownerDocument.createElement("div");
    	var img = ownerDocument.createElement("img");
    	var url = CustomGetTileUrl(coord, zoom);
    	div.id = id;
    	img.src = url;
    	div.style.width = this.tileSize.width + 'px';
    	div.style.height = this.tileSize.height + 'px';
    	div.appendChild(img);
    	return div;
    };

    CoordMapType.prototype.name = "Tile #s";
    CoordMapType.prototype.alt = "Tile Coordinate Map Type";
}




