/******************************************************************************
******************************************************************************
// CONTENT OPERATIONS
// Copyright 2007-2008 Collaborative Bike Map Project
******************************************************************************
******************************************************************************/
/*
SAVE STATES...
1. Buffered changes to existing route
2. Buffered changes to new route - not finished yet (may save as route in progress?)
3. Finished route, ready for save
4. Deleted route, ready for save
5. Buffered changes to multiple routes (new routes, deletions, edits)
NOTES...
- User will be prompted whether to save changes when route is finished
- Only intersections require changes to multiple routes at the same time
- Opening a route requires that it not be opened by another user.  Not sure how to handle.
  Maybe allow route checkin/out.  
*/


/******************************************************************************/
// Add a new route.                        
// This is called when the New Route button is clicked.
// It creates a new route, opens it for editing, and appends it to the RouteList array.
// Mode is set to MODE_NEW (new route without any points yet).
// Route fields are initialized to null or other default values.
/*******************************************************************************/
// NOTE: NEED TO DELAY SOME OF THESE ACTIONS UNTIL A FIRST POINT IS ADDED!!!
function routeAdd () {
	if (OpenRoute == null) {
		var rte = new Route;
		if (RouteList == null) 
			RouteList = new LinkedList;
		rte.id = RouteList.genUniqueListId();      // generate unique id within RouteList
		RouteList.insertEnd (rte);
		SelectedRoute = OpenRoute = rte;
		//debugger;
		SelectedPoint = SelectedSegment = null;
		CurrMode = MODE_NEW;
		setModeText (CurrMode);
		setButtons_NewEmptyRoute();
		FldInfo.configFields_NewEmptyRoute();       // Blank (but enable) route fields, disable seg/pnt fields
	}
}

/******************************************************************************/
// Delete route.                        
// This is called when the Delete Route button is clicked.
// Deletes the open route if one is open.  Otherwise deletes the selected route
// if one is selected.  Parameter prompt is optional (false by default).
/*******************************************************************************/
function routeDelete (prompt) {
	var msg;
	var rte, pnt;

	if (prompt == undefined)
		prompt = true;

	if (SelectedRoute != null) {
		if (OpenRoute != null) {
			msg = "Are you sure you wish to delete the currently open route?";
			rte = OpenRoute;
		}	
		else { 
			msg = "Are you sure you wish to delete the selected route";
			if (SelectedRoute.name != null) 
				msg += " entitled '" + SelectedRoute.name + "'"; 
			msg += "?";
			rte = SelectedRoute;
		}

		// If user confirms
		if (!prompt || confirm (msg)) {

			//Delete all overlays
			pnt = rte.pointlist.firstnode;  
			while (pnt != null) {           // loop thru points
				pnt.erasePoint();           // remove each marker           			
				pnt = pnt.next;
			}
			rte.erasePolylines();           // remove polylines
			//debugger;
			// Remove route from data structure    
			SelectedRoute.cleanup();				// clean up route contents
			RouteList.remove (SelectedRoute);       // remove route from RouteList
			//dumpText ("After route deletion");
			//dumpRoute(SelectedRoute);
			SelectedRoute = null;                   // no route is selected now
			OpenRoute = null;
			SelectedPoint = null;
			SelectedSegment = null;
			
			// Return to view mode, reset "current" globals, set buttons and text on screen
			enterViewMode ();

			/* CurrMode = MODE_VIEW;
			setModeText (MODE_VIEW);
			setButtons_ViewMode(); */
			// setButtons_DeletedRoute();

			// Start new route automatically
			// routeAdd();        // this also updates buttons on the screen
		}
	}
	else {
		alert ("You must first select a route.");
	}
}



/******************************************************************************/
// Open selected route for editing.
// This is called when the Edit Route button is clicked.
// NOT FINISHED WITH THIS.
/*******************************************************************************/
function routeEdit () {
	if (OpenRoute == null) {
		if (SelectedRoute != null) {
			msg = "Are you sure you wish to edit the selected route";
			if (SelectedRoute.name != null) 
				msg += " (entitled '" + SelectedRoute.name + "')"; 
			msg += "?";
			if (confirm (msg)) {
				/* Need to add code to check route out from server */
				/********/
				/* Make this route the selected route */
				OpenRoute = SelectedRoute;
				CurrMode == MODE_APPEND;
			}
		}
		else {
			alert ("You must first select a route.");
		}
	}
	else {
		alert ("You must first save or end the currently open route.");
	}
}

