
var drivingDirections = null;
var _Page = 1;

﻿function GetCoordForSuburb()
{
    document.getElementById("MapPanel").style.cursor = "pointer";
    g_map.GetCoordinateFromMap(true,"GetSuburbID");
}
function GetSuburbID(lat,lon)
{
document.getElementById("MapPanel").style.cursor = "default";
        xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
      var strClickedPoint =  g_map.GetClickedCoordinates();   //To retrieve values use: strClickedPoint[0].Longitude and strClickedPoint[0].Latitude
        
    var url = "AJAXGetSuburbID.aspx?lat="+strClickedPoint[0].Latitude+"&lon="+strClickedPoint[0].Longitude;
    xmlHttp.onreadystatechange=RecieveSuburbID;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    
}
function RecieveSuburbID()
{
 if (xmlHttp.readyState==4)
    {
        if(xmlHttp.responseText == "none")
        {
            alert("No Suburb Found");
        }
        else
        {
            window.open("SuburbHistory.aspx?id="+xmlHttp.responseText,"", "resizable=no,scrollbars=yes,top=0,left=0,width="+660+",height="+800);
        }
    }
}

function ResetSearch()
{
    wayPoint = "";
    oDirections = null;
    RouteType = "";
    RouteLat = "";
    RouteLon = "";
    RouteLocation = "";
    document.getElementById("ResultsDiv").innerHTML ="";
    document.getElementById("SelectedRouteDest").style.display = 'none';
    document.getElementById("SelectedRoute").style.display = 'none';
    document.getElementById("RouteDirections").innerHTML ='';
    document.getElementById("SearchBox").style.display='';
    document.getElementById("btnShowWeather").innerHTML = "Show Weather";
    document.getElementById("btnShowTraffic").innerHTML = "Show Traffic Incidents";
    //g_map.DrivingDirections.Clear();
    if (drivingDirections != null)
    {
        drivingDirections.clear();
    }
    //g_map.RemoveAllObjects();
    g_map.removeGroupOverlay("Traffic");    
    g_map.removeGroupOverlay("Weather");    
    g_map.removeGroupOverlay("Point");
    g_map.removeGroupOverlay("Flags");
   
}
function CalcRouteFromClick()
{
    alert("Test");
}
function ClearMapAsync()
   {
      var oLatLng = new AGCoord(-28.5751829172523,24.0430317799304);
      g_map.centreAndScale(oLatLng,5);
      //g_map.DrivingDirections.Clear();
      if (drivingDirections != null)
      {
          drivingDirections.clear();
      }
      //g_map.RemoveAllObjects();
        g_map.removeGroupOverlay("Traffic");    
        g_map.removeGroupOverlay("Weather");    
        g_map.removeGroupOverlay("Point"); 
        g_map.removeGroupOverlay("Flags");   
   }
   
function ClearMap()
{       var oLatLng = new AGCoord(-28.5751829172523,24.0430317799304);
        g_map.centreAndScale(oLatLng, 5);
        //g_map.DrivingDirections.Clear();
        if (drivingDirections != null)
        {
            drivingDirections.clear();
        }
        //g_map.RemoveAllObjects();
        document.getElementById("SearchBox").style.display='';
        document.getElementById("ResultsDiv").style.display='';
        document.getElementById("navPanel1").style.display = '';
        g_map.removeGroupOverlay("Traffic");    
        g_map.removeGroupOverlay("Weather");    
        g_map.removeGroupOverlay("Point");    
        g_map.removeGroupOverlay("Flags");
}

