// JavaScript Document

	var oAddress;
	var dAddress;
	var isRoofTop = false;
	var lastItem;
	var secondLastItem;
	var restaurantLatLong;
    var streetLatLong;
	
	function DisableBirdseyePopup()
	{
		document.getElementById("MSVE_obliqueNotifyBeak").style.display = "none";
   	    document.getElementById("MSVE_obliqueNotifyContent").style.display = "none";
	}
	
	function GetDrivingDirections( bReverse, lat, lon )
	{
		var oStreet = document.getElementById("street").value;
		var oCity = document.getElementById("city").value;
		var oState = document.getElementById("state").value;
		var oZip = document.getElementById("zip").value;
		
		var dStreet = document.getElementById("dstreet").value;
		var dCity = document.getElementById("dcity").value;
		var dState = document.getElementById("dstate").value;
		var dZip = document.getElementById("dzip").value;
		
		var locations = null;
		if ( bReverse == false )
		{
			oAddress = GetAddressString( oStreet, oCity, oState, oZip );
			dAddress = GetAddressString( dStreet, dCity, dState, dZip );
		}
		else
		{
			oAddress = GetAddressString( dStreet, dCity, dState, dZip );
			dAddress = GetAddressString( oStreet, oCity, oState, oZip );
		}
		
		map.Find(null,dAddress, null, null, null, null, null, null, false, false, findRestaurantCallback);
	}
	
	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;}
  	}
	
	function PrintDrivingDirections( route )
	{
		var legs = route.RouteLegs;           
		var numTurns = 0;
		var leg = null;
		
		var directionsDiv = document.getElementById("drivingDirections");
		directionsDiv.innerHTML = "<h2>Door-to-Door Directions</h2>";
		
        var table =	document.createElement("table");
		table.setAttribute("id", "directions");
		table.setAttribute("class", "DirectionsTable");
		var tbody = document.createElement("tbody");
		
		var titleRow = document.createElement("tr");
		var routeCell = document.createElement("th");
		routeCell.setAttribute("class", "DirectionsTableInstructionHeader");
		//routeCell.setAttribute("style", "width:80%;line-height:16px;");
		routeCell.innerHTML = "<strong>ROUTE</strong>"
		var distCell = document.createElement("th");
		distCell.setAttribute("class", "DirectionsTableDistanceHeader");
		//distCell.setAttribute("style", "width:20%;line-height:16px;");
		distCell.innerHTML = "<strong>DISTANCE</strong>";
		
		titleRow.appendChild( routeCell );
		titleRow.appendChild( distCell );
		tbody.appendChild( titleRow );
		
		// Get intermediate legs
		for(var i = 0; i < legs.length; i++)
		{
			// Get this leg so we don't have to dereference multiple times               
			leg = legs[i];  // Leg is a VERouteLeg object                                 
			
			// Unroll each intermediate leg               
			var turn = null;  // The itinerary step                                 
			
			for(var j = 0; j < leg.Itinerary.Items.length; j ++)               
			{                  
			   turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object 
			   
			   var row = document.createElement("tr")
			   var instructionCell = document.createElement("td")
			   
			   if ( i == (legs.length -1) && j == (leg.Itinerary.Items.length -1))
					instructionCell.id = "LastStep";
			   
			   if ( numTurns % 2 == 1 )
			      instructionCell.setAttribute("class", "DirectionsTableInstructionCellAlt");
			   else
     		      instructionCell.setAttribute("class", "DirectionsTableInstructionCell");
               
			   if (j > 0)
			   instructionCell.innerHTML = j + '. ' + turn.Text;
			   else
			   instructionCell.innerHTML = turn.Text;
			   
			   row.appendChild( instructionCell );
			   
			   var distanceCell = document.createElement("td");
			   
			   if ( numTurns % 2 == 1 )
			      distanceCell.setAttribute("class", "DirectionsTableDistanceCellAlt");
			   else
			      distanceCell.setAttribute("class", "DirectionsTableDistanceCell");
				  
			   distanceCell.innerHTML = turn.Distance.toFixed(1) + "mi";
			   row.appendChild( distanceCell );
			                   
			   numTurns++;                  
			   tbody.appendChild( row );
			}            
		}            
        table.appendChild(tbody);
		
		//Fix for IE
		if (table.outerHTML )
		    directionsDiv.innerHTML = table.outerHTML
		//Non Microsoft Browsers
		else
		  	directionsDiv.appendChild( table );
			
		var timeDistance = document.getElementById("TimeDistance");
		timeDistance.style.display = "block";
		var estimatedTime = "Estimated Time: " + FormatTime( route.Time );
		var totalDistance = "Total Distance: " + route.Distance.toFixed(2) + " miles";
		var timeDistanceString = "" + estimatedTime + "<br />" + totalDistance;
        timeDistance.innerHTML = timeDistanceString;
		
		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 FormatTime( time )
	{
	       var timeString = "";

           var hours = parseInt(time / 3600);
           time = time -  (hours*3600);

           var minutes = parseInt( time / 60 );
           var seconds = time % 60;

           if ( hours > 0 )
              timeString += hours + " h ";
           if ( minutes > 0 )
              timeString += minutes + " m ";
           if ( seconds > 0 )
              timeString += seconds + " s";

           return timeString; 
	}
	
	function GetAddressString(a, c, s, z )
	{
		return a+ "," + c +"," + s + "," +z;
	}
	
	function doPrint()
	{
	    //Enable printing
		var printOpt = new VEPrintOptions(true);
		map.SetPrintOptions(printOpt);
		// Print the map 
		window.print();
	}