/******************************************************************************/
// End and save the open route.
// This is called when the End Route button is clicked.
/*******************************************************************************/
function routeEnd () {
	if (OpenRoute != null) {
		// debugger;
		if (OpenRoute.pointlist.length == 0) 
			alert ("The open route has no points.");
		else if (OpenRoute.pointlist.length == 1) {
			openPrompt (
				"<p>The open route has only one point.  Do you wish to cancel this route and start another?</p>" +
				"<p align='center'><button type='button' onclick='routeEndContinue()' name='yesbutton' style='width:60px'>Yes</button></p>" +
				"<p align='center'><button type='button' onclick='closePrompt()' name='nobutton' style='width:60px'>No</button></p>"
			);
			// If yes clicked, jump to routeEndContinue() //
		}
		else {
			// Need to save route to server here 
			/*********/

			// Change markers and polylines of old route
			OpenRoute.redrawRoute (false);
			
			// Return to view mode
			enterViewMode();
			
			// Start new route
			// routeAdd();       
		}
	}
	else {
		alert ("You do not have a route open.");
	}
}


/******************************************************************************/
// This is called by the delete prompt (currently posted by routeEnd()) if the user
// confirms it's okay to delete the route. 
/*******************************************************************************/
function routeEndContinue () {
	closePrompt();

	// delete currently open route, start empty new route
	routeDelete (false);        // don't prompt user
}





