// JavaScript Document
	  var printpage = false;

      //flag to indicate whether the reverse directions are currently being displayed
      var reverseDirectionsDisplayed = false;
	  
	  var RouteStartIcon = "http://dev.virtualearth.net/mapcontrol/v6.1/i/bin/6.1.20080306152009.13/pins/mapicon_start.gif";
	  var RouteEndIcon  = "http://dev.virtualearth.net/mapcontrol/v6.1/i/bin/6.1.20080306152009.13/pins/mapicon_end.gif";
      var RouteWaypointIconPath = "http://dev.virtualearth.net/mapcontrol/v6.1/i/bin/6.1.20080306152009.13/pins/RedCircle";
	  function GetMap()
	  { 	
	  		FocusOnAddressInput();
			SetFormValues();
			map=new VEMap ('myMap');
			
            map.onLoadMap = DisableBirdseyeNotification;    
		
			map.LoadMap(restaurantLatLong, 14, VEMapStyle.Road );
			map.HideDashboard();
				
			var shape = new VEShape( VEShapeType.Pushpin, restaurantLatLong );
            shape.SetCustomIcon("../images/nav/Seasons52_32x32.PNG");
			map.AddShape(shape);
			
			
      }
	  
	  function SetFormValues()
	  {
		var addressFields = restaurantAddress.split(',');

   	    document.DDForm.daddr.value = addressFields[0];
		document.DDForm.dcity.value = addressFields[1];
		document.DDForm.dst.value = addressFields[2];
		document.DDForm.dzip.value = addressFields[3];
		document.DDForm.dLat.value = restaurantLatLong.Latitude;
		document.DDForm.dLon.value = restaurantLatLong.Longitude;
	  }
	  
	  function FocusOnAddressInput()
	  {
		document.getElementById("oad").focus();  
	  }
	  //This function disables the birdseye preview image that appears when birdseye becomes available
	  //NOTE:  This code is unsupported through the API, and might break with a future release of Virtual Earth
	  function DisableBirdseyeNotification()
	  {
		  document.getElementById("MSVE_obliqueNotifyBeak").style.display = "none";
		  document.getElementById("MSVE_obliqueNotifyContent").style.display = "none";
	  }
	  
	  function GetDrivingDirections(bReverse)
	  {
		  
		  var addressString = "";
			  addressString += document.getElementById("oad").value + ', ';
			  addressString += document.getElementById("ocity").value +', ';
			  addressString += document.getElementById("ost").value +',' ;
			  addressString += document.getElementById("opostalcode").value;
			  
		 var locations;
		 if ( bReverse )
		 {
			 locations = new Array( restaurantLatLong, addressString );
			 reverseDirectionsDisplayed = true;
		 }
		 else
		 {
			locations = new Array( addressString, restaurantLatLong );
			reverseDirectionsDisplayed = false;
		 }
		 
		 
		  var routeOptions = new VERouteOptions();
		  routeOptions.RouteCallback = PrintDrivingDirections;
		  map.GetDirections( locations, routeOptions );
	  }
	  
	  
	function findRestaurantCallback(layer, resultsArray, places, hasMore, veErrorMessage)
  	{  		  	
	  	try
	  	{
	  		restaurantLatLong = places[0].LatLong;
	  		
			if (places[0].Precision == VELocationPrecision.Rooftop)
			{
				isRoofTop = true;
			}	
			else
				isRoofTop = false;	
				
			var routeOptions = new VERouteOptions();
			routeOptions.RouteCallback = PrintDrivingDirections;
			
			map.GetDirections( [oAddress, restaurantLatLong], routeOptions );
			
	  	
  		}
  		catch(e){
	  		var exp = e;}
  	}
	  
	  //This function prints the driving directions on to the screen
	  function PrintDrivingDirections( route )
	  {
	        //var directionsInput = document.getElementById("directionsInput");
//		    directionsInput.style.display = "none";
//		    var directionsDiv = document.getElementById("drivingDirections");
//		    directionsDiv.style.display = "block";
//			var printLinks = document.getElementById("PrintLinks");
//		    printLinks.style.display = "block";
	  
	        var turns = "<span class='bodyCopyBold'><b>Turn-by-Turn Directions</b></span><br/>";
            turns += "<span class='bodyCopyBold'><b>Estimated Time:</b> " + GetTime(route.RouteLegs[0].Time) + "</span><br/>";
			turns += "<span class='bodyCopyBold'><b>Total Distance:</b>" + route.RouteLegs[0].Distance.toFixed(1) + " miles</span><br/>";
               
               // Unroll route and populate DIV
               var legs          = route.RouteLegs;
               var leg           = null;
               var turnNum       = 0;  // The turn #
             
			   // 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

                  var legNum = i + 1;
           
                  // Unroll each intermediate leg
                  var turn        = null;  // The itinerary leg
                  var legDistance = null;  // The distance for this leg
                 
				 
				 turns += "<table style='width:270px' ><tr><th class='bodyCopyBold'>No.</th><th class='bodyCopyBold'>Directions</th><th class='bodyCopyBold'>Distance</th></tr>";
                  for(var j = 0; j < leg.Itinerary.Items.length; j++)
                  {
                     turnNum++;
                     turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
                     
					 var linkText;
					 if ( j == 0 )
					 {
					    linkText = "Start";
						if ( reverseDirectionsDisplayed )
							turn.Shape.Hide();
					 }
					 else if ( j == leg.Itinerary.Items.length - 1 )
					 {
					 	linkText = "End";
						if ( !reverseDirectionsDisplayed )
							turn.Shape.Hide();
					 }
				     else
					 {
					    linkText = j;
					 }
					 
                     turns += "<tr><td class='bodyCopy' style='width:6%'>" + GenerateDirectionHyperlink(linkText, turn.Shape) + "</td>";

					if ( i == (legs.length -1) && j == (leg.Itinerary.Items.length -1))
						turns += "<td class='bodyCopy' id='LastStep' style='width:69%;text-align:left'>" + turn.Text + "</td>";
					else
						turns += "<td class='bodyCopy'  style='width:69%;text-align:left'>" + turn.Text + "</td>";
						
                     legDistance = turn.Distance;
					 
					 // So we don't show 0.0 for the arrival
                     if(legDistance > 0)
                     {
                        turns += "<td class='bodyCopy' style='width:25%;text-align:left'>" + legDistance.toFixed(1) + " miles</td></tr>";
                     }
					 else
					 {
					     turns += "<td style='width:25%'></td>";
					 }
                  }
                  turns += "</table><br/>";
                  
				}
			
				var directionsDiv = document.getElementById("drivingDirections");
				directionsDiv.innerHTML = turns ;
			  
				var routeItems = legs[0].Itinerary.Items;
				lastItem = routeItems[routeItems.length - 1].LatLong;
				secondLastItem = routeItems[routeItems.length - 2].LatLong;
				
				var lastStepString = routeItems[routeItems.length - 1].Text;
				if (lastStepString.match("left") == null && lastStepString.match("right") == null)
				{
					if (isRoofTop)
					{
						var reg = new RegExp(/^(?:[a-zA-Z\s]*)(\d{1,8})([\w\s,\.]+)$/);
				        var m = dAddress.match(reg);
				        if(m.length>2)
						{
					        var streetAddress = m[2];
							map.Find(null,streetAddress, null, null, null, null, false, null, false, false, findStreetCallback);
				        }	
					
					}
				}
      }
	  
	function findStreetCallback(layer, resultsArray, places, hasMore, veErrorMessage)
  	{
	  	try
	  	{
		  	streetLatLong = places[0].LatLong;
			
			var bearing = streetOffset(lastItem, streetLatLong);
			
			var lastStep = document.getElementById("LastStep");
			
			if ((bearing > 225 && bearing <= 315) || (bearing > 45 && bearing < 135))  //EW
			{	
				if (restaurantLatLong.Latitude > lastItem.Latitude)
				{
					if (lastItem.Longitude > secondLastItem.Longitude)
						lastStep.innerHTML = "Arrive on the left";
					else
						lastStep.innerHTML = "Arrive on the right";
				}
				else
				{
					if (lastItem.Longitude > secondLastItem.Longitude)
						lastStep.innerHTML = "Arrive on the right";
					else
						lastStep.innerHTML = "Arrive on the left";
				}
			}
			else
			{
				if (restaurantLatLong.Longitude > lastItem.Longitude)
				{
					if (lastItem.Latitude > secondLastItem.Latitude)
						lastStep.innerHTML = "Arrive on the right";
					else
						lastStep.innerHTML = "Arrive on the left";
				}
				else
				{
					if (lastItem.Latitude > secondLastItem.Latitude)
						lastStep.innerHTML = "Arrive on the left";
					else
						lastStep.innerHTML = "Arrive on the right";
				}
			}
	    	
		}catch(e){} 	 	
  	}
	
	function streetOffset(house, street)
	{    
	     //distinguish if road runs NS or EW
	     if(Math.abs(house.Latitude-street.Latitude)>Math.abs(house.Longitude-street.Longitude))
	     {
		     if((house.Latitude-street.Latitude)<0)
		     	bearing = calculateBearing(street, house);
		     else
		     	bearing = calculateBearing(house, street);
	     }
	     else
	     {
		     if((house.Longitude-street.Longitude)<0)
		     	bearing = calculateBearing(street, house);
		     else
		     	bearing = calculateBearing(house, street);
	     }
	     
		 return bearing;
		  
     }

	function calculateBearing(A,B)
	{
		var lat1 = DegtoRad(A.Latitude);
		var lon1 = A.Longitude;
		var lat2 = DegtoRad(B.Latitude);
		var lon2 = B.Longitude;
				
		var dLon = DegtoRad(lon2-lon1);
				
		var y = Math.sin(dLon) * Math.cos(lat2);
		var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
	
		var brng = (RadtoDeg(Math.atan2(y, x))+360)%360;
				
		return brng;
	}

	function DegtoRad(x)
	{
		return x*Math.PI/180;
	}
	
	function RadtoDeg(x)
	{
		return x*180/Math.PI;
	}
	  
	  function ShowDirectionsInput()
	  {
     	//  var directionsDiv = document.getElementById("drivingDirections");
//		  directionsDiv.style.display = "none";
//		  
//		  var directionsInput = document.getElementById("directionsInput");
//		  directionsInput.style.display = "block";
//		  
//		  var printLinks = document.getElementById("PrintLinks");
//		  printLinks.style.display = "none;"
	  }
	  
	  function GenerateDirectionHyperlink(turnNum, shape)
	  {
          var turnLink = "<a href='#' ";
          //Make sure that we've received a Pushpin, and not a polygon or polyline
		  if ( shape.GetType() == VEShapeType.Pushpin)
		  {
			  turnLink += "onclick='map.SetCenterAndZoom(";
              turnLink += "new VELatLong(" + shape.GetPoints()[0].Latitude + "," + shape.GetPoints()[0].Longitude + "),17);'";																	
		  }
		  
		  turnLink += ">" + turnNum + "</a>";
		  
		  return turnLink;
	  }
	  

	  
	 function GetTime(time)
	 {
		if(time == null)
		{
		   return("");
		}

		if(time > 60)
		{                                 // if time == 100
		   var seconds = time % 60;       // seconds == 40
		   var minutes = time - seconds;  // minutes == 60
		   minutes     = minutes / 60;    // minutes == 1


		   if(minutes > 60)
		   {                                     // if minutes == 100
			  var minLeft = minutes % 60;        // minLeft    == 40
			  var hours   = minutes - minLeft;   // hours      == 60
			  hours       = hours / 60;          // hours      == 1

			  return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
		   }
		   else
		   {
			  return(minutes + " minutes, " + seconds + " seconds");
		   }
		}
		else
		{
		   return(time + " seconds");
		}
	 }
		 
	 function PrintDirectionsToWindow()
	 {
		var querystring = "?dLat="; 
		 
		querystring += restaurantLatLong.Latitude;
		querystring += "&dLon=" + restaurantLatLong.Longitude;
		querystring += "&oad=" + document.getElementById("oad").value;
		querystring += "&ocity=" + document.getElementById("ocity").value;
		querystring += "&ost=" + document.getElementById("ost").value;
		querystring += "&ozip=" + document.getElementById("opostalcode").value;
		querystring += "&dAddress=" + restaurantAddress;
		querystring += "&rev=" + reverseDirectionsDisplayed;
		
		var url = "PrintDirections.asp";
		
		var printWindow = window.open( url + querystring, "Print", "scrollbars=1" );
		printWindow.focus();
	}

	  
	