﻿/// <reference path="~/VOMaps.aspx" />

var LLlat = null;
var LLlon = null;
var LLaddress = null;
var MAddress = new Array();
var gAddress = null;
var gCity = null;
var gState = null;
var gZip = null;

//the drive function that calls initializes and calls GetDirections
function Drive() {
	var endAddress = "";
	var startAddress = "";
	var startValue = "";
	var endValue = "";
	MAddress = "";
	
	try {
		var options = new VERouteOptions;
		options.DrawRoute = true;
		// Show as miles
		options.DistanceUnit = VERouteDistanceUnit.Mile;
		options.SetBestMapView = true;
		options.RouteOptimize = VERouteOptimize.MinimizeDistance;
		options.RouteCallback = ShowTurns;
		
		//Value is index|Lat,Lon
		/* check for a lat & lon, if found, parse & use instead of the address ( which is probably useless because the data available in listingInfo object is not enough for a fully qualified address (i.e. no state) )*/
		startValue = getComboBoxValue(StartComboBox);
		MAddress = getComboBoxText(StartComboBox);
		endAddress = getComboBoxText(EndComboBox);

		if (trim(MAddress) == trim(endAddress)) {
		    alert("Please select a Start and End Address.\n Start & End Address must be different.");
		    return false;
		}
		if ((startValue.indexOf("|") > -1) && (!startValue == "")){
			var myStartLatLonArr = startValue.split("|")[1].split(",");
			startAddress = new VELatLong(myStartLatLonArr[0], myStartLatLonArr[1]);
			getGeoAddr(myStartLatLonArr[0], myStartLatLonArr[1]);
		} else {
			startAddress = getComboBoxText(StartComboBox);
			//call setcookie here
			_setCookie("HCScript=StartAddr", startAddress, Date() + 31);
		}

		var endValue = getComboBoxValue(EndComboBox);
		if ((endValue.indexOf("|") > -1) && (!endValue == "")){
			var myEndLatLonArr = endValue.split("|")[1].split(",");
			endAddress = new VELatLong(myEndLatLonArr[0], myEndLatLonArr[1]);
		}else{
			endAddress = getComboBoxText(EndComboBox);
			//call setcookie here
			_setCookie("HCScript=EndAddr", endAddress, Date() + 31);

		}

		map.GetDirections([startAddress, endAddress], options);
		$("results").style.visibility = "visible";
		$("results").style.display = '';
		$("results").style.width = "235px";
	} catch(ex) {alert(ex); handleE(ex, "Drive()")}
}//End Drive Function

function ShowTurns(route) {
// Unroll route and populate alert text
   var legs          = route.RouteLegs;
   var leg           = null;
   var turnNum       = 0;  // The turn #
   var totalDistance = 0;  // The sum of all leg distances
   //added <center> ghetto resolution
   var saddr = getComboBoxItem(StartComboBox);
   if (saddr == ""){saddr = getComboBoxText(StartComboBox);}
   
   var eaddr = getComboBoxItem(EndComboBox);
   if (eaddr == ""){eaddr = getComboBoxText(EndComboBox);}

   var turns = '<table id="pdir" class="MapFont" style="text-align:left;"><tr class="MapFont"><td><b>Start Address: ' + '</b>' + saddr + '</td></tr><tr class="MapFont"><td><b>End Address: ' + '</b>' + eaddr + '</td></tr><tr><td style="text-align:left;font-family: Arial; font-size: small; height: 20px; vertical-align: middle;"><b>TURN-BY-TURN DIRECTIONS</b></td></tr>';

	try{
		 // 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

				for(var j = 0; j < leg.Itinerary.Items.length; j ++){
					 turnNum++;
					// turn is a VERouteItineraryItem object
					turn = leg.Itinerary.Items[j];
					turns += '<tr><td class="MapFont"><b>' + turnNum + '</b>:  ' + turn.Text;
					legDistance    = turn.Distance;
					totalDistance += legDistance;

					// Round distances to 1/10ths
					// Note that miles is the default
					turns += ' (' + '<b>' + legDistance.toFixed(1) + ' miles</b>' + ') ' + '</td></tr>';
				}
		}
		turns += '<tr><td class="MapFont"><b>Approximate distance:  </b>' + totalDistance.toFixed(1) + ' miles</td></tr>';
		turns += '<tr><td class="MapFont"><b>Approximate Time:</b> ' + GetTime(route.Time) + "" + '</td></tr></table>';
		$("printwin").style.display='';
			
} catch(ex) {
	handleE(ex, "ShowTurns");
}
	// Populate DIV with directions
	$('results').innerHTML = turns;
}

// time is an integer representing seconds
// returns a formatted string
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");}
}

//Send LAT/LON and do reverse lookup to get Address
function getGeoAddr(GLat, GLon) {
    var url = "GetMapAddr.aspx?GLat=" + GLat + "&GLon=" + GLon;
    var address = "";
    var params = "GLat=" + GLat + "GLon=" + GLon;
    new Ajax.Request(url, { method: 'get', onSuccess: function(transport) {
        var JSONObject = eval("(" + transport.responseText + ")");
        address = JSONObject.address
        gCity = address.placename;
        gState = address.adminCode1;
        if (gState.length > 2) { gState = gState.substring(0, 2); }
        gZip = address.postalcode;
        gAddress = address.streetNumber + " " + address.street;
        buildGasStationLink(GLat, GLon, MAddress, gCity, gState, gZip);
    }
    });
}

//Build GasStation Link
function buildGasStationLink(GLat, GLon, MAddress, city, state, zip) {
    $("gaslink").style.display = '';
    var httptst = "http://gasprices.mapquest.com/searchresults.jsp?";
    glink = httptst + "search=true&hdLatitude=" + escape(GLat) + "&longitude=" + escape(GLon) + "&gasPriceType=3%2C4%2C5&address=" + escape(MAddress) + "&city=" + escape(city) + "&stateProvince=" + escape(state) + "&postalCode=" + escape(zip) + "&radius=1&brand=&sortOrder=2";

    var vopenurl = "javascript:openpopup('" + glink + "');"
    $('gaslink').innerHTML = "<input type=button onclick=" + vopenurl + " value='Find Gas Station' style='font-family: Arial; font-size: small; height: 23px;' />"
}

//Open popup window with gas station link
function openpopup(glink) {
    var mywindow;
    var wintarget = "_blank";
    mywindow = window.open(glink, wintarget, 'width=740px,height=680px,toolbar=1,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
    mywindow.focus();

}