$(document).ready(function(){
	setDrivingDirections();
  
	$("#from").click(function(){
		if($("#from").val() ==  defaultMsg){
			$("#from").val('');
		} 
	});
	
	$(window).keypress(function(e) {
	    if(e.keyCode == 13) {
		    FindDirections();
	    }
	});
		
	
});

var map = null;
var width;
var useMiles;
var keycode;

var language;

function printDD(map){
	if(map == "without"){
		var css = 
			"<style>\n@media print { \n" +
			"    .fromInput, .toInput, .print-icon { background-image: none; } \n" +
			"    #drivingDirections .find, #print{display:none;} \n" +
			"    #map{ display:none;}\n" +
			"}</style>";
		$("head").append(css); 
	} else{
		$("head").find("style").remove();
	}
	window.print();
}


//Agent Map Script	        	         
function GetAgentMap(latitude, longitude, zoom, token) {
	var latLong = new VELatLong(latitude, longitude);
	var selStyle = VEMapStyle.Road;
    var selMode = VEMapMode.Mode2D;
	var fixed=0;
    var showSwitch=0;
	map = new VEMap('myMap');
	if (token!=null) {map.SetClientToken(token);} 
	map.LoadMap(latLong, zoom, selStyle, fixed, selMode, showSwitch);
	createShape(latLong, 0);
}
	        
function createShape(latLong, uniqueId) {
 	var shape = new VEShape(VEShapeType.Pushpin, latLong);
	shape.SetCustomIcon("<span><img name='Pushpin' src='images/SFmap-pin-Red.gif' id='icon" + uniqueId + "' /></span>");
	map.AddShape(shape);
}

function GetDrivingMap(token) {
	var latitude=0;
    var longitude=0;
    var zoom=14
	var latLong = new VELatLong(latitude, longitude);
	var selStyle = VEMapStyle.Road;
    var selMode = VEMapMode.Mode2D;
	var fixed=0;
    var showSwitch=0;
    map = new VEMap('myMap');
	if (token!=null) {map.SetClientToken(token);} 
	map.LoadMap(latLong, zoom, selStyle, fixed, selMode, showSwitch);
}

function FindDirections() {
	var locations;
	var latLong;
	
	var options = new VERouteOptions;
	var from = document.getElementById("from").value;

	var to = document.getElementById("to").value;
	var destLat = document.getElementById("destLatitude").value;
	var destLong = document.getElementById("destLongitude").value;
	var mapObj = document.getElementById("myMap"); 
	
	document.getElementById("map").style.visibility="visible";

	options.DrawRoute      = true;
	options.SetBestMapView = true;
	options.RouteCallback  = ShowTurns;
	options.ShowDisambiguation = true;
	
	if (usesMiles(to)){
		options.DistanceUnit = VERouteDistanceUnit.Mile;
		map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
		useMiles = true;
	}else{
		options.DistanceUnit = VERouteDistanceUnit.Kilometer;
		map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);	
		useMiles = false;
	}	
	//how to set mi/km when passing lat/long
	if( (destLat != "") && (destLong != "") && isLatLongValid(destLat,destLong)){
		to = new VELatLong(destLat, destLong);
	}
	
	locations = new Array(from, to);	
	map.GetDirections(locations, options);
}

function isLatLongValid(lat,long){
	lat = lat.replace(".","");
	long = long.replace(".","");
	if(parseInt(lat)!=0 && parseInt(long)!=0){
		return true;
	}
	return false;
}

function ShowTurns(route) {
	var turns = "";
	var distanceType; 
	var distanceTypeInt;
	
	if (useMiles) {
		distanceType = miTxt+"s";
		distanceTypeInt = "mi";
	}
	else{
		distanceType= kmTxt+"s";
		distanceTypeInt="km";
	}
	turns = "<h3><font color='3F3F3F'>"+ turnByTurnTxt + "</font></h3>";
	turns += "<p><b>" + distanceTxt +":</b> " + route.Distance.toFixed(1) + " " + distanceType;
	turns += "<br/><b>" + timeTxt + ":</b> " + GetTime(route.Time) + "</p>";
	
  	// Unroll route and populate DIV
	var legs          = route.RouteLegs;
	var leg           = null;
	var turnNum       = 0;  // The turn #
	var width         = "100%"

  	// 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
  	  var legNum = i + 1;

      // Unroll each intermediate leg
      var turn        = null;  // The itinerary leg
  	  var legDistance = null;  // The distance for this leg
  	   
  	  turns += "<table>";
        
      for(var j = 0; j < leg.Itinerary.Items.length; j ++) {
         turnNum++;
         turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
         if (turnNum%2){turns += "<tr class='oddLine'><td class='oddLine'>";}else{turns += "<tr class='evenLine'><td class='evenLine'>";}
  	     turns += "<b>" + turnNum + ".&nbsp;</b>" + turn.Text + "</td>";
      	 legDistance    = turn.Distance;

         // So we don't show 0.0 for the arrival
         if (turnNum%2){turns += "<td align='right' class='oddLine'>";}else{turns += "<td align='right' class='evenLine'>";}
         if(legDistance > 0) {  // Round distances to 1/10ths
  	         turns += legDistance.toFixed(1) + " " + distanceTypeInt;
  	      }
  	     turns += "</td></tr>";

      }
      turns += "</table>";
	}
   SetDirections(turns);
}

function SetDirections(s) {
	var d = document.getElementById("directions");
    d.innerHTML = s;
}

// 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 + " " + hourTxt+"(s), " + minLeft + " " + minuteTxt+"(s), " + seconds + " " + secondTxt + "(s)");
       } else {
		  return(minutes + " " + minuteTxt+"s, " + seconds + " " + secondTxt+"s");
   	   }
    } else {
		return(time + " " + secondTxt+"s");
  	}
}

function usesMiles(inputValue) {
	var address=inputValue.split(",");
	var zip=trim(address[2].toString());
	var patt=/^\d{5}$|^\d{5}-\d{4}$/;
	return(patt.test(zip));
}

function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
	ws = /\s/,
	i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}



function setDrivingDirections(){
	var currentURL = window.location.href.toLowerCase();
	var index = currentURL.indexOf("language=spanish");
	
	if(index > 0){
	    language = "spanish";
	}
	if(document.getElementById("from").value == ""){
		document.getElementById("from").value = defaultMsg;
	}
}