function AddressSearch()
{
if(document.getElementById("txtSearchAddress").value != "")
   { 
        var w = document.createElement('div');
        document.getElementById("ResultsDiv").innerHTML ="";
        w.innerHTML = "<center><img src='images/loading_animated.gif'/></center>";
        document.getElementById("ResultsDiv").appendChild(w);
        var oBoundingBox = g_map.getBoundingBox();
        var oSouthWestCoords = oBoundingBox.getSouthWest();
        var oNorthEastCoords = oBoundingBox.getNorthEast();
        var boundingBox = oSouthWestCoords.longitude() + "," + oSouthWestCoords.latitude() + "," + oNorthEastCoords.longitude() + "," + oNorthEastCoords.latitude();
        
        var _url = "GenericLuceneSearch.aspx?";
            _url = _url + "SearchText=" + document.getElementById("txtSearchAddress").value;
            _url = _url + "&Index=UNIFIEDLUCENE";
            _url = _url + "&bb="+ boundingBox;
            _url = _url + "&RandomID=" + Math.random();        
            $.getJSON(_url,
                    function(json)
                    {
                       callbackFunction(json)
                    }
                );
    }
}
function SelectRouteMap(lat,lon)
{
    var oInfoDisplay = g_map.getInfoDisplay();
    oInfoDisplay.hide();

    if(document.getElementById("rbFrom").checked)
    {
        SelectRoute("RouteFrom",lat,lon,document.getElementById("lblAddrBubble").innerHTML);
    }
    else
    {
        SelectRoute("RouteTo",lat,lon,document.getElementById("lblAddrBubble").innerHTML);
    }
    document.getElementById("txtSearchAddress").value = document.getElementById("txtbubble").value;
    AddressSearch();
}
function SearchDestinationBubble(lat,lon)
{
    g_map.removeGroupOverlay("Flags");
    var oInfoDisplay = g_map.getInfoDisplay();
    oInfoDisplay.hide();
    DrawRoute(lat,lon,document.getElementById("lblAddrBubble").innerHTML);
}
function AddressSearchNext()
{

    var w = document.createElement('div');
    document.getElementById("ResultsDiv").innerHTML ="";
   w.innerHTML = "<center><img src='images/loading_animated.gif'/></center>";
   document.getElementById("ResultsDiv").appendChild(w);
    //document.getElementById("imgLoading").style.display = '';
    
   // if(document.getElementById("txtBusiness").value != "" && document.getElementById("txtSearchAddress").value != "")
   // {
    
  //      AddressSearchJSONBusinessLocation(document.getElementById("txtBusiness").value,"Business",g_map.GetBoundingBox(),document.getElementById("txtSearchAddress").value);
  //  }

    var oBoundingBox = g_map.getBoundingBox();
    var oSouthWestCoords = oBoundingBox.getSouthWest();
    var oNorthEastCoords = oBoundingBox.getNorthEast();
    var boundingBox = oSouthWestCoords.longitude() + "," + oSouthWestCoords.latitude() + "," + oNorthEastCoords.longitude() + "," + oNorthEastCoords.latitude();
    
    var _url = "GenericLuceneSearchNext.aspx?";
        _url = _url + "SearchText=" + document.getElementById("txtSearchAddress").value;
        _url = _url + "&Index=UNIFIEDLUCENE";
        _url = _url + "&bb="+ boundingBox;
        _url = _url + "&RandomID=" + Math.random();        
        $.getJSON(_url,
                function(json)
                {
                   callbackFunction(json)
                }
            );

}
function callbackFunction(Result)
{
    var icntLocal = 0;
   document.getElementById("ResultsDiv").style.display='';
   g_map.removeGroupOverlay("Flags");
   document.getElementById("ResultsDiv").innerHTML ="";
   var oLucene =Result;
   var w = document.createElement('div');
   var elHtml = "";
   if(!oLucene.Results.Record)
   {
    elHtml += "<a class='SearchResultLink' href='javascript:{};'>No Results Found</a>";
   }
   else
   {
   
   if(oLucene.ResultsLocal != null && oLucene.ResultsLocal.LuceneLocal.RecordLocal != null)
   {
   icntLocal = oLucene.ResultsLocal.LuceneLocal.RecordLocal.length;
       elHtml +="<div style='background-color:#FFFFCC;'><span style='float:right;color:black;font-size:8pt;'>Local Search Results</span><br/>";
var arrdata = new Array()
       for(var i =0;i < oLucene.ResultsLocal.LuceneLocal.RecordLocal.length;i++)
       {           
            arrdata[i] = oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS;
           
           if(RouteType == "")
            {   
                 _i = i+1;
                sImage = "Green/button"+_i+".png";
                sFlag = "Green/Flag"+_i+".png";
                sFlagRed = "Yellow/Flag"+_i+".png";
                imgID = i+"imgl";
                elHtml += "<div><img src='MapFlag/"+sImage+"' style='float:left;' /><div style='margin-left:20px;'><a class='SearchResultLink' href='javascript:{};' onmouseover='this.style.background=\"Gray\";document.getElementById(\""+i+"divl\").style.zIndex=10;getElementById(\""+i+"imgl\").src=\"MapFlag/"+sFlagRed+"\"' onmouseout='this.style.background=\"#f3f3f3\";getElementById(\""+i+"divl\").style.zIndex=1;getElementById(\""+i+"imgl\").src=\"MapFlag/"+sFlag+"\"' onclick='NoPoint(" + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude + "," + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude + ",\"" + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS  + "\")'>"+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS+"</a><br/>";
                elHtml +="<div><a href='javascript:{};' class='RouteTag' onclick='SelectRoute(\"RouteTo\"," + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude + "," + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude + ",\"" + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS + "\");'>&nbsp;Route To&nbsp;</a>&nbsp;&nbsp;<a class='RouteTag' href='javascript:{};' onclick='SelectRoute(\"RouteFrom\"," + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude + "," + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude + ",\"" + oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS + "\")';>&nbsp;Route From&nbsp;</a><br/></div></div></div>";
                
               str = "<div><p><strong><a id=lblAddrBubble > "+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS+"</a></strong></p>";
               str+="<p><strong>Get Directions</strong></p>";
               str+="<p><strong></strong>From Here <input type=radio name=radGroup id=rbFrom checked/> End Here <input type=radio name=radGroup id=rbTo /></p>";
               str+="<p><strong></strong>Search Text :<input id=txtbubble type=text/></a></p><br/><a href=javascript:{} onclick=SelectRouteMap("+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude+","+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude+");>Search</a></div>";
                
             
                var myHTMLObj = document.createElement('div');
                myHTMLObj.setAttribute("id",i+"divl");
                myHTMLObj.style.zIndex = 1;                
                myHTMLObj.innerHTML = "<img onclick='ShowBubblePopup(g_map,"+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude+","+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude+",\""+str+"\",300,200,5,-32)' id='"+imgID+"'  class='clsPoi' style='z-index:1' src='MapFlag/"+sFlag+"' title='"+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS+"' />";
                var _point = new AGPoint(-15,-40);
                var _options = new AGHTMLOverlayOptions(_point);
                var myHTMLOverlay = new AGHTMLOverlay(myHTMLObj, new AGCoord(parseFloat(oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude), parseFloat(oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude)),_options );
                g_map.addOverlay(myHTMLOverlay,"Flags");                
            }   
            else
            {
               str = "<div><p><strong><a id=lblAddrBubble > "+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].ADDRESS_DETAILS+"</a></strong></p>";
               str+="<p><a href=javascript:{} onclick=SearchDestinationBubble("+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude+","+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude+")>Get Directions</a></div>";
                
                
                 _i = i+1;                                
                sImage = "Green/button"+_i+".png";
                sFlag = "Green/Flag"+_i+".png";
                sFlagRed = "Yellow/Flag"+_i+".png";
                imgID = i+"imgl";
                elHtml += "<div><img src='MapFlag/"+sImage+"' style='float:left;' /><div style='margin-left:20px;'><a class='SearchResultLink' href='javascript:{};' onmouseover='this.style.background=\"Gray\";document.getElementById(\""+i+"divl\").style.zIndex=10;getElementById(\""+i+"imgl\").src=\"MapFlag/"+sFlagRed+"\"' onmouseout='this.style.background=\"#f3f3f3\";getElementById(\""+i+"divl\").style.zIndex=1;getElementById(\""+i+"imgl\").src=\"MapFlag/"+sFlag+"\"' onclick='NoPoint(" + oLucene.Results.Record[i].Latitude + "," + oLucene.Results.Record[i].Longitude + ",\"" + oLucene.Results.Record[i].ADDRESS_DETAILS  + "\")'>"+oLucene.Results.Record[i].ADDRESS_DETAILS+"</a><br/>";
                elHtml +="<div><a href='javascript:{};' class='RouteTag' onclick='DrawRoute(" + oLucene.Results.Record[i].Latitude + "," + oLucene.Results.Record[i].Longitude + ",\"" + oLucene.Results.Record[i].ADDRESS_DETAILS + "\");'>&nbsp;Get Directions&nbsp;</a><br/></div></div></div>";
                var myHTMLObj = document.createElement('div');
                myHTMLObj.setAttribute("id",i+"divl");
                myHTMLObj.style.zIndex = 1;           
                myHTMLObj.innerHTML = "<img id='"+imgID+"' onclick='ShowBubblePopup(g_map,"+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Latitude+","+oLucene.ResultsLocal.LuceneLocal.RecordLocal[i].Longitude+",\""+str+"\",300,150,5,-32)' class='clsPoi' style='z-index:100' src='MapFlag/"+sFlag+"' title='"+oLucene.Results.Record[i].ADDRESS_DETAILS+"' />";
                var _point = new AGPoint(-15,-40);
                var _options = new AGHTMLOverlayOptions(_point);
                var myHTMLOverlay = new AGHTMLOverlay(myHTMLObj, new AGCoord(parseFloat(oLucene.Results.Record[i].Latitude), parseFloat(oLucene.Results.Record[i].Longitude)) ,_options);
                g_map.addOverlay(myHTMLOverlay,"Flags");
            }   
       }
       elHtml +="</div><br/>";
   }
    icnt = 1;
   for(var i =0;i < oLucene.Results.Record.length;i++)
   {    
        match = false;
        for(icnt1 =0;icnt1<10;icnt1++)
        {
            if(arrdata != null)
            {
                if(oLucene.Results.Record[i].ADDRESS_DETAILS == arrdata[i])
                    match = true;
            }
        }
        if(icnt < 11 && match == false)
        {
            
            if(RouteType == "")
                {
                    
                    _ii = icnt+icntLocal;
                    _iii = icnt-1;
                    imgID = icnt+"img";
                    sImage = "Blue/button"+_ii+".png";
                    sFlag = "Blue/Flag"+_ii+".png";
                    sFlagRed = "Red/Flag"+_ii+".png";
                    
                    elHtml += "<div><img src='MapFlag/"+sImage+"' style='float:left;' /><div style='margin-left:20px;'><a class='SearchResultLink' href='javascript:{};' onmouseover='this.style.background=\"Gray\";document.getElementById(\""+icnt+"div\").style.zIndex=10;getElementById(\""+icnt+"img\").src=\"MapFlag/"+sFlagRed+"\"' onmouseout='this.style.background=\"#f3f3f3\";getElementById(\""+icnt+"div\").style.zIndex=1;getElementById(\""+icnt+"img\").src=\"MapFlag/"+sFlag+"\"' onclick='NoPoint(" + oLucene.Results.Record[i].Latitude + "," + oLucene.Results.Record[i].Longitude + ",\"" + oLucene.Results.Record[i].ADDRESS_DETAILS  + "\")'>"+oLucene.Results.Record[i].ADDRESS_DETAILS+"</a><br/>";
                    elHtml +="<div><a href='javascript:{};' class='RouteTag' onclick='SelectRoute(\"RouteTo\"," + oLucene.Results.Record[i].Latitude + "," + oLucene.Results.Record[i].Longitude + ",\"" + oLucene.Results.Record[i].ADDRESS_DETAILS + "\");'>&nbsp;Route To&nbsp;</a>&nbsp;&nbsp;<a class='RouteTag' href='javascript:{};' onclick='SelectRoute(\"RouteFrom\"," + oLucene.Results.Record[i].Latitude + "," + oLucene.Results.Record[i].Longitude + ",\"" + oLucene.Results.Record[i].Address + "\")';>&nbsp;Route From&nbsp;</a><br/></div></div></div></div>";
                    
                    str = "<div><p><strong><a id=lblAddrBubble > "+oLucene.Results.Record[i].ADDRESS_DETAILS+"</a></strong></p>";
                    str+="<p><strong>Get Directions</strong></p>";
                    str+="<p><strong></strong>From Here <input type=radio name=radGroup id=rbFrom checked/> End Here <input type=radio name=radGroup id=rbTo /></p>";
                    str+="<p><strong></strong>Search Text :<input id=txtbubble type=text/></a></p><br/><a href=javascript:{} onclick=SelectRouteMap("+oLucene.Results.Record[i].Latitude+","+oLucene.Results.Record[i].Longitude+");>Search</a></div>";
                
                    
                    var myHTMLObj = document.createElement('div');
                    myHTMLObj.setAttribute("id",icnt+"div");
                    myHTMLObj.style.zIndex = 1;                
                    myHTMLObj.innerHTML = "<img id='"+imgID+"' onclick='ShowBubblePopup(g_map,"+oLucene.Results.Record[i].Latitude+","+oLucene.Results.Record[i].Longitude+",\""+str+"\",300,150,5,-32)' class='clsPoi' style='z-index:100' src='MapFlag/"+sFlag+"' title='"+oLucene.Results.Record[i].ADDRESS_DETAILS+"' />";
                    var _point = new AGPoint(-15,-40);
                    var _options = new AGHTMLOverlayOptions(_point);
                    var myHTMLOverlay = new AGHTMLOverlay(myHTMLObj, new AGCoord(parseFloat(oLucene.Results.Record[i].Latitude), parseFloat(oLucene.Results.Record[i].Longitude)),_options );
                    g_map.addOverlay(myHTMLOverlay,"Flags");
                    
                }   
                else
                {
                    _ii = icnt+icntLocal;
                    _iii = icnt-1;
                    imgID = icnt+"img";
                    sImage = "Blue/button"+_ii+".png";
                    sFlag = "Blue/Flag"+_ii+".png";
                    sFlagRed = "Red/Flag"+_ii+".png";
                    elHtml += "<div><img src='MapFlag/"+sImage+"' style='float:left;' /><div style='margin-left:20px;'><a class='SearchResultLink' href='javascript:{};' onmouseover='this.style.background=\"Gray\";document.getElementById(\""+icnt+"div\").style.zIndex=10;getElementById(\""+icnt+"img\").src=\"MapFlag/"+sFlagRed+"\"' onmouseout='this.style.background=\"#f3f3f3\";getElementById(\""+icnt+"div\").style.zIndex=1;getElementById(\""+icnt+"img\").src=\"MapFlag/"+sFlag+"\"' onclick='NoPoint(" + oLucene.Results.Record[i].Latitude + "," + oLucene.Results.Record[i].Longitude + ",\"" + oLucene.Results.Record[i].ADDRESS_DETAILS  + "\")'>"+oLucene.Results.Record[i].ADDRESS_DETAILS+"</a><br/>";
                    elHtml +="<div><a href='javascript:{};' class='RouteTag' onclick='DrawRoute(" + oLucene.Results.Record[i].Latitude + "," + oLucene.Results.Record[i].Longitude + ",\"" + oLucene.Results.Record[i].ADDRESS_DETAILS + "\");'>&nbsp;Get Directions&nbsp;</a><br/></div></div>";
                   str = "<div><p><strong><a id=lblAddrBubble > "+oLucene.Results.Record[i].ADDRESS_DETAILS+"</a></strong></p>";
                    str+="<p><a href=javascript:{} onclick=SearchDestinationBubble("+oLucene.Results.Record[i].Latitude+","+oLucene.Results.Record[i].Longitude+")>Get Directions</a></div>";
              
                     var myHTMLObj = document.createElement('div');
                     myHTMLObj.setAttribute("id",icnt+"div");
                    myHTMLObj.style.zIndex = 1;      
                        var _point = new AGPoint(-15,-40);
                var _options = new AGHTMLOverlayOptions(_point);     
                    myHTMLObj.innerHTML = "<img id='"+imgID+"' onclick='ShowBubblePopup(g_map,"+oLucene.Results.Record[i].Latitude+","+oLucene.Results.Record[i].Longitude+",\""+str+"\",300,150,5,-32)' class='clsPoi' style='z-index:100' src='MapFlag/"+sFlag+"' title='"+oLucene.Results.Record[i].ADDRESS_DETAILS+"' />";
                    var myHTMLOverlay = new AGHTMLOverlay(myHTMLObj, new AGCoord(parseFloat(oLucene.Results.Record[i].Latitude), parseFloat(oLucene.Results.Record[i].Longitude)) ,_options);
                    g_map.addOverlay(myHTMLOverlay,"Flags");
                }    
                icnt++; 
            }     
   }
   }