/******************************************************************************/
// Add point to route.  Updates the route data model, route markers and polylines, 
// and on-screen buttons and fields.  It updates SelectedSegment and 
// SelectedPoint to point to the new point and its segment.
// It returns the new point object and redrawn points (legacy).
/*******************************************************************************/
function addPoint (lat, lng) {
	var pnt = null;
	var prevpnt;
	var seg = null;
	var prev_SelectedSegment;
	var situation;

	var pnts2redraw = new Array ();
	// var redrawpoint1 = null;       // existing point to redraw if any
	// var redrawpoint2 = null;       // existing point to redraw if any	

	prev_SelectedSegment = SelectedSegment;
	// If creating first point of route...
	if (OpenRoute.pointlist.length == 0) {
		//alert ("addPoint first point");
		// Push new point
		pnt = new Point (lat, lng);	
		pnt.id = 1;
		pnt.boundtype = SEG_BOUNDARY;
		pnt.route = OpenRoute;
		OpenRoute.pointlist.insertEnd (pnt); 
		// dumpText ("Inserted first point, linked list length = " + OpenRoute.pointlist.length);
		// Create new segment  
		seg = new Segment;               // single point only allowed as route is being built
		seg.id = 1;
		seg.remember();                  // set segment values to remembered values (whatever last created segment was)
		// seg.bikeway = Math.floor(Math.random()*5) + 1;      // for testing
		// seg.sidewalk = Math.floor(Math.random()*2) + 1;     // for testing
		seg.route = OpenRoute;
		OpenRoute.seglist.insertEnd (seg);       // push onto segment list
		// Link point to segment (SIMPLE MODEL)
		pnt.segafter = seg;		
		// Set COMPLEX MODEL data
		OpenRoute.buildComplexModel ();
		// Update mode, update buttons
		CurrMode = MODE_APPEND;      // enter append mode
		setModeText (CurrMode);      // display instructions accordingly
		// setButtons_FirstRoutePoint();             // MOVED BELOW
		// FldInfo.configFields_FirstRoutePoint();     // MOVED BELOW
	}

	else {         // Else not creating first point of route...
		// debugger;
		// If appending to end of route...
		if (CurrMode == MODE_APPEND || (CurrMode == MODE_INSERT_AFTER && SelectedPoint == OpenRoute.pointlist.lastnode)) {
			// Push new point.  Asume we're adding it to the final existing segment.  Split after if appropriate.
			//alert ("addPoint appending to end");
			pnt = new Point (lat, lng);	
			pnt.boundtype = SEG_BOUNDARY;	
			pnt.route = OpenRoute;
			pnt.segafter = null;
			pnt.id = OpenRoute.pointlist.genUniqueListId ();			
			prevpnt = OpenRoute.pointlist.lastnode;
			// dumpText ("Checking length in addPoint: " + OpenRoute.pointlist.length);
			if (OpenRoute.pointlist.length > 1) {          // if more than one point in route)
				prevpnt.boundtype = SEG_INTERIOR;          // update previous point boundary type
				prevpnt.segafter = prevpnt.segbefore;      // since interior point			
				pnts2redraw.push (prevpnt);                     // change in boundary type affects marker icon
				// dumpText ("Redraw needed, id = " + prevpnt.id);
			}
			OpenRoute.pointlist.insertEnd (pnt);         // do insert
			// Set COMPLEX MODEL data
			OpenRoute.buildComplexModel ();
			// If we're adding a new segment, split at previous final point
			if (OpenRoute.pending_new_seg) {             
				splitSegment (prevpnt, false);
				OpenRoute.pending_new_seg = false;
			}
		}
		// Else if inserting before beginning of route...
		else if (CurrMode == MODE_INSERT_BEFORE && SelectedPoint == OpenRoute.pointlist.firstnode) {
			//alert ("addPoint inserting before start");
			// Push new point into first segment.
			pnt = new Point (lat, lng);	
			pnt.boundtype = SEG_BOUNDARY;
			pnt.route = OpenRoute;
			pnt.segafter = OpenRoute.seglist.firstnode;
			pnt.id = OpenRoute.pointlist.genUniqueListId ();			
			if (OpenRoute.pointlist.length > 1) {         // if already more than one point in route
				OpenRoute.pointlist.firstnode.boundtype = SEG_INTERIOR;    // update 2nd point's boundary status
				pnts2redraw.push (OpenRoute.pointlist.firstnode);         // change in boundary type affects marker icon
			}
			OpenRoute.pointlist.insertBeginning (pnt);   // do insert
			// Set COMPLEX MODEL data
			OpenRoute.buildComplexModel ();
		}
		// Else inserting in middle of route
		else {     
			// debugger;
			//alert ("addPoint inserting in middle");
			// Push new point between two existing points.
			pnt = new Point (lat, lng);	
			pnt.boundtype = SEG_INTERIOR;
			pnt.route = OpenRoute;
			pnt.id = OpenRoute.pointlist.genUniqueListId();
			if (CurrMode == MODE_INSERT_BEFORE) {
				pnt.segafter = SelectedPoint.prev.segafter;
				OpenRoute.pointlist.insertBefore (SelectedPoint, pnt);             // do insert
			}
			else {       // mode == MODE_INSERT_AFTER
				pnt.segafter = SelectedPoint.segafter;
				OpenRoute.pointlist.insertAfter (SelectedPoint, pnt);              // do insert
			}
			// Set COMPLEX MODEL data
			OpenRoute.buildComplexModel ();
		}

		// Common logic for cases where new point is NOT first point starts here...
		// Update buttons if second point of route
		// if (OpenRoute.pointlist.length == 2)       // MOVED BELOW
		//  	setButtons_SecondRoutePoint();
	}

	// Update pointers to selected point/segment
	// dumpText ("SelectedPoint = " + getField(SelectedPoint, "id"));
	var oldselectedpoint = selectPoint (pnt, false, false);       // select new point (don't redraw route yet)
	if (oldselectedpoint != null) {
		pnts2redraw.push (oldselectedpoint);
	}

	// Update on-screen fields for new point and (if new) segment - NO, DONE BY SelectPoint()
	//... FldInfo.setFields_NewPointOrSegment (true, (prev_SelectedSegment != SelectedSegment));

	// Update map markers and polylines
	pnt.drawPoint(true);                                     // Draw marker for this point		
	redrawSpecPoints (pnts2redraw, true);
	OpenRoute.redrawPolylines (true, true);                       // redraw polyline on screen

	// Set fields & buttons as appropriate
	if (OpenRoute.pointlist.length == 1) {
		FldInfo.configFields_FirstRoutePoint();     
		setButtons_FirstRoutePoint();
	}
	else if (OpenRoute.pointlist.length == 2) {
		setButtons_SecondRoutePoint();
	}

	// Return point and pnts2redraw via object
	return ({newpoint:pnt, pnts2redraw:pnts2redraw});

	// }
	// else field check failed, so do nothing (user must first fix fields)
	// else {
	// 	return ({newpoint:null, pnts2redraw:null});
	// }
	
}

