var BingMap = null;
var BingID = "AiJYFl0BGIFMlaiBwxHBm8Q3kk1kQELwzaIryN3zl8y1UM6mpw-zCKzEPp1dwq19";
var BingLocation = "Largo da Alfândega, 4050 Porto (Porto), Portugal";
var BingWidth = 450;
var BingHeight = 400;
var BingZoomLevel = 14;
var BingStyle = VEMapStyle.Road;
var BingDashboard = VEDashboardSize.Normal;
var BingDistanceUnits = VEDistanceUnit.Kilometers;
var BingShowTraffic = true;
var BingShowDirections = true;
var BingShowTurnByTurn = true;
var BingRouteDistanceUnits = (BingDistanceUnits==VEDistanceUnit.Miles)?VERouteDistanceUnit.Mile:VERouteDistanceUnit.Kilometer;
var BingRouteOptimize = VERouteOptimize.MinimizeDistance;

function GetMap()
{
	if (!document.getElementById('BingMapResult'))
		return;
		
	if (!BingMap)
	{
		BingMap = new VEMap('BingMapResult');
		BingMap.SetCredentials(BingID);
		BingMap.SetDashboardSize(BingDashboard);
	}
	if (document.getElementById('BingLocation'))
		document.getElementById('BingLocation').innerHTML = BingLocation;
	BingMap.LoadMap();
	StartGeocoding(BingLocation);
}

function GetLatLong(e)
{
	//Get the pixel coordinates from the click event, convert to LatLong value
	var x = e.mapX;
	var y = e.mapY;
	pixel = new VEPixel(x, y);
	latLong = BingMap.PixelToLatLong(pixel);
	document.getElementById('addressfrom').value = latLong;
}

function ZoomIn()
{
	//Increase zoom level by a factor of 1
	BingMap.ZoomIn();
	document.getElementById('txtZoom').value = BingMap.GetZoomLevel();
}

function ZoomOut()
{
	//Decrease zoom level by a factor of 1
	BingMap.ZoomOut();
	document.getElementById('txtZoom').value = BingMap.GetZoomLevel();
}
 
function StartGeocoding( address )
{
   BingMap.Find(null,    // what
						address, // where
						null,    // VEFindType (always VEFindType.Businesses)
						null,    // VEShapeLayer (base by default)
						null,    // start index for results (0 by default)
						null,    // max number of results (default is 10)
						null,    // show results? (default is true)
						null,    // create pushpin for what results? (ignored since what is null)
						null,    // use default disambiguation? (default is true)
						null,    // set best map view? (default is true)
						GeocodeCallback);  // call back function
}

function GeocodeCallback (shapeLayer, findResults, places, moreResults, errorMsg)
{
	 // if there are no results, display any error message and return
	 if(places == null)
	 {
			alert( (errorMsg == null) ? "There were no results" : errorMsg );
			return;
	 }

	 var bestPlace = places[0];
	 
	 // Add pushpin to the *best* place
	 var location = bestPlace.LatLong;
	 
	 var newShape = new VEShape(VEShapeType.Pushpin, location);
	 
	 var desc = "Latitude: " + location.Latitude + "<br>Longitude:" + location.Longitude;
	 newShape.SetDescription(desc);
	 newShape.SetTitle(bestPlace.Name);
	 BingMap.AddShape(newShape);
	 BingMap.SetMapStyle(BingStyle);
	 BingMap.SetZoomLevel(BingZoomLevel); 
   BingMap.SetScaleBarDistanceUnit(BingDistanceUnits);		 	 
	 BingMap.Resize(BingWidth, BingHeight);
	 if (BingShowTraffic)
		 ShowTraffic();
}				

function ShowTraffic()
{
	BingMap.LoadTraffic(true);
	BingMap.ShowTrafficLegend();
}
				 
function DrivingDirections(startAddress)
{
	var locations;

	locations = new Array(startAddress, BingLocation);

	var options = new VERouteOptions;

	options.DrawRoute = true;

	options.SetBestMapView = true;

	if (BingShowTurnByTurn)
		options.RouteCallback  = ShowTurns;

  options.DistanceUnit = BingRouteDistanceUnits;

	options.ShowDisambiguation = false;

	options.RouteOptimize = BingRouteOptimize;	

	options.UseTraffic   = true;
	
	BingMap.GetDirections(locations, options);
}

function ShowTurns(route)
{
	var units = (BingRouteDistanceUnits==VERouteDistanceUnit.Mile)?"miles":"kilometers";

	var turns = "<h3>Turn-by-Turn Directions</h3>";

	turns += "<p id=\"totaldistance\"><strong>Total Distance:</strong> " + route.Distance.toFixed(1) + " "+units+"</p>";

	turns += "<p id=\"totaltime\"><strong>Total Time:</strong> " + GetTime(route.Time) + "</p>";

	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
	
		turns += "<ol>";
		// Unroll each intermediate leg
		var turn        = null;  // The itinerary leg
		var legDistance = null;  // The distance for this leg
		
		for(var j = 0; j < leg.Itinerary.Items.length; j ++)
		{
			 turnNum++;
			 
			 turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
	
			 turns += "<li>" + turn.Text;
	
			 legDistance    = turn.Distance;
	
			 // So we don't show 0.0 for the arrival
			 if(legDistance > 0)
			 {
					// Round distances to 1/10ths
					turns += " (" + legDistance.toFixed(1) + " " + units;
	
					// Append time if found
					if(turn.Time != null)
					{
						 turns += "; " + GetTime(turn.Time);
					}
	
					turns += ")";
			 }
			 turns += "</li>";
		}
	
		turns += "</ol>";
	}
	
	if (document.getElementById("BingDirections"))
	 document.getElementById("BingDirections").innerHTML = turns;
}
				 
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 ClearAll()
{
	BingMap.DeleteRoute();
	if (document.getElementById("BingDirections"))
		document.getElementById("BingDirections").innerHTML = "";
	GetMap();
}