//   if(Result.Results.Lucene[0].MoreResult == "YES" && _Page == 1)
//   {
//    _Page = 2;
//    elHtml +="<a onclick='AddressSearchNext()' style='cursor:pointer'>Next<a>";
//    
//   }
//   else if(_Page == 2)
//   {
//    _Page = 1;
//    elHtml +="<a onclick='AddressSearch()' style='cursor:pointer'>Back<a>";
//   }
   w.innerHTML = elHtml;
   document.getElementById("ResultsDiv").appendChild(w);
   //document.getElementById("imgLoading").style.display = 'none';
   
}
function DrawRoute(Lat,Lon,Description)
{   
document.getElementById("txtSearchAddress").value = "";
    var StartLat;
    var StartLon;
    var EndLat;
    var EndLon;
    document.getElementById("RouteHeading").innerHTML = "Route From:";
    document.getElementById("RouteHeadingDest").innerHTML = "Route To:";
    if(RouteType == "To")
    {
        
        StartLat = Lat;
        StartLon = Lon;
        EndLat = RouteLat;
        EndLon = RouteLon;
        document.getElementById("SelectedPoint").innerHTML = Description;
        sDescription = Description;
        document.getElementById("SelectedPointDest").innerHTML = RouteLocation;
        
    }   
    else
    {
        StartLat = RouteLat;
        StartLon = RouteLon;
        EndLat = Lat;
        EndLon = Lon;
        sDescription = Description;
        document.getElementById("SelectedPointDest").innerHTML = Description;
        document.getElementById("SelectedPoint").innerHTML = RouteLocation;
    }
    
    //g_map.DrivingDirections.SetOrigin(StartLat, StartLon); 
    //g_map.DrivingDirections.SetDestination(EndLat, EndLon);
    var startCoord = new AGCoord(StartLat,StartLon);
    var endCoord = new AGCoord(EndLat,EndLon);
    
    
 
    centerLat = (StartLat + EndLat) /2;
    centerLon = (StartLon + EndLon) /2;
    var bb = new AGBoundingBox(startCoord, endCoord)

    var oCenterLatLng = new AGCoord(parseFloat(centerLat),parseFloat(centerLon));
    var z_scale = g_map.getBoundingBoxZoomLevel(bb);
    g_map.centreAndScale(oCenterLatLng,z_scale-1);
    drivingDirections = new AGDirections(g_map);
    drivingDirections.load(startCoord, endCoord);
    document.getElementById("SelectedRouteDest").style.display = '';
    document.getElementById("SearchBox").style.display='none';
    document.getElementById("ResultsDiv").innerHTML = ''; 
    document.getElementById("ResultsDiv").style.display='none';
    wayPoint = StartLat+"|"+StartLon+"$"+EndLat+"|"+EndLon;
    GetDrivingDirections(wayPoint);
    

}
function GetRouteFromClick()
{
  var points, strPoints;
  var Start = g_map._oRoutingManager._arrWaypoints[0];
  var End = g_map._oRoutingManager._arrWaypoints[1];
   var startCoord = new AGCoord(Start._fLat,Start._fLng);
    var endCoord = new AGCoord(End._fLat,End._fLng);
    centerLat = (Start._fLat + End._fLat) /2;
    centerLon = (Start._fLng + End._fLng) /2;
    var bb = new AGBoundingBox(startCoord, endCoord)
    var oCenterLatLng = new AGCoord(parseFloat(centerLat),parseFloat(centerLon));
    var z_scale = g_map.getBoundingBoxZoomLevel(bb);
    g_map.centreAndScale(oCenterLatLng,z_scale-1);
  //points = g_map.DrivingDirections.GetPoints();
  strPoints = Start._fLat + ";" + Start._fLng+";"+End._fLat + ";" + End._fLng;
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 

    var url = "AJAXReverseGeoCoding.aspx?coord="+strPoints+"&num="+Math.random();
 
    xmlHttp.onreadystatechange=RecieveRouteDescription;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);

}
function RecieveRouteDescription()
{

    if (xmlHttp.readyState==4)
    {
       Result =xmlHttp.responseText.split(";");
        var StartLat;
        var StartLon;
        var EndLat;
        var EndLon;
        document.getElementById("RouteHeading").innerHTML = "Route From:";
        document.getElementById("RouteHeadingDest").innerHTML = "Route To:";        
        StartLat = Result[1];
        StartLon = Result[2];
        EndLat = Result[4];
        EndLon = Result[5];
      //  document.getElementById("SelectedPoint").innerHTML = Result[0];
        sDescription = Result[0];
        //document.getElementById("SelectedPointDest").innerHTML = Result[3];
        document.getElementById("SelectedRouteDest").style.display = '';
        document.getElementById("SelectedRoute").style.display = '';
        document.getElementById("SearchBox").style.display='none';
        document.getElementById("ResultsDiv").innerHTML = ''; 
        document.getElementById("ResultsDiv").style.display='none';
        wayPoint = StartLat+"|"+StartLon+"$"+EndLat+"|"+EndLon;
        GetDrivingDirections(wayPoint);
    }

}

