/*
Betson Thomas
NOTE [11/11/07]: At the time of creation, the main entrance's road structure had been slightly changed and this was yet to be reflected on road data
available online.  So, I could not accurately  lead them to the parking garage via the map's route function.  Instead, I opted to direct them to
the main entrance using the in-built route function and then manually add the line structure leading to the parking garage.
*/

 var map = null;	//map object
 var start;	//the starting location/address
 var destLoc;	//the destination location
 var walkDir = null;	//fcn pointer for text directions
 var lineWalkDir = null;	//object for line drawn directions
 
 //draw layers for this scope
 var intPtsLayer = new VEShapeLayer();
 
 //toggles
 var opttype = VERouteOptimize.Default;	//route optimization type
 var pinExist = false;	//if interest points have been marked
 var ccPin = false;	//if the career center has been marked 
 var lastPin = null;	//used during test purposes to locate points on the map and retrieve lat/lon coords
 var genlirr = false;	//determines if the lirr schedule should be shown for general lirr trains to SB
 var lirrbus = false;	//toggle to determine if the bus route and walking directions are shown from the train station
 var dirState = "";		//stores the inner html from the directions form before resetting it to retrieve the actual directions

 /**
 Loads the initial map view.
 */
 function GetMap()
 {
	//if javascript is enabled this will cause the message to be removed
	remjsmsg();
	
	//fix for firefox 2
	var ffv = 0;
	var ffn = "Firefox/"
	var ffp = navigator.userAgent.indexOf(ffn);
	
	if (ffp != -1) 
		ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
		
	if (ffv >= 1.5) { // If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
		Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b); }
	}
	
	map = new VEMap('myMap');
	map.LoadMap(campusCenterLoc, 15, VEMapStyle.Hybrid);
	map.AddShapeLayer(driveDirLayer);
	map.AddShapeLayer(walkDirLayer);
	map.AddShapeLayer(intPtsLayer);
	
	var sacLotShape = new VEShape(VEShapeType.Polygon, [new VELatLong(40.91404160607222, -73.12852576375007),
				new VELatLong(40.91464360051495, -73.12839701771737),
				new VELatLong(40.91445509779411, -73.12664821743966),
				new VELatLong(40.913863236295725, -73.12675014138222)]);
				
	sacLotShape.SetFillColor(new VEColor(80, 255, 80, 0.5));
	sacLotShape.SetTitle("The SAC Parking Lot");
	sacLotShape.SetDescription("Designated Parking for Orientation.");
	map.AddShape(sacLotShape);
 }
 
 function GetCustomMap()
 { 	 	
	storeForm();
	
	//have to check for this here directly from the form because on refresh
	//the checkbox will maintain the checked value, but the variable is reset to false
	lirrbus = document.dirForm.lirrbus.checked;   
	
	var locations;
	if((document.dirForm.startLoc.value === "") &&
		(document.dirForm.startLoc2.selectedIndex == 0))
	{
		alert("Enter a starting address or select a starting location.");
	}
	else if((document.dirForm.startLoc.value !== "") &&
		(document.dirForm.startLoc2.selectedIndex != 0))
	{
		alert("Please either fill in an address OR select a starting location.  Do not enter values for both.");
	}
	else{
		//get optional pre-config start loc
		var precStart = document.dirForm.startLoc2.options[document.dirForm.startLoc2.selectedIndex].value;
		//alert(precStart);
		setPointers();
	
		genlirr = false;	//need to reset this value otherwise if we do multiple calls on the same page, it will retain its old value
	        start = document.dirForm.startLoc.value;
	        if(start == ""){	        
	        	start = convertStartLoc(precStart);	  
				//alert(start);
	        	if(start == "lirr"){
	        		setPointersTrain();					
				deleteRoute();
				driveDirLayer.DeleteAllShapes();	        	        
				walkDirLayer.DeleteAllShapes();
				//call line and directions functions directly
				showTurnsTrain();
				if(lirrbus){
					drawPath(lineRRBusTrainToSacLoop);
				}
					
				drawPath(lineWalkDir);
	        		return;
	        	}	
	        }
	        
		locations = new Array(start, mainEntrance);	
		var options = getOptions();
		
		//var gnd = "<br /> <input id=\"customRoute\" type=\"button\" onclick=\"viewForm();\" value=\"Reset\" />";
		SetDirections("<h3>Calculating Route...</h3><br />"/*+gnd*/);
		
		driveDirLayer.DeleteAllShapes();
		walkDirLayer.DeleteAllShapes();
		deleteRoute();
	        map.GetDirections(locations, options);
	}
 } 
 
 function getOptions(){
	var options = new VERouteOptions;
	options.DrawRoute      = true;	// Otherwise what's the point	
	options.SetBestMapView = true;	// So the map doesn't change:
	options.RouteCallback  = ShowTurns;	// Call this function when map route is determined:
	options.DistanceUnit   = VERouteDistanceUnit.Mile;	// Show as miles
	options.ShowDisambiguation = true;	// Show the disambiguation dialog
	
	toggleOptType();
	//alert("opttype: "+opttype);
	options.RouteOptimize = opttype; 
	
	return options;
}
 
 function setPointersTrain(){
	if(!lirrbus){
		lineWalkDir = lineTrainToSac;
		walkDir = dirTrainToSac;
	}else{
		lineWalkDir = lineSacLoopToSac;
		walkDir = dirSacLoopToSac;
	}
 }
 
 function setPointers(){
	//get destination location
	destLoc = "sac";
	lineWalkDir = lineSacParkToSac;
	walkDir = dirSacParkToSac;
 }

 function showTurnsTrain(){ 	
 	var turnNum = 0;
 	//function pointer, look at GetCustomMap() to see how its set
	var turns = "<p>";
	if(genlirr){
	  	//turnNum++;
	  	turns += "<h3>Train Directions</h3><br /><b>1.</b>\t"+"Take the Long Island Railroad's Port Jefferson line to Stony Brook station. ";
	  	turns += "<a href=\"http://www.mta.nyc.ny.us/lirr/Timetable/Branch.htm?Folder=Branch&Branch=Port%20Jefferson&Direction=East&Period=Weekdays\"><strong>View Schedule</strong></a> or <a href=\"http://lirr42.mta.info/index.asp\"><strong>Use this Form</strong></a>.<br /><br />";
	}
	
	if(lirrbus){
		turns += dirRRBusTrainToSacLoop(turnNum);
	}
	
	turns += walkDir(turnNum)+"</p>";
	
	var gnd = "<br /> <input id=\"customRoute\" type=\"button\" onclick=\"viewForm();\" value=\"Get New Directions\" /><br /><br />";
	turns = "<strong>Start:</strong> "+startToStr(start) + "<br /><strong>End:</strong> " +endToStr(destLoc) + gnd + turns;
	
	//turns += "<a href=\"\" onclick=\"return mapPan(40, -73);\">Pan to Career Center</a>";
   // Populate DIV with directions
   SetDirections(turns);
   DoCenterZoom(lirrZoomLoc, 15);
 }
 
 function ShowTurns(route)
 {	
   // Unroll route and populate DIV
   var legs          = route.RouteLegs;
   var turns         = "<h3>Driving Directions</h3><p>";
   var leg           = null;
   var turnNum       = 0;  // The turn #
   var totalDistance = 0;  // The sum of all leg distances
   
   // Get intermediate legs
   for(var i = 0; i < legs.length; i++)
   {
	  // Get this leg so we don't have to derefernce multiple times
	  leg = legs[i];  // Leg is a VERouteLeg object
	  
	  // Unroll each intermediate leg
	  var turn        = null;  // The itinerary leg
	  var legDistance = null;  // The distance for this leg
	  	  
	  //NOTE
	  //j will be terminated one before the final step so that
	  //i can add in custom directions to the parking garage
	  for(var j = 0; j < leg.Itinerary.Items.length-1; j ++)
	  {
		 turnNum++;
	  	
		 turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
		 
		 /*
		 turns += "<input size=3 id=\""+turnNum+"\" type=\"button\" value=\""+turnNum+"\" onclick=\"mapPan("+
		 			turn.LatLong.Latitude+","+turn.LatLong.Longitude+");\">" + turn.Text;
		*/
		 
		 turns += "<b>"+turnNum+".</b>\t" + turn.Text;
		 
		 legDistance    = turn.Distance;
		 totalDistance += legDistance;
		//	alert("legdist: "+legDistance+" totdist: "+totalDistance);
		 // Round distances to 1/10ths
		 
		 //if its the last turn, indicate that they are using the main entrance
		 if( j == (leg.Itinerary.Items.length-2) )
			turns += " via the Main Entrance";
		 turns += " (" + legDistance.toFixed(1) + " miles)<br/>";
	  }
   }
	
	
   turns += turnStr(++turnNum)+'Make a right at the light.<br />';
   turns += turnStr(++turnNum)+'Make your first left onto John S. Toll Dr. You will pass the Union, Melville library and the \
   Sports Complex. After you round the bend, go past the first Faculty/Staff lot (its a woody area) and you will see a much \
   larger and open Faculty/Staff lot on your left. (0.6 miles)<br />';
   turns += '<em>If you reach Campus Dr, you\'ve gone too far</em><br />';
   turns += turnStr(++turnNum)+'Make a left into the SAC Lot.<br />';

   turns += "<strong>Total travel distance: </strong>" + totalDistance.toFixed(1) + " miles (approximately)<br />";

   //function pointer, look at GetCustomMap() to see how its set
   turns += walkDir(turnNum)+"</p>";
		
   var gnd = "<br /> <input id=\"customRoute\" type=\"button\" onclick=\"viewForm();\" value=\"Get New Directions\" /><br /><br />";
   turns = "<strong>Start:</strong> "+startToStr(start) + "<br /><strong>End:</strong> " +endToStr(destLoc) + gnd + turns;
   //turns += "<a href=\"\" onclick=\"return mapPan(40, -73);\">Pan to Career Center</a>";
   // Populate DIV with directions
   SetDirections(turns);
   displayCustomDir();
 } 
 
 function SetDirections(s)
 {
    var d = document.getElementById("directions");
    d.innerHTML = s;
 }
 
 function displayBusOption(){
	var d = document.getElementById("lirrbus");
	var s = "<input type=\"checkbox\" name=\"lirrbus\" id=\"lirrbus\" \
				onClick=\"toggleLirrBus();\"/>I want to take the bus from the LIRR station.";
    d.innerHTML = s;
 }

 function toggleLirrBus(){
	lirrbus = !lirrbus;
 }

 function evalActiveOpt(){ 
	//if there is text in the text box
		//enable both checkboxes, bc they can type in lirr stony brook into text box
	//if there is no text
		//determine the index of the select box
	if(document.dirForm.startLoc.value !== ""){
		enableLirrBusOption();		
		enableRouteOpt();	//could be typing in a full address
	}else{
		checkTrain();
	}
 }

 function checkTrain(){
	var index = document.dirForm.startLoc2.selectedIndex;
	if((index == 1) || (index == 2)){
		enableLirrBusOption();
		disableRouteOpt();
	}
	else{
		disableLirrBusOption();
		enableRouteOpt();
	}
}

 function checkEnter(e){ //e is event object passed from function invocation
	var characterCode;// literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		GetCustomMap();
		return false 
	}
}

/**
toggle the optimization type variable
*/
function toggleOptType(){
	for(var i = 0; i < document.dirForm.opttype.length; i++){
		if(document.dirForm.opttype[i].checked){
			if(i == 0)
				opttype = VERouteOptimize.Default;
			else if(i == 1)
				opttype = VERouteOptimize.MinimizeDistance;
			else if(i == 2)
				opttype = VERouteOptimize.MinimizeTime;
			else
				alert("need to add values to toggleopptype code. unknown index for opttype.");
		}
	}
	//alert("opttype: "+opttype);
}
