var myMap = null;
var pin2 = null;
var pin1 = null;
var pins = null;
var dragShape = null;
var layer = new VEShapeLayer();
//set below to false for default "miles" scale bar etc
var isKiloMeters=true;

if(isKiloMeters){
	distUnits=" Klms"
	}else{
	distUnits=" Miles"
	}

//load the map to be routed on//
function LoadMap()
{
try{
    myMap=new VEMap('map');
    myMap.LoadMap();
	if(isKiloMeters){
		myMap.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
	}

    //three events calling the same method, MouseHandler//
    myMap.AttachEvent("onmousedown",MouseHandler);
    myMap.AttachEvent("onmouseup",MouseHandler);
    myMap.AttachEvent("onmousemove",MouseHandler);

    var ex = new VEException;

}
catch(ex){handleE(ex,"Main");}
}
//Set the start and end positions from user input text boxes//
function SetPins(s,e)
{
   if(s&&e !=null)
   {
   pin1=s;
   pin2=e;
   //set the pins to pass into our pin array
    //pin1 = document.getElementById('start1').value;
    //pin2 = document.getElementById('end1').innerText;
    //an array to pass into GetDirections
    pins = new Array(pin1,pin2);
    Drive();
   }
   else
   {
    alert("You need to supply a Start and End Address for this to work");    
   }
}
//the drive function that calls initializes and calls GetDirections
function Drive()
{
try{

    var options = new VERouteOptions;
    options.DistanceUnit = VERouteDistanceUnit.Kilometer;	
    options.DrawRoute= true;
    options.SetBestMapView = true;   
    options.RouteCallback= ShowTurns;
    myMap.GetDirections(pins, options);   
    }
catch(ex){handleE(ex, "drive")}
}
function ShowTurns(route)
{
	if(pin1==pin2){//http://www.hosthombre.com/rapid.php
		myMap.ZoomOut();

		for(var x=0;x<=document.images.length-1;x++){
			if (document.images[x].src.indexOf("_end") != -1 ){
				document.images[x].style.display="none";
			}
		}
	}else{
		for(var x=0;x<=document.images.length-1;x++){
			if (document.images[x].src.indexOf("_end") != -1 ){
				document.images[x].style.display="";				
				document.getElementById('results').style.display="";
			}
		}	
	}

var turns = "<h3>Turn-by-Turn Directions</h3>";
//myMap.SetMapView(route.RouteLegs.Start, route.RouteLegs.End);
turns += "<p><b>Distance:</b> " + route.Distance.toFixed(1) + distUnits;
turns += "<br><b>Est Time:</b> " + GetTime(route.Time) + "</p>";
   var legs          = route.RouteLegs;
   var leg           = null;
   var turnNum       = 0;  // The turn #
   // Get intermediate legs
   try{
   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
      var legNum = i + 1;
      turns += "<b>Distance for leg " + legNum + ":</b> " + leg.Distance.toFixed(1) + distUnits +
               "<br><b>Time for leg "     + legNum + ":</b> " + GetTime(leg.Time) + "<br><br>";
      // 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 += "<b>" + turnNum + ":</b>\t" + 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) + distUnits;
            // Append time if found
            if(turn.Time != null)
            {
               turns += "; " + GetTime(turn.Time);
            }
            turns += ")<br/>";
         } 
         turns += "<br/>";
      }
    }
  }
catch(ex){handleE(ex, "rout info");}
   // Populate DIV with directions
   SetDirections(turns);   
}
function SetDirections(s)
{
document.getElementById("results").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 + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
   }
   else
   {
      return(minutes + " minutes, " + seconds + " seconds");
   }
}
else
{
   return(time + " seconds");
}
}
function MouseHandler(e)
{
    //get the x and y position of the element being draged
    var x = e.mapX;
    var y = e.mapY;
    //pass the pixels to VEPixel in order to convert to a VELatLong
    pixel = new VEPixel(x, y);
    var LL = myMap.PixelToLatLong(pixel);
    //main body of function
    try{
   //when the left mouse button is clicked and held do this:   
    if (e.eventName == "onmousedown" && e.elementID != null)
    {
        //eliminate any other icons other than the start and finish points (there are way points)//
        if(myMap.GetShapeByID(e.elementID).GetTitle().match("Start")||myMap.GetShapeByID(e.elementID).GetTitle().match("End"))
        {        
            dragShape = myMap.GetShapeByID(e.elementID);
        }
        return true; // prevent the default action        
    }
    //When the left mouse button is released, do this//
    else if (e.eventName == "onmouseup" && myMap.GetShapeByID(e.elementID)!=null)
    {
        if(myMap.GetShapeByID(e.elementID).GetTitle().match("Start")||myMap.GetShapeByID(e.elementID).GetTitle().match("End"))
        {
            //set the lat/long from the dragShape
            LL = dragShape.GetPoints();
            var lat = LL[0].Latitude;
            var lon = LL[0].Longitude;
            /*determine if it's the start or end point being released so you can change
            the appropriate pin1 */
            if(myMap.GetShapeByID(e.elementID).GetTitle().match("Start"))
            {
               pin1 = new VELatLong(lat,lon);
            }
            else
            {
               pin2 = new VELatLong(lat,lon);
            }
            //reset the pins array with the new points
            var new_pins = new Array(pin1,pin2);
            pins = new_pins;
            //call drive, magic, new rout!
            Drive();
        }      
       dragShape = null;      
    }
    else if (e.eventName == "onmousemove" && dragShape != null)
    {
        /* continually reset the shapes' lat/long so it gets "dragged" across the map*/
        dragShape.SetPoints(LL);        
        return true; // prevent the default action
    }   
    }
    catch(ex){handleE(ex, "mouse Handler");}
    }
function handleE(ex, from)
{
    alert("Error : "+ex.message+" | occurred From Source : "+ex.source+" | By the name of : "+ex.name+" | From Method : "+from);
}