function GetDrivingDirections(Waypoint)
{
        xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    
    var url = "AjaxDrivingDirections.aspx?Waypoints="+Waypoint+"&num="+Math.random();
    xmlHttp.onreadystatechange=RecieveDirections;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    
}
function RecieveDirections()
{
    if (xmlHttp.readyState==4)
    {
       Result =xmlHttp.responseText;
       oDirections = eval("("+Result+")");
       document.getElementById("RouteDirections").innerHTML = '';
       document.getElementById("RouteDirections").innerHTML ="<strong class='directionDesc'>Route Instructions:</strong><br/>";
       var sHtml = "";
       for(var i =0;i < oDirections.Directions.length;i++)
        {
            eHTML = "<div class='egStyle'>"
            eHTML += "<img id='btnExpandMap"+i+"' alt='Display Map' src='Images/MapExpand.gif' onclick='ShowMap("+i+");' style='cursor:pointer;float:right;' />"
            eHTML += "</div>"
            eHTML += "<img id='dirIcon' style='margin-right:10px;' src='"+oDirections.Directions[i].Image+"' /><span class='directionDesc' >"+oDirections.Directions[i].Instruction;+"</span>";
            eHTML += "<div class='DirectionImage' id='DirectionImage"+i+"'style='height:0px;margin-top:10px'>"
            eHTML += "</div>"
            if(oDirections.Directions[i].Length == "for 0")
            {
            eHTML += "<div style='text-align:right;'><span style='padding-right:35px;'><strong></strong></span></div>";
            }
            else
            {
                eHTML += "<div class='egStyle' style='text-align:right;'><span style='padding-right:35px;'><strong>"+oDirections.Directions[i].Length+"</strong></span></div>";
            }
            eHTML += "<hr style='width:230px;' />"
            var w = document.createElement("div") //'<div style="text-align:left;">')
            w.innerHTML = eHTML
            document.getElementById("RouteDirections").appendChild(w)   
        
        }
     
    }
}
function ShowMap(id)
{
 if(document.getElementById("MapImage"+id) == null)
 {
 
 var iHTML = "<img id='MapImage"+id+"' src='"+oDirections.Directions[id].Thumbnail+"' style='height:0;margin-left:17px'/>"
 var w = document.createElement("div") //'<div style="text-align:left;">')
 w.innerHTML = iHTML
 document.getElementById("DirectionImage"+id).appendChild(w)

 }

 if(document.getElementById("btnExpandMap"+id).alt=='Display Map')
{

 document.getElementById("btnExpandMap"+id).alt='Hide Map';
 document.getElementById("btnExpandMap"+id).src='Images/mapHide.gif';
 Amount = 50;
 MoveAmount = 1;
 Expand(id);
 //document.getElementById("spnMap"+id).style.display='block';
 }
 else
 {

 document.getElementById("btnExpandMap"+id).alt='Display Map';
 document.getElementById("btnExpandMap"+id).src='Images/MapExpand.gif';
 Amount = 0;
 MoveAmount = -1;
 Expand(id);
 //document.getElementById("spnMap"+id).style.display='none';
 }
}
function Expand(id)
{

 if(parseInt(document.getElementById("DirectionImage"+id).style.height) != parseInt(Amount))
 {
 document.getElementById("MapImage"+id).style.height = (parseInt(document.getElementById("MapImage"+id).style.height) + MoveAmount) + 'px'
 document.getElementById("DirectionImage"+id).style.height = (parseInt(document.getElementById("DirectionImage"+id).style.height) + MoveAmount) + 'px'
 setTimeout("Expand("+id+")",1)
 }
}
function SelectRoute(Type,Lat,Lon,Description)
{
    RouteLat = Lat;
    RouteLon = Lon;
    RouteLocation = Description;
    document.getElementById("ResultsDiv").innerHTML ="";
    if(Type == "RouteTo")
    {
        document.getElementById("RouteHeading").innerHTML = "Route To:";
        RouteType = "To";
    }
    else
    {
        RouteType = "From";
        document.getElementById("RouteHeading").innerHTML = "Route From:";
    }
    sDescription =  Description;
    document.getElementById("SelectedPoint").innerHTML = Description;
    document.getElementById("SelectedRoute").style.display = '';
    document.getElementById("txtSearchAddress").value = "";
}
function ShowStaticMap()
{
   
 var centroid;
 centroid = g_map.getCentre();
 window.open("http://maps.afrigis.co.za/sm/StaticMapWizard.aspx?latitude="+centroid.latitude()+"&longitude="+centroid.longitude()+"&scaleindex="+g_map.getZoomLevel()+"&zoomno=5","","resizable=yes,scrollbars=yes,top=0,left=0,width=700,height=700");
 //centroid = g_map.GetMapCentroid();
 //window.open("http://maps.afrigis.co.za/sm/StaticMapWizard.aspx?latitude="+centroid.latitude+"&longitude="+centroid.longitude+"&scaleindex="+g_map.GetScale()+"&zoomno=5","","resizable=yes,scrollbars=yes,top=0,left=0,width=700,height=700");

 
}
function ShowPoint(Lat,Lon,Name)
{
    if(RouteLat == '')
    {
        RouteLat = Lat;
        RouteLon = Lon;
    }
    //g_map.RemoveAllObjects();
    g_map.removeGroupOverlay("Point");
    sDescription = Name;
    var oLatLng = new AGCoord(parseFloat(Lat),parseFloat(Lon));
    g_map.centreAndScale(oLatLng, 18);
    //g_map.AddPoint("Images/Pin_Red_32x32_24bit.png", "1", parseFloat(Lat),parseFloat(Lon),-5,-32,"Search Result",Name);    
    var oIcon = new AGIcon();
    oIcon.image = "Images/Pin_Red_32x32_24bit.png";
    //oIcon.iconSize = new AGSize(31, 32);
    oIcon.iconAnchor = new AGPoint(-5, -32);
    var oNewMarkerOptions = new AGMarkerOptions(oIcon);
    g_map.addOverlay(new AGMarker(oLatLng, oNewMarkerOptions), "Point");
}
function NoPoint(Lat,Lon,Name)
{
    if(RouteLat == '')
    {
        RouteLat = Lat;
        RouteLon = Lon;
    }
    //g_map.RemoveAllObjects();
    g_map.removeGroupOverlay("Point");
    sDescription = Name;
    var oLatLng = new AGCoord(parseFloat(Lat),parseFloat(Lon));
    g_map.centreAndScale(oLatLng, 18);
    //g_map.AddPoint("Images/Pin_Red_32x32_24bit.png", "1", parseFloat(Lat),parseFloat(Lon),-5,-32,"Search Result",Name);    

}
function AddressSearchJSONBusinessLocation(Business,Type,BoundingBox,Location)
{
            var url = jsonpUrl +"?SearchString="+Business+"&Location="+Location+"&bbox="+BoundingBox+"&Type="+Type;
            var Callback = "callbackFunction";
            var name = "callbackFunction";
            var query = "";
            jsonp(url,Callback,name,query);            
}