/*******************************************************************
// Deletes the selected point and redraws the route.  Called from button click.
// Cases:
//  1. Final point, only point of route
//  2. Final point, 2nd point of route
//  4. Final point, 2nd point of segment (but not of route)
//  3. Final point, 3rd+ point of segment & route
//  4. Initial point of 2-point route
//  5. Initial point, 3-point+ route, 2-point segment
//  6. Initial point, 3-point+ route, 3-point+ segment
//  7. Middle point, segment interior
//  8. Middle point, segment boundary
// These impact:
//  1. Point list
//  2. Segmenting - may need to prompt
//  3. Use of zero-span segment
//  4. Pending new segment flag - left alone
********************************************************************/
function deletePoint () {
	var pnts2redraw = new Array ();
	var delseg, p;

	//debugger;
	if (OpenRoute != null && SelectedPoint != null) {       // safety check
		if (FldInfo.checkAndSaveOnNext (SIT_PNT_DEL, SelectedPoint)) {      // check and save currently displayed seg info if necessary
			var pnt = SelectedPoint;
			var pointlist = OpenRoute.pointlist;
			var seglist = OpenRoute.seglist;
			var newselectedpoint = SelectedPoint;     // init

			// Check for special case where entire route would be deleted - requires confirmation, so do first
			if (pointlist.length == 1) {         // if only one point in route
				routeDelete();                   // delete the whole route - called subroutine does everything
			}

			// Else not trying to delete entire route
			else {
				// First delete overlay from screen (while we still have Point object)
				pnt.erasePoint(); 

				// Test for which case
				// if last point of route ////////////////////
				if (pnt.next == null) {
					newselectedpoint = pnt.prev;         // point to select after deletion
					if (pointlist.length == 2) {         // if second point of two-point route
						pointlist.remove(pnt);
					}
					else if (pnt.segbefore.span == 1) {    // second point of two-point segment (not 1st segment) - remember what span means!
						pnt.prev.segafter = null;          // no segafter for previous point
						seglist.remove(pnt.segbefore);     // delete segment
						pointlist.remove(pnt);             // delete point
					}
					else {                                 // nth point of segment (n > 2)
						pnt.prev.boundtype = SEG_BOUNDARY; // segment has new end point
						pnt.prev.segafter = null;          // no segafter for previous point
						pnts2redraw.push (pnt.prev);       // redundant but that's okay 
						pointlist.remove(pnt);             // delete point
					}
				}
				// else if first point of route ////////////////////
				else if (pnt.prev == null) {               
					newselectedpoint = pnt.next;           // point to select after deletion

					if (pointlist.length == 2) {           // first point of two-point route
						pnt.next.segafter = pnt.segafter;  // update segment pointer
						pointlist.remove(pnt);
					}
					else if (pnt.segafter.span == 1) {     // first point of two-point segment (not 2-pt route) 
						seglist.remove(pnt.segafter);      // delete segment
						pointlist.remove(pnt);             // delete point
					}
					else {                       // first point of n-point segment (n > 2)
						pnt.next.boundtype = SEG_BOUNDARY; // segment has new start point
						pnts2redraw.push (pnt.next);       // redundant but that's okay 
						// pnt.next.segafter = pnt.segafter;  // update SIMPLE MODEL segment pointer
						pointlist.remove(pnt);
					}
				}
				// else neither first nor last point of route ////////////////////
				else {                           
					newselectedpoint = pnt.next;           // point to select after deletion
					if (pnt.boundtype == SEG_INTERIOR) {       // if not a segment boundary
						pointlist.remove(pnt);                 // simply remove the point
					}
					else {                                     // else a segment boundary
						// Do we move segment boundary to the next point, or merge the two segments???
						// Probably should merge the two segments.  That requires prompting.  
						// For now, do no prompting.  Just remove the second segment.
						//dumpText ("Before delete");
						//dumpRoute(OpenRoute);
						delseg = pnt.segafter;
						for (p=pnt; p!=null && p.segafter==delseg; p=p.next) {    // update segafter for each point in deleted segment
							p.segafter = pnt.segbefore;
						}
						seglist.remove(delseg);          // delete segment (after point)
						pointlist.remove(pnt);
					}
				}

				// Finish up //////////////////////////
				// Set COMPLEX MODEL data
				//dumpText ("After delete -- before complex model built");
				//dumpRoute(OpenRoute);				
				OpenRoute.buildComplexModel ();

				// Update SelectedPoint, SelectedSegment 
				SelectedPoint = null;							 // do this to be safe
				selectPoint (newselectedpoint, false, false);	    // update info but don't redraw yet	

				// Need to refresh map...
				pnts2redraw.push (newselectedpoint);      // make sure we draw newly selected point (as well as points determined above)
				redrawSpecPoints (pnts2redraw, true);          // redraw altered points			
				OpenRoute.redrawPolylines (true, true);    // redraw route polylines

				// Enable/disable buttons as appropriate
				if (OpenRoute.pointlist.length == 1) 
					setButtons_FirstRoutePoint();
					
				//dumpText ("After delete");
				//dumpRoute (OpenRoute);

			}           // end else not deleting entire route			
		}            // end check & save ok
	}            // end safety checks ok
}


