var map;
var LocationSearchHandler="/_layouts/VirtualEarth/LocationSearch.ashx";
var _listid;
var _webid;
var _titlefield;
var _descfield;
var tmpPushpinTitle;
var findIcon;

var endpt;
var startpt;

function VEWebPart_LoadMap(divid, latitude, longitude, zoom, type, listid, webid, titlefield, descfield, showsearchbox) {   
    // Show the map and hook up events
    map = new VEMap(divid);
    map.SetDashboardSize(VEDashboardSize.Tiny);
    
    endpt = new VELatLong(latitude, longitude);
    
    map.LoadMap(endpt, zoom , type ,false);
    map.AttachEvent("onchangeview", view_Changed);
        
    _listid = listid;
    _webid=webid;
    _titlefield = titlefield;
    _descfield = descfield;
    
    if (showsearchbox) {
        ShowSearchBox();
    }
        
    view_Changed();
}

function view_Changed()  {
    var view = map.GetMapView();
    var geoRSSUrl = LocationSearchHandler + "?hlat=" + view.TopLeftLatLong.Latitude + "&llng=" + view.TopLeftLatLong.Longitude + "&llat=" + view.BottomRightLatLong.Latitude  + "&hlng=" + view.BottomRightLatLong.Longitude + "&titlefld=" + _titlefield + "&listid=" + _listid + "&webid=" + _webid;
    geoRSSUrl = geoRSSUrl + "&" + (new Date()).getTime();
    if (_descfield != "") {
        geoRSSUrl = geoRSSUrl + "&descfld=" + _descfield;
    }
            
    LoadGeoRSS(geoRSSUrl);
}

function LoadGeoRSS(url) {   
    var l = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, url, l);
    map.ImportShapeLayerData(veLayerSpec, onFeedLoad, 0);
}

function onFeedLoad(shapeLayer) {
    for (i=0; i < shapeLayer.GetShapeCount(); i++) {
		var s = shapeLayer.GetShapeByIndex(i);                
		s.SetCustomIcon("<img src=\"/_layouts/1033/images/businessschool/pin.gif\" />");
	}
	
    var resultsdiv = document.getElementById('VEWebPart_SearchResults');
    if (resultsdiv) {
        if ( resultsdiv.hasChildNodes() ) {
            while ( resultsdiv.childNodes.length >= 1 )  {
                resultsdiv.removeChild( resultsdiv.firstChild );       
            } 
        }
        
        for (i=0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            if (shape.GetTitle() != "dummy")  {
              var el = document.createElement("div");
              el.id="velocation_" + i;
              var strHtml =  "<span class=\"title\">" + shape.GetTitle() + "</span>";
              strHtml += "<div>" + shape.GetDescription() + "</div>";
              strHtml += "<hr />";
                            
              el.innerHTML = strHtml;
              resultsdiv.appendChild(el);
            }
        }
    }
}

function ShowSearchBox() {
    var el = document.createElement("div");
    el.id = "VEWebPart_SearchForm";
    el.style.top = 14;
    //el.style.left = GetMapWidth() - 168; // = Width of the map - width of the div - margin right
    el.style.left = 40;
    el.style.border = "1px solid gray";
    el.style.background = "#f1f7f7";
    el.style.padding = 3;
    el.style.width = "163px";
    el.style.fontSize = "10px";    
    
    var strHtml =  "Address:<br/><input type=\"text\" id=\"VEWebPart_findAddress\"><br />";
    strHtml = strHtml + "<input type=\"submit\" value=\"Search\"  id=\"VWebPart_AddressSearchSubmit\" onclick=\"VEWebPart_FindAddress(); return false;\">";
            
    el.innerHTML = strHtml;
    map.AddControl(el);   
}

function VEWebPart_FindAddress() {
    var address = document.getElementById('VEWebPart_findAddress').value;
    tmpPushpinTitle = address;
    
    try {            
        map.Find(null, address, null, null, null, null, true, true, true, true, onLocationFound);         
    }         
    catch(e) {            
        alert(e.message);         
    }
}

function onLocationFound(layer, resultsArray, places, hasMore, veErrorMessage) {
    var latlon;
    
    latlon = places[0].LatLong;
    if (findIcon)
        map.DeleteShape(findIcon);
    
    findIcon = new VEShape(VEShapeType.Pushpin, latlon);    
    findIcon.SetTitle(tmpPushpinTitle);
    findIcon.SetCustomIcon("/_layouts/images/ewr206l.gif");
    map.AddShape(findIcon);
    map.SetZoomLevel(12);
}

function VEWebPart_FindDirections() {
    var address = document.getElementById('VEWebPart_findAddress').value;

    var locations = new Array(address, endpt);

    var options = new VERouteOptions;

    options.DrawRoute = true;
    options.SetBestMapView = true;
    options.RouteCallback  = OnGotDirections;
    options.DistanceUnit = VERouteDistanceUnit.Mile;
    options.ShowDisambiguation = true;
    
    map.GetDirections(locations, options);
}

function OnGotDirections(route) {

   var turns = "<p>";

   var legs          = route.RouteLegs;
   var leg           = null;
   var turnNum       = 0;

   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 += "<br/><b>Distance:</b> " + leg.Distance.toFixed(1) + " miles" +
               "<br/><b>Time:</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) + " miles";

            // Append time if found
            if(turn.Time != null) {
               turns += "; " + GetTime(turn.Time);
            }

            turns += ")<br/>";
         }
      }

      turns += "</p>";
   }
       
   // Populate DIV with directions
   SetDirections(turns);
}

function SetDirections(s) {
    var d = document.getElementById("directions");
    d.innerHTML = s;
    
    setFooter();    
}

// 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 GetMapWidth() {
    var view = map.GetMapView();
    var bottomright = view.BottomRightLatLong;
            
    return map.LatLongToPixel(bottomright).x;
}

function GetMapHeight() {
    var view = map.GetMapView();
    var bottomright = view.BottomRightLatLong;
            
    return map.LatLongToPixel(bottomright).y;
}