function AddressSearchJSONAddress(Address, Type) {

    var url = "GenericLuceneSearch.aspx?SearchText=" + Address + "&jsonp=callbackFunction";
    var Callback = "callbackFunction";
    var name = "callbackFunction";
    var query = "";
    jsonp(url, Callback, name, query);
}
function AddressSearchJSONBusiness(Business, Type, BoundingBox) {
    var url = jsonpUrl + "?SearchString=" + Business + "&bbox=" + BoundingBox + "&Type=" + Type + "&jsonp=callbackFunction";
    var Callback = "callbackFunction";
    var name = "callbackFunction";
    var query = "";
    jsonp(url, Callback, name, query);
}
 
 function jsonp(url,callback,name, query)
{                
            if (url.indexOf("?") > -1)
                url += "&jsonp=" 
            else
                url += "?jsonp="; 
                url += name + "&";
            if (query)
                url += encodeURIComponent(query) + "&";   
                url += new Date().getTime().toString(); // prevent caching        
                var script = document.createElement("script");        
                script.setAttribute("src",url);
                script.setAttribute("type","text/javascript");                
                document.body.appendChild(script);
}       
var FORMAT = "image/png";
var VERSION = "1.0.0" ;
var CRS = "EPSG:4326" ;
var EXCEPTION = "INIMAGE";
var IMAGEOFFSETX = 0;
var IMAGEOFFSETY = 0;