/*******************************************************************
* End or split segment at the selected point.  Called from button click
* so it handles marker/polyline updates.
********************************************************************/
function endSegment () {
	var ok, pnt;

	if (OpenRoute != null && SelectedPoint != null) {     // safety check

		// Check which fields need to be checked, save fields if checks pass 
		//   (currently does nothing for split segment case because selected point & segment doesn't change)
		if (FldInfo.checkAndSaveOnNext (SIT_SPLIT_SEG, SelectedPoint)) {       // do the check & save

			if (SelectedPoint.next == null) {        // if last point of route
				OpenRoute.pending_new_seg = true;    // next append will trigger new segment
			}
			else if (SelectedPoint.boundtype == SEG_INTERIOR) {       // else if interior point of a segment
				//debugger;
				splitSegment (SelectedPoint, false);                 // split the segment (first part retains segment info)
					// this leave both SelectedPoint and SelectedSegment alone
			}
			
			// Update SelectedSegment
			pnt = SelectedPoint;
			selectPoint (pnt, false);     // this updates SelectedPoint and SelectedSegment - be careful

			// Need to refresh map...
			redrawSpecPoints (new Array (SelectedPoint), true);
			OpenRoute.redrawPolylines (true, true);

			// Update fields carefully...
			//  ...
		}
	}
}

/******************************************************************************/
// Split route into segments at specified point.  New segment is created
// before the point if beforeflag = true, otherwise it's created after the point.
// Routine does nothing if point is already a segment boundary.  
// It returns the new segment object if it created a segment, null if it didn't.  
// It does NOT update SelectedPoint or SelectedSegment and does NOT update the diaplay,
// so that it can be called from routines that update these themselves.
/*******************************************************************************/
function splitSegment (pnt, beforeflag) {

	var newseg = null;
	var oldseg;
	var p;

	// If interior point (else do nothing)
	if (pnt.boundtype == SEG_INTERIOR) { 
		pnt.boundtype = SEG_BOUNDARY;
		oldseg = pnt.segafter;
		
		// Create segment
		newseg = new Segment;
		newseg.id = OpenRoute.seglist.genUniqueListId();
		newseg.route = OpenRoute;
		newseg.remember();       // load with saved residual values 

		if (!beforeflag) {       // inserting new segment after point
			OpenRoute.seglist.insertAfter (oldseg, newseg);       // insert into seglist
			for (p=pnt; p!=null && p.segafter==oldseg; p=p.next) 
				p.segafter = newseg;
		}
		else {            // Else inserting new segment before point
			OpenRoute.seglist.insertBefore (oldseg, newseg);       // insert into seglist
			for (p=oldseg.firstpoint; p!=pnt; p=p.next)
				p.segafter = newseg;			
		}
		
		// Set COMPLEX MODEL data
		OpenRoute.buildComplexModel ();	
	}
	
	//dumpText ("After split");
	//dumpRoute (OpenRoute);	
	
	return newseg;
}


/******************************************************************************/
// Set up event listener to handle polyline click event.  This is isolated into
// a separate function to ensure that a closure is created for each polyline.
/*******************************************************************************/
/* function setPolylineListener (overlay, firstpoint, lastpoint) {
	// Set up event listener to handle polyline click event - BEWARE - Closure! (avoid calling in loops!)
	GEvent.addListener(overlay, 'click', function() {
		// dumpText ("Polyline click.  Firstpoint ID = " + firstpoint.id + ", Lastpoint ID = " + lastpoint.id + ", firstpoint text = " + firstpoint.opp_pntnote); 
		polylineClick (overlay, firstpoint, lastpoint); 
	});
} */




