﻿var map = null;
var _isPrint = false;
var browser = navigator.appName;
var isIE = (browser == "Microsoft Internet Explorer");
var $get;
if(isIE)
    $get = document.getElementById;
else
    $get = function(id){return document.getElementById(id);}
var _DirectionObj = { 
    "StreetAddress":"",
    "Directions" : "",
    "StreetLatLong" : null,
    "Changed" : true,
    "Valid" : false,
    "LastHousePos" : null
    };

function SPWMapFunctions()
{
    this.map = null;
    this.Load = 
        function()
        {
            var point = new VELatLong(
                parseFloat(document.getElementById('vemap_lat').value),
                parseFloat(document.getElementById('vemap_lon').value)
                );
            map = new VEMap('vemap');
            map.LoadMap(point, 16);
            map.AddShape(new VEShape(VEShapeType.Pushpin, point));
        };
}
var SPW_Map = new SPWMapFunctions();

function HideMapPopUp()
{
    var popUpDiv = $get('Map_PopupDiv');
    if(popUpDiv){
        popUpDiv.style.display = 'none';
    }
}
function SetDirections(s)
{
    $get("divRections").innerHTML = s;
}
function GotClientPos(layer, results, places, hasMore, error)
{
    if(error != null){
        SetDirections(error);
        return;
    }
    SetDirections('');
    _DirectionObj.StreetLatLong = places[0].LatLong;
    _DirectionObj.Valid = true;
    GetDirections();
}

function GetDirections()
{
    var newAddress = $get('startAddress').value;
    _DirectionObj.Changed = _DirectionObj.StreetAddress != newAddress;
    if(_DirectionObj.Changed)
    {
        _DirectionObj.StreetAddress = newAddress;
        _DirectionObj.Changed = false;
        _DirectionObj.Valid = false;
        map.Find(null, _DirectionObj.StreetAddress + ", United States" , null, null, null, 1, false, false, false, false, GotClientPos)
    }
    if(!_DirectionObj.Valid) return;
    var locations = new Array();

    locations.push(new VELatLong(parseFloat(document.getElementById('vemap_lat').value),parseFloat(document.getElementById('vemap_lon').value)));
        
    
    if(locations.length < 1) return;
    if(locations.length > 1)
    {
        var templocations = new Array();
        _DirectionObj.LastHousePos = _DirectionObj.StreetLatLong;
        while(locations.length > 0)
        {
            locations.sort(DistanceSort);
            templocations.push(locations.pop());
            _DirectionObj.LastHousePos = templocations[templocations.length - 1];
        }
        locations = templocations;
    }
    locations.splice(0,0,_DirectionObj.StreetLatLong);
    var options = new VERouteOptions();
    options.DrawRoute = true;
    options.SetBestMapView = true;
    options.RouteCallback = DirectionsComplete;
    options.ShowDisambiguation = false;
    map.GetDirections(locations, options);
}
function DirectionsComplete(route)
{  
    var to_address = $get('vemap_addr').value;    
	var turns = "<h3>Directions</h3>\r\n"+((_DirectionObj.StreetAddress != null && _DirectionObj.StreetAddress.length >0)?"<p><b>Starting Address:</b> " + _DirectionObj.StreetAddress + "<br/>\r\n":"") + "<br/><b>Destination Address :</b> " + to_address + "<br/><br/>\r\n" + "<p><b>Total Distance:</b> " + route.Distance.toFixed(1) + " miles<br/>\r\n<b>Estimated Time (Total):</b> " + GetTime(route.Time) + "</p>";
	// Unroll route and populate DIV
	var legs          = route.RouteLegs;
	var leg           = null;
	var turnNum       = 0;  // The turn #
	var styles = new Array();
	styles[0] = 'background-color:#F7F5F6;';
	styles[1] = 'background-color:#EAEAEA;';
	// Get intermediate legs
	var address = $get('startAddress').value;
	
	for(var iLoopCnt = 0; iLoopCnt < legs.length; iLoopCnt++)
	{
		// Get this leg so we don't have to reference multiple times
		leg = legs[iLoopCnt];  // Leg is a VERouteLeg object
		var legNum = iLoopCnt + 1;
		address = "";
		// Unroll each intermediate leg
		var turn        = null;  // The itinerary leg
		var legDistance = null;  // The distance for this leg
		turns += "<table width='300' cellspacing='3' cellpadding='3' style='font-size:12px;border:1px solid #b5b5b5;'>";
		for(var j = 0; j < leg.Itinerary.Items.length; j ++)
		{
			turnNum++;
			// turn is a VERouteItineraryItem object
			turn = leg.Itinerary.Items[j];
			turns += "<tr><td style='" + styles[j % 2] + ((j != (leg.Itinerary.Items.length-1))? "border-bottom:1px solid #b5b5b5;":"") + "'>" + turn.Text;
			legDistance = turn.Distance;
			// So we don't show 0.0 for the arrival
			if(legDistance > 0)
			{
			    // Round distances to 1/10ths then // Append time if found
			    turns += " (" + legDistance.toFixed(1) + " miles" + (turn.Time != null? "; " + GetTime(turn.Time):"") + ")<br/>\r\n";
		    }
		    turns += "</td></tr>\r\n";
	    }
    	turns += "</table>\r\n";
    }
    _DirectionObj.Directions = turns;
    //new Code to popup print directions only after Directions are loaded.
    if(_isPrint)
        SendToPrintPage(_DirectionObj.Directions);
    _isPrint = false;
    // Populate DIV with directions
    SetDirections(turns);
    $get("print_button").style.visibility = 'visible';
}
function PrintMapDirections()
{
    _isPrint = true;
    GetDirections();
}
function SendToPrintPage(directions){
    var printWin = window.open("","PrintDirections","width=500, height=400, scrollbars=yes");
	printWin.document.open();	
    printWin.document.write('<html><head><title>Print Directions</title>');
    printWin.document.write('<style type="text/css">body{ font-family:Tahoma, sans-serif; color:black;font-size:12px;margin:0px;padding:0px; background-color:#f0f0f0; } input.button{font-size:11px;font-weight:bold;border:1px solid #b6b4b5;background-color:#ccc;}</style>');
    printWin.document.write('</head><body><div style="width:100%;" align="right"><input type="button" class="button" value="Print Directions" onclick="window.print();" />&nbsp;<input type="button" value="Close Window" class="button" onclick="window.close();" /></div>');
    printWin.document.write('<div style="margin-left:15px;">' + directions + '</p>');
    printWin.document.write('</body></html>');
	printWin.document.close();
	//printWin.print();
    HideMapPopUp();
}
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");
}