var BBOX_TAG = "&BBOX"
var CRS_TAG = "&CRS"
var EXCEPTIONS_TAG = "&EXCEPTIONS"
var FORMAT_TAG = "&FORMAT"
var HEIGHT_TAG = "&HEIGHT"
var LAYERS_TAG = "&LAYERS"
var REQUEST_TAG = "REQUEST"
var STYLES_TAG = "&STYLES"
var TILECOLUMN_TAG = "&TILECOLUMN"
var TILEROW_TAG = "&TILEROW"
var TOKEN_TAG = "&TOKEN"
var VERSION_TAG = "&VERSION"
var WIDTH_TAG = "&WIDTH"
var ROUTING_TAG = "&ROUTING</>"

     
   var g_RequestManager = null;
   var g_TravelDirections = null;
   
   var m_Layers;
   var m_Styles;
   var m_RoutableParameter;
   var m_RoutableLayer;
   var m_MapServerUrl;
     
function DirectionItem()
{
	this.m_strDescripTion = "";
	this.m_strIconUrl = "";
	this.m_dLatitude = 0;
	this.m_dLongitude = 0;
    this.m_ptStart = new Point(0,0);
    this.m_ptEnd = new Point(0,0);
}
           
    function InitTravelDirections()
    {
//       m_MapServerUrl = "http://196.28.152.158/MapServerGateway/IISGateway.aspx";
//       m_Layers = "AG_OCEANS,AG_SADECS,AG_PROVINCES,AG_NATIONALROAD_LABELS,AG_TOWNS,AG_TOWNS_CENTROID,AG_SUBURBS,AG_STREETS,AG_CAD_PARKS,AG_AIRPORTS";
//       m_Styles = "Mapstyle2,Mapstyle2,Mapstyle1,Point_SCHEME,Mapstyle2,Point_SCHEME,Mapstyle2,Mapstyle3,Mapstyle2,Point_SCHEME";
//       m_RoutableLayer = "AG_STREETS";
//       m_RoutableParameter = "TRAVELTIME";
       
       m_MapServerUrl = "http://maps.afrigis.co.za/GW/IISGateway.aspx";
       m_Layers = "AG_OCEANS,AG_SADECS,AG_PROVINCES,AG_NATIONALROAD_LABELS,AG_TOWNS,AG_TOWNS_CENTROID,AG_SUBURBS,AG_STREETS,AG_CAD_PARKS,AG_AIRPORTS";
       m_Styles = "Mapstyle2,Mapstyle2,Mapstyle1,Point_SCHEME,Mapstyle2,Point_SCHEME,Mapstyle2,Mapstyle3,Mapstyle2,Point_SCHEME";
       m_RoutableLayer = "AG_STREETS";
       m_RoutableParameter = "TRAVELTIME";
       
        g_RequestManager = new ThumbNailRequestManager(m_MapServerUrl, VERSION, CRS, FORMAT, m_Layers, m_Styles, EXCEPTION);
        g_TravelDirections = new TravelDirections(m_MapServerUrl, m_RoutableLayer, m_RoutableParameter);
        
    }
      
    function getXmlFromServer(str, fnc)
    {
        ShowResultBarLoadingWidget();
        var url="TravelDirections/GetFromMapServer.aspx";
        url=url+"?source=|"+str;
        url=url+"|&sid="+Math.random();
        getUsingAjax(url, fnc);                        
    }
    
   function ShowResultBarLoadingWidget()
	{
		document.getElementById("ResultBarLoadingWidget").style.display='block';
	}
	function HideResultBarLoadingWidget()
	{
		document.getElementById("ResultBarLoadingWidget").style.display='none';
	}

    function ShowFlyOut()
    {
      var amount = 5;
      if(parseInt(document.getElementById("RouteToFromLocationInput").style.height) != 145)
        {
          if(parseInt(document.getElementById("RouteToFromLocationInput").style.height) == 15) 
             {
                document.getElementById("FlyOutHeading").style.display='';
             }
           if(parseInt(document.getElementById("RouteToFromLocationInput").style.height) == 40) 
             {
                document.getElementById("lblStreetAdd1").style.display='';
             }
           if(parseInt(document.getElementById("RouteToFromLocationInput").style.height) == 65) 
             {
                document.getElementById("inputAddr").style.display='';
             }
            if(parseInt(document.getElementById("RouteToFromLocationInput").style.height) == 80) 
             {
                document.getElementById("lblStreetAdd2").style.display='';
             }
            if(parseInt(document.getElementById("RouteToFromLocationInput").style.height) == 105) 
             {
                document.getElementById("inputTown").style.display='';
             }
            if(parseInt(document.getElementById("RouteToFromLocationInput").style.height) == 135) 
             {
                document.getElementById("btnSubmitLocationRouteSearch").style.display='';
             }       
          document.getElementById("RouteToFromLocationInput").style.height = (parseInt(document.getElementById("RouteToFromLocationInput").style.height) + amount) + 'px'
          setTimeout("ShowFlyOut()",1) 
        }   
    }