/******************************************************************************/
// Move point, i.e. change latitude and longitude.
/*******************************************************************************/
//function movePoint (pnt, lat, lng) {
//	pnt.lat = lat;
//	pnt.long = lng;
//}

/******************************************************************************/
// Move segment split forward or backwards one point.
// Point must be a boundary point or error will be returned.
// Returns true if successful, false if error.
/*******************************************************************************/
function moveSegmentSplit (pnt, forwardflag) {
	if (point.boundtype == SEG_BOUNDARY) { 
		// ...
		return true;
	}
	else {
		return false;
	}
}




/****************************************************************
// Select specified point and its segment.  
// No checking or saving of fields is performed... caller must do that PRIOR
// to calling this routine.
// Redraw the parent route if redraw parameter = true.  If the point is at a 
// segment boundary where two segments meet, select the segment
// starting at the point. 
// For performance reasons, SelectedPoint may NOT point to a deleted point  
// if redraw == true.  It may be null however.  
// SelectedSegment may be null or point to a deleted segment.  
// Inputs: 
//   newpnt - Point to select (along with its segment)
//   redraw - Redraw parent route if set to true
// Return:
//   Previous value of SelectedPoint global, before this routine changed it.
****************************************************************/
function selectPoint (newpnt, redraw) {
	var prevpnt, prevseg;              // save so we can return it
	var rte;
	var newseg;

	// Setup
	rte = (newpnt == null) ? null : newpnt.route;       // ???
	prevpnt = SelectedPoint;       // save old value         
	prevseg = SelectedSegment;     // save old value

	// Determine new segment for selected point
	newseg = getCurrSegForPnt (newpnt);    // determine new curr segment from new curr point

	ok = true;

	// Update SelectedPoint and SelectedSegment
	SelectedPoint = newpnt;                   
	SelectedSegment = newseg;

	// Load new field values
	if (newpnt != prevpnt)
		FldInfo.loadFields (PNT);
	if (newseg != prevseg)
		FldInfo.loadFields (SEG);

	// Redraw if we're asked to redraw the route - NOTE: SHOULD PROBABLY BE SEPARATE IF's, NOT NESTED IF's.  FIX LATER.
	if (redraw) {
		// WARNING: There is no check to see if prevpnt hasn't been deleted (and therefore shouldn't be drawn!)
		if (prevpnt != SelectedPoint) {         // if selected point different
			redrawSpecPoints (new Array (newpnt, prevpnt), true);      // redraw affected markers    /* second parm??? */
			if (prevseg != SelectedSegment) {      // if selected segment different
				rte.redrawPolylines (true, true);                            // redraw polyline
			}
		}
	}

	// Update navigation buttons
	// debugger;
	setNavButtons (true);

	// Return previously selected point
	return (prevpnt);
}




/**********************************************************************
* Safely select new point.  Checks to see if there are any 
* errors in the data attached to the old point 
* (and if segment changes, to the segment).
* Inputs:
*   pnt - New point to select
*   situation - SIT_PNT_CLICK or SIT_PNT_NAV
***********************************************************************/


/**********************************************************************
* Safely select new segment.  Checks to see if there are any 
* errors in the data attached to the old segment. 
*   seg - New segment to select
*   situation - SIT_PNT_CLICK or SIT_PNT_NAV
***********************************************************************/






/******************************************************************************
******************************************************************************
// MODE PROCEDURES
******************************************************************************
******************************************************************************/

/*******************************************************************
* Enter Insert Before mode.  Called from button click.
********************************************************************/
function enterInsertBeforeMode () {
	// debugger;
	if (OpenRoute != null && SelectedPoint != null) {     // safety check
		CurrMode = MODE_INSERT_BEFORE;
		setModeText (CurrMode);
		/* var modelabel = document.getElementById ("modelabel");
		modelabel.innerHTML = "Insert before";
		var modekey = document.getElementById ("modekey");
		modekey.innerHTML = "<ul><li>To insert a new point BEFORE the selected point, click on the map." + 
			"<li>To select a route point, click on it." + 
			"<li>To move a route point, drag it.</ul>"; */
	}
}