function ThumbNailRequestManager( _mapServerUrl, _version, _crs, _format, _layers, _styles, _exceptions)
{
    this.mapServerUrl = _mapServerUrl;
    this.version = _version;
    this.crs = _crs;
    this.format = _format;
    this.layers = _layers;
    this.styles = _styles;
    this.exceptions = _exceptions;
    
    this.getThumbnailRequest = function (BBox, iWidth, iHeight)
    {
        var req = this.mapServerUrl;
        req += "?";
        req += REQUEST_TAG + "=GetMapAG";
        req += VERSION_TAG + "=" + this.version;
        req += CRS_TAG + "=" + this.crs;
        req += BBOX_TAG + "=";
        req += BBox;
        req += WIDTH_TAG + "=" + iWidth;
        req += HEIGHT_TAG + "=" + iHeight;
        req += FORMAT_TAG + "=" + this.format;
        req += LAYERS_TAG + "=" + this.layers;
        req += STYLES_TAG + "=" + this.styles;
        req += EXCEPTIONS_TAG + "=" + this.exceptions;
        
        return req;
    }    
}  

function TravelDirections(strMapServerUrl, strRouteLayer, strRouteParam)
{
	this.m_strMapServerUrl = strMapServerUrl;
	this.m_strRouteLayer = strRouteLayer;
	this.m_strRouteParam = strRouteParam;
	this.m_dTotalDist = -1;
    this.m_dTotalTravelTime = -1;
	this.m_arrDirectionItem = new Array();
	this.m_arrNode = new Array();
	
	this.addNode = function( obMapSearchItem)
	{
		this.m_arrNode[this.m_arrNode.length] = obMapSearchItem;
	}

	this.clearNodes = function()
	{
		this.m_arrNode = new Array();
	}	

    this.getDirections = function(callBackFunc)
	{
	    directionItemCallBack = callBackFunc;
		var strReq = this.getDDRequestString();
		getXmlFromServer(strReq, callBackParseDrivingDirection);
	}

 
	this.getThumbnailMap = function(dirItem, iWidth, iHeight)
	{
	    var segDist = GetDistanceGC(dirItem.m_ptStart, dirItem.m_ptEnd)
	    
        var long1 = (dirItem.m_ptStart.x <= dirItem.m_ptEnd.x)? dirItem.m_ptStart.x : dirItem.m_ptEnd.x;
        var long2 = (dirItem.m_ptStart.x >= dirItem.m_ptEnd.x)? dirItem.m_ptStart.x : dirItem.m_ptEnd.x;
        var lat1 = (dirItem.m_ptStart.y <= dirItem.m_ptEnd.y)? dirItem.m_ptStart.y : dirItem.m_ptEnd.y;
        var lat2 = (dirItem.m_ptStart.y >= dirItem.m_ptEnd.y)? dirItem.m_ptStart.y : dirItem.m_ptEnd.y;
        
        var dLong = long2 - long1;        
        var dLat = lat2 - lat1;
        
        
        //Determine how much the thumbnail must zoom out from the route
        var fZoomFactor = 1.5;
        if (segDist < 0.1) //Smaller than 100 meter
        {
            fZoomFactor = 5.5;
        }
        
        
        dLat = dLat * fZoomFactor;
	    dLong = dLong * fZoomFactor;
	    
	    
	    long1 -= dLong/2;
	    long2 += dLong/2;
	    
	    lat1 -= dLat/2;
	    lat2 += dLat/2;
	    
	    var strThumbnailBBox = long1 + "," + lat1 + "," + long2 + "," + lat2;
	    
	    var strReq = g_RequestManager.getThumbnailRequest(strThumbnailBBox, iWidth, iHeight);
	    
        // Add routing Param;
		strReq += "&ROUTING=" + this.m_strRouteLayer + "$" + this.m_strRouteParam + "$";
		
		for (var i= 0; i < this.m_arrNode.length; i++)
		{
		    strReq += "LATLONG," + this.m_arrNode[i].Longitude + "," + this.m_arrNode[i].Latitude + "^";
		}
		strReq = strReq.substring(0, strReq.length-1);

		return strReq;
	}	
	
	this.getDDRequestString = function()
	{
		if (this.m_arrNode.length < 2)
			return "";

		var strReq = this.m_strMapServerUrl;
		strReq += "?REQUEST=GetRouteAG";
		strReq += "&VERSION=1.0.0";
		strReq += "&ROUTING=" + this.m_strRouteLayer + "$" + this.m_strRouteParam + "$";

		var strNodes = ""
		for (var i = 0; i < this.m_arrNode.length; i++ )
		{
			strNodes += "LATLONG," + this.m_arrNode[i].Longitude + "," + this.m_arrNode[i].Latitude + "^";
		}

		strNodes = strNodes.substring(0,(strNodes.length-1));

		strReq += strNodes;

		return strReq;
	}
}

var directionItemCallBack = null;

function callBackParseDrivingDirection(xmlDrivingDirection)
{
	// Parse the xml got from server
	var xmlDoc = xmlDrivingDirection.documentElement;
	var root_node = xmlDoc.getElementsByTagName('RoutingPath').item(0);
	
	var roadCount = root_node.childNodes.length;
	var CumilitiveLength = 0;
	
	// Clear the Direction Item
	g_TravelDirections.m_arrDirectionItem = new Array();
	
	for(var i =0; i<roadCount; i++)
	{
	    var dirItem = new DirectionItem();
	    
	    var roadNode = root_node.childNodes[i];
	    var desc, angle;
	    var ptStart = new Point(0,0);
	    var ptEnd = new Point(0,0);
	    	    
		var Length = 0;
		var Name = "";
		var AbsoluteDirection = "";
		var RelativeDirectionAngle = "";
   
	    for(var j=0; j<roadNode.childNodes.length; j++)
	    {
	        var childNode = roadNode.childNodes[j];
	        if (!childNode.firstChild || childNode.firstChild == null)
	        {
	            //alert(childNode.tagName + "::Value Not Found")
	            continue;
	        }
	            
	        switch(childNode.tagName)
	        {
	            case "starting_point":
	                ptStart.x = parseFloat(childNode.childNodes[0].firstChild.data);
	                ptStart.y = parseFloat(childNode.childNodes[1].firstChild.data);
	                break;
	            
	            case "ending_point":
	                ptEnd.x = parseFloat(childNode.childNodes[0].firstChild.data);
	                ptEnd.y = parseFloat(childNode.childNodes[1].firstChild.data);
	                break;

	            case "abs_dir":
	                AbsoluteDirection = childNode.firstChild.data;
	                break;
	                
	            case "rel_dir_angle":
	                RelativeDirectionAngle = parseFloat(childNode.firstChild.data);
	                break;
	                	                
	            case "name":
	                Name = childNode.firstChild.data;
	                break;	                	        
	                
	            case "length":
	                Length = parseFloat(childNode.firstChild.data);
	                break;
	                
	            case "cum_length":
	                CumilitiveLength = parseFloat(childNode.firstChild.data);
	                break;
	                
	        }
	    }
	    
        var ob = getDirDescAndIcon(i, RelativeDirectionAngle, roadCount);
        
        var directionString = ob.description;
        		
	    directionString += ",continue ";
		directionString += AbsoluteDirection + " ";
		directionString += "on ";
		directionString += Name + ", ";					
		directionString += "drive for ";
		directionString += Length + " km";
		directionString += " (" + CumilitiveLength + " km)";
		
		if(i == roadCount-1)
		    directionString += ",Stop.";
	    
	    dirItem.m_strDescripTion = directionString;
	    dirItem.m_ptStart = ptStart;
	    dirItem.m_ptEnd = ptEnd;
	    dirItem.m_strIconUrl = "TravelDirections/mapDirIcons/" + arrDirImageFile[ob.iconIndex];
	    dirItem.m_dLongitude = parseFloat((ptEnd.x + ptStart.x)/2) ;
	    dirItem.m_dLatitude = parseFloat((ptEnd.y + ptStart.y)/2)  ;
	    
	    g_TravelDirections.m_arrDirectionItem[g_TravelDirections.m_arrDirectionItem.length] = dirItem;
	    
        //Clear all the param;   
	    Length = 0;
		Name = "";
		AbsoluteDirection = "";
		RelativeDirectionAngle = "";
		//====================
	}
	
	g_TravelDirections.m_dTotalDist = CumilitiveLength;
	   
    
    HideResultBarLoadingWidget();
    directionItemCallBack();
}

var arrDirImageFile = new Array("072_Go_16x16.jpg",
					        "071_Stop_16x16.jpg",
      					    "032_DeviateLeft_16x16.jpg",
					        "022_SoftLeft_16x16.jpg",
      					    "031_SharpLeft_16x16.jpg",
     					    "032_VerySharpLeft_16x16.jpg",
      					    "051_UturnLeft_16x16.jpg",
      					    "032_DeviateRight_16x16.jpg",
      					    "021_SoftRight_16x16.jpg",
      					    "032_SharpRight_16x16.jpg",
      					    "032_VerySharpRight_16x16.jpg",
      					    "052_UturnRight_16x16.jpg"
      					);




function getDirDescAndIcon(dirItemIndex, angle, roadCount)
{
    var directionString = "";
    var directionIconIndex;
    roadCount = parseInt(roadCount,10);
    dirItemIndex = parseInt(dirItemIndex,10);
    if(dirItemIndex == 0)
    {
	    directionString += "Start";
	    directionIconIndex = 0;
    }

    else
    {
        directionIconIndex = 2;
	    var dir;
    	
	    if(angle < 0 )
	    {
		    dir = "right"; 	
		    angle = -angle;
		    directionIconIndex += 5;
	    } 
	    else
	    {
		    dir = "left";
	    }
    	
	    if( angle >= 0 && angle <= 23 )
	    {
		    directionString += "Deviate Slightly to the";
		    directionIconIndex += 0;
	    }
	    else if( angle > 23 && angle <= 45 )
	    {
		    directionString += "Turn Slightly to the" ;					
		    directionIconIndex += 1;
	    }
	    else if( angle > 45 && angle <= 100 )
	    {
		    directionString += "Turn to the" ;					
		    directionIconIndex += 2;
	    }
	    else if( angle > 100 && angle < 160 )
	    {
		    directionString += "Turn Sharply to the" ;					
		    directionIconIndex += 3;
	    }
	    else if( angle >= 160)
	    {
		    directionString += "Hairpin turn to the" ;					
		    directionIconIndex += 4;
	    }
    	
	    directionString += " " + dir ;
	    
	    if(dirItemIndex == (roadCount - 1))
	        directionIconIndex = 1;
    }	    
    
    return {description:directionString, iconIndex:directionIconIndex};    
}


    var R = 6371; // earth's mean radius in km
    
    /// <summary>
    /// Calculates the Great Circle distance between two coordinates in Kilometers
    /// </summary>
    /// <param name="fLat1"></param>
    /// <param name="fLong1"></param>
    /// <param name="fLat2"></param>
    /// <param name="fLong2"></param>
    /// <returns></returns>
    function GetDistanceGC(Coordinate1, Coordinate2)
    {
        //Convert the Decimal Degrees to radians
        var radLat1 = DecDegrees2RadDegrees(Coordinate1.y);
        var radLon1 = DecDegrees2RadDegrees(Coordinate1.x);
        var radLat2 = DecDegrees2RadDegrees(Coordinate2.y);
        var radLon2 = DecDegrees2RadDegrees(Coordinate2.x);

        var dLat = radLat2 - radLat1;
        var dLong = radLon2 - radLon1;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c;
        return d;
    }
    
    function DecDegrees2RadDegrees(DecDegree)
    {
        return DecDegree * Math.PI / 180;
    }