/*******************************************************************
* Enter Insert After mode.  Called from button click.
********************************************************************/
function enterInsertAfterMode () {
	// debugger;
	if (OpenRoute != null && SelectedPoint != null) {     // safety check
		CurrMode = MODE_INSERT_AFTER;
		setModeText (CurrMode);
		/* var modelabel = document.getElementById ("modelabel");
		modelabel.innerHTML = "Insert after";
		var modekey = document.getElementById ("modekey");
		modekey.innerHTML = "<ul><li>To insert a new point AFTER the selected point, click on the map." + 
			"<li>To select a route point, click on it." + 
			"<li>To move a route point, drag it.</ul>";  */
	}
}

/*******************************************************************
* Enter Append mode (the default mode).  Called from button click.
********************************************************************/
function enterAppendMode () {
	if (OpenRoute != null) {     // safety check
		CurrMode = MODE_APPEND;
		setModeText (CurrMode);
		/* var modelabel = document.getElementById ("modelabel");
		modelabel.innerHTML = "Append point";
		var modekey = document.getElementById ("modekey");
		modekey.innerHTML = "<ul><li>To add a new point to the END of the route, click on the map." + 
			"<li>To select a route point, click on it." + 
			"<li>To move a route point, drag it.</ul>"; */
	}
}

/******************************************************************************/
// Enter view mode.  This is typically done after Finish Route or Delete Route operations.
// Called from other routines, not from buttons.  
// Careful -- it doesn't save or clean up any route data.
/*******************************************************************************/
function enterViewMode () {

	// Reset current route, etc.
	SelectedRoute = null;                    
	OpenRoute = null;
	SelectedPoint = null;
	SelectedSegment = null;
	
	// Return to view mode
	CurrMode = MODE_VIEW;
	setModeText (MODE_VIEW);
	setButtons_ViewMode();
	FldInfo.configFields_NoRoute();       // Disable and clear seg/pnt fields (as long as no route is selected)

}

/*******************************************************************
* Set mode label and text
********************************************************************/
function setModeText (mode) {
	var modelabel = document.getElementById ("modelabel");
	var modekey = document.getElementById ("modekey");

	switch (mode) {
		case MODE_NEW:
			modelabel.innerHTML = "Start new route";
			modekey.innerHTML = "<h3>Instructions:</h3>Click on the map to start plotting the new route.<br/>&nbsp;";
			break;
		case MODE_APPEND:
			modelabel.innerHTML = "Append point";
			modekey.innerHTML = "<h3>Instructions:</h3><ul><li>Click on the map to add a new point to the route.</li>" + 
				/* "<ul><li>To add a new point to the END of the route, click on the map." +  */
				"<li>To select a route point or segment, click on the point or segment.</li>" + 
				"<li>To move a route point, drag it.</li>" + 
				"<li>To start a new segment at the selected route point, click on the cut segment button.</li>" + 
				"<li>To finish the route, click on the 'Finish Route' button.</li>" + 
				"</ul></font>";
			break;
		case MODE_INSERT_BEFORE:
			modelabel.innerHTML = "Insert point before";
			modekey.innerHTML = "<h3>Instructions:</h3><ul><li>To insert a new point BEFORE the selected point, click on the map.</li>" + 
				"<li>To select a route point or segment, click on the point or segment.</li>" + 
				"<li>To move a route point, drag it.</li></ul></font>";
			break;
		case MODE_INSERT_AFTER:
			modelabel.innerHTML = "Insert point after";
			modekey.innerHTML = "<h3>Instructions:</h3><ul><li>To insert a new point AFTER the selected point, click on the map.</li>" + 
				"<li>To select a route point or segment, click on the point or segment.</li>" + 
				"<li>To move a route point, drag it.</li></ul></font>";			
			break;
		case MODE_VIEW:
			modelabel.innerHTML = "View routes";
			if (!HereYet) {
				modekey.innerHTML = "<font>Welcome! Not all features are turned on in this prototype.  " + 
				                    "To start, click on the 'New Route' button.</font>";
				HereYet = true;
			}
			else
				modekey.innerHTML = "<h3>Instructions:</h3>To start a new route, click on the 'New Route' button.";
				// modekey.innerHTML = "Click on the New Route button if you want to create a route.  Click on an existing route to select it.";
			break;
		default:
			break;
	}
}


