﻿var oDirection = null;
var g_RoutePreference = "TRAVELTIME";


function GetXmlHttpObject()
{

    var xmlHttp=null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

//============== Handle the redirect of page to RouteFinder page when user click om map to get directions =================
function GetRedirectRoutePoints()
{

    var LatFrom = g_map._dd._u[0].latitude();
    var LonFrom = g_map._dd._u[0].longitude();
    var LatTo = g_map._dd._u[1].latitude();
    var LonTo = g_map._dd._u[1].longitude();
   
    var points, strPoints;
//  var oDirection = new AGDirections(null,null);

//    //points = g_map.DrivingDirections.GetPoints();
    strPoints = LatFrom + ";" + LonFrom+";"+LatTo + ";" + LonTo;
    centerLat = (LatFrom + LatTo) /2;
    centerLon = (LonFrom + LonTo) /2;
    var startCoord = new AGCoord(LatFrom,LonFrom);
    var endCoord = new AGCoord(LatTo,LonTo);
    var bb = new AGBoundingBox(startCoord, endCoord)
    var oCenterLatLng = new AGCoord(parseFloat(centerLat),parseFloat(centerLon));
    var scaleIndex = g_map.getBoundingBoxZoomLevel(bb);
    var CentreScale = oCenterLatLng.latitude() + ", " + oCenterLatLng.longitude() + "," + scaleIndex;
    window.location = "RouteFinder.aspx?Direction=Route&Point=" +  strPoints + "&CentreScale=" + CentreScale ;
    
    
    //RedirectToRoutePlanning(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;
//    
    
    
    
     
}

function RedirectToRoutePlanning(PointString)
{
    var centroid = g_map.GetMapCentroid();
    var scaleIndex =  g_map.GetScale();
    var CentreScale = centroid.latitude + ", " + centroid.longitude + "," + scaleIndex;
    window.location = "RouteFinder.aspx?Direction=Route&Point=" +  PointString + "&CentreScale=" + CentreScale ;
}
//=================================================================================================================


//============= This part handles the routing on the RouteFinder page
function GetRouteFromClick(coord)
{
    if (document.getElementById("rbTime").checked)
    {
        g_RoutePreference = "TRAVELTIME";
    }
    else
    {
       g_RoutePreference = "LENGTH"; 
    }
  div = document.getElementById("DivDirections");
  oDirection = new AGDirections(g_map, div);
  oDirection.load(coord[0], coord[1]);

//  var LatFrom = g_map._dd._u[0].latitude();
//  var LonFrom = g_map._dd._u[0].longitude();
//  var LatTo = g_map._dd._u[1].latitude();
//  var LonTo = g_map._dd._u[1].longitude();
  
  var LatFrom = coord[0].latitude();
  var LonFrom = coord[0].longitude();
  var LatTo = coord[1].latitude(); 
  var LonTo = coord[1].longitude();
   
  var strPoints;

    strPoints = LatFrom + ";" + LonFrom+";"+LatTo + ";" + LonTo;
    
    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;
        
        StartLat = Result[1];
        StartLon = Result[2];
        EndLat = Result[4];
        EndLon = Result[5];
        sDescription = Result[0];
        document.getElementById("divDSelected").innerHTML = "From : " + Result[0] + " To : " + Result[3];
        wayPoint = StartLat+"|"+StartLon+"$"+EndLat+"|"+EndLon;
        GetRouteDrivingDirections(wayPoint);
        DrawRouteStations();
    }

}

function GetRouteDrivingDirections(Waypoint)
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    
    var url = "AJAXGetDirections.aspx?Waypoints="+Waypoint+"&Preference=" + g_RoutePreference + "&num="+Math.random();
    xmlHttp.onreadystatechange=RecieveRouteDirections;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    
}
function RecieveRouteDirections()
{
    if (xmlHttp.readyState==4)
    {
       document.getElementById("DivDirections").innerHTML = "";
       document.getElementById("DivDirections").innerHTML = xmlHttp.responseText;
    }
}

//================================================================================
// Handle the station details
//================================================================================

function ShowHideProjectDetails(TrueFalse,StationID)
{
    editlat =  document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value;
    editlong = document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value;
    stationname = document.getElementById("ctl00_ContentPlaceHolder1_txtOutletName").value;
    stationid = document.getElementById("ctl00_ContentPlaceHolder1_hdfStationID").value;
    if (TrueFalse == "True")
    {
       
        ClearStationPanel();
        document.getElementById("ctl00_ContentPlaceHolder1_tblEdit").style.display = "";
        document.getElementById("ctl00_ContentPlaceHolder1_tblSearch").style.display = "none";
        document.getElementById("ctl00_ContentPlaceHolder1_hdfStationID").value = StationID;
        bSearch = false;
        GetStationDetails();
    }
    else
    {
        ClearSearchPanel();
        document.getElementById("ctl00_ContentPlaceHolder1_tblSearch").style.display = "";
        document.getElementById("ctl00_ContentPlaceHolder1_tblEdit").style.display = "none";
        document.getElementById("ctl00_ContentPlaceHolder1_hdfStationID").value = "";
        //document.getElementById("lblDatabaseResult").innerHTML = "";
        bSearch = true;
        
        var oLatLng = new AGCoord(parseFloat(editlat),parseFloat(editlong));
        var oIcon = new AGIcon();
        oIcon.image = "Images/Pin_Total_32x32_24bit.png";
        var Browser = {
                            Version: function() {
                                var version = 999; // we assume a sane browser
                                if (navigator.appVersion.indexOf("MSIE") != -1)
                                  version = parseFloat(navigator.appVersion.split("MSIE")[1]);
                                return version;
                              }
                            }
                            
        if (Browser.Version() >= 7) {
            oIcon.shadow = "Images/transparent.gif";
        }
        //oIcon.shadow = "Images/transparent.gif";
        oIcon.iconAnchor = new AGPoint(-5, -32);
        oIcon.maxHeight = 32;
        oIcon.iconSize.height =  25;
        oIcon.iconSize.width =  25;
        var oNewMarkerOptions = new AGMarkerOptions(oIcon);
        marker = new AGMarker(oLatLng, oNewMarkerOptions);
        g_map.addOverlay(marker, "Point");
        
        infodisplay = new AGInfoDisplayOptions();
        infodisplay.height = 150;
        infodisplay.width = 150;
        pointObj = document.createElement("div");
        pointObj.innerHTML = "<table><tr><td><img src='images/Pin_Total_16x16_24bit.gif'/></td><td style='v-align:center'><strong>Service Station<strong></td></tr></table>"+
                          stationname+"<br/><br/><a href='#' onclick='ShowHideProjectDetails(\"True\",\"" + stationid + "\")'>Edit Details</a><br/><br/>";
        marker.bindInfoDisplay(pointObj, infodisplay);
        
        
        //g_map.AddPoint("Images/Pin_Total_32x32_8bit.png","img1", parseFloat(editlat),parseFloat(editlong),-5,-32,
        //                            "<table><tr><td><img src='images/logoSmall.gif'/></td><td style='v-align:center'><strong>Service Station<strong></td></tr></table>",
        //                            stationname+"<br/><br/><a href='#' onclick='ShowHideProjectDetails(\"True\",\"" + stationid + "\")'>Edit Details</a><br/><br/>");
    }
    document.getElementById("ToFromNavigation").style.display = "none";
    document.getElementById("lblUpdateMessage").innerHTML = "";
    
}

function GetStationDetails()
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    sStationID = document.getElementById("ctl00_ContentPlaceHolder1_hdfStationID").value ; 
    var url = "AjaxHandleAdmin.aspx?type=getStation&stationID="+sStationID + "&num=" + Math.random();
    xmlHttp.onreadystatechange=RecieveStationDetailsResults;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}
         
 function RecieveStationDetailsResults()
 {
     if (xmlHttp.readyState == 4)
    {
        var arr_received = xmlHttp.responseText;
        var StationList = arr_received.split("|");
         
        for(var i = 0; i < StationList.length; i++)
        {
            var StationServices = StationList[i].split("~");
            var StationDetails = StationServices[0].split(";");// StationList[i].split(";");
            var Services = StationServices[1].split(":");
           
           document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value = StationDetails[2];
           document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value = StationDetails[1];
           document.getElementById("ctl00_ContentPlaceHolder1_txtStatus").value = StationDetails[3];
           document.getElementById("ctl00_ContentPlaceHolder1_txtOutletName").value = StationDetails[4];
           document.getElementById("ctl00_ContentPlaceHolder1_txtOutletNumber").value = StationDetails[5];
           document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd1").value = StationDetails[6];
           document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd2").value = StationDetails[7];
           document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd3").value = StationDetails[8];
           document.getElementById("ctl00_ContentPlaceHolder1_txtPostCode").value = StationDetails[9];
           document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd1").value = StationDetails[10];
           document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd2").value = StationDetails[11];
           document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd3").value = StationDetails[12];
           document.getElementById("ctl00_ContentPlaceHolder1_txtTelNo").value = StationDetails[13];
           document.getElementById("ctl00_ContentPlaceHolder1_txtFaxNo").value = StationDetails[14];
           document.getElementById("ctl00_ContentPlaceHolder1_txtEMail").value = StationDetails[15];
           document.getElementById("ctl00_ContentPlaceHolder1_txtContactPerson").value = StationDetails[16];
           document.getElementById("ctl00_ContentPlaceHolder1_txtDepotCode").value = StationDetails[17];
           
//           if (StationDetails[18] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chk24").checked = true;
//           if (StationDetails[19] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkshop").checked = true;
//           if (StationDetails[20] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkworkshop").checked = true;
//           if (StationDetails[21] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkgas").checked = true;
//           if (StationDetails[22] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkroute").checked = true;
//           if (StationDetails[23] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkSteers").checked = true;
//           if (StationDetails[24] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkCarWash").checked = true;
//           if (StationDetails[25] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkInternet").checked = true;
//           if (StationDetails[26] == 'True') document.getElementById("ctl00_ContentPlaceHolder1_chkIsis").checked = true;

            iNumRows = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows.length;
            for (var j = 0; j <  iNumRows; j++)
            {
                iNumCells = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows[j].cells.length;
                for (var l = 0; l < iNumCells; l++)
                {
                    cellElement = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows[j].cells[l];
                    ServID = cellElement.firstChild.getAttribute("ServiceID");
                    
                    for (var k = 0; k < Services.length; k++)
                    {
                        ServiceDetails = Services[k].split(";");
                        ID = ServiceDetails[0];
                        if (ID == ServID)
                        {
                            cellElement.firstChild.firstChild.checked = true;
                        }
                    }
                
                }
            }
           
            var Lat = parseFloat(StationDetails[2]);
            var Lon = parseFloat(StationDetails[1]);
            
            var oLatLng = new AGCoord(Lat,Lon);
            var oIcon = new AGIcon();
            oIcon.image = "Images/Pin_Total_32x32_24bit.png";
            var Browser = {
                            Version: function() {
                                var version = 999; // we assume a sane browser
                                if (navigator.appVersion.indexOf("MSIE") != -1)
                                  version = parseFloat(navigator.appVersion.split("MSIE")[1]);
                                return version;
                              }
                            }
                            
            if (Browser.Version() >= 7) {
                oIcon.shadow = "Images/transparent.gif";
            }
            //oIcon.shadow = "Images/transparent.gif";
            oIcon.iconAnchor = new AGPoint(-5, -32);
            oIcon.maxHeight = 32;
            oIcon.iconSize.height =  25;
            oIcon.iconSize.width =  25;
            var oNewMarkerOptions = new AGMarkerOptions(oIcon);
            oNewMarkerOptions.draggable = true;
            oDragMarker = new AGMarker(oLatLng, oNewMarkerOptions);
            g_map.addOverlay(oDragMarker, "Point");
            AGEvent.addListener(oDragMarker, "onmouseup", SetDragLatLong);
            
            
            //var icon1 = new DraggableIcon("Images/Pin_Total_32x32_24bit.png","oDrag");
            //g_map.AddDraggableIcon(icon1,Lat,Lon,-5,-32,"DragIcon","Drag icon to exact location of Total Filling Station");
            document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value = Lat;
            document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value = Lon;
            if(navigator.appName == "Microsoft Internet Explorer")
            {
                // IE
                //document.getElementById("oDrag").attachEvent("onmouseup", SetDragLatLong);
            } 
            else 
            { 
             // Mozilla, Netscape, Firefox
                //var el = document.getElementById("oDrag"); 
                //el.addEventListener("mouseup", SetDragLatLong, false);
            }
        }
     }
 }
 
 
 function UpdateStationDetails()
 {
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var sDetails = StationDetailsString();
    SetServiceDetailString();
     var url = "AjaxHandleAdmin.aspx?type=updateStation&stationDetails="+sDetails + "&Services=" + CheckedServiceID + "&num=" + Math.random();
    xmlHttp.onreadystatechange=ReceiveStationUpdateResults;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
 
 }
 
 
 function ReceiveStationUpdateResults()
 {
 
    if (xmlHttp.readyState==4)
    {
       var sResult = xmlHttp.responseText;
       switch (sResult)
       {
            case "Success" :
                document.getElementById("lblDatabaseResult").innerHTML = "Record successfully updated";
                document.getElementById("lblUpdateMessage").innerHTML = "Record successfully updated";
                break;
                
            case "Failed" :
                document.getElementById("lblDatabaseResult").innerHTML = "Failed to update record - please retry";
                document.getElementById("lblUpdateMessage").innerHTML = "Failed to update record - please retry";
                break;
       
       
       }
       if (bIsAdmin == true)
       {
            ShowHideProjectDetails('False');
       }
    }
 
 }
 
 
 function SetServiceDetailString()
 {
    iNumRows = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows.length;
    CheckedServiceID = "";
    for (var i = 0; i <  iNumRows; i++)
    {
        iNumCells = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows[i].cells.length;
        for (var j = 0; j < iNumCells; j++)
        {
            cellElement = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows[i].cells[j];
//            var inner = cellElement.innerHTML;
//            var iIndex = inner.indexOf("CHECKED")
            if (cellElement.firstChild.firstChild.checked == true)
            {
                CheckedServiceID += cellElement.firstChild.getAttribute("ServiceID") + ";";
            }    
        }
    }
 }
 
 
 function StationDetailsString()
 {
    var StationDetails = "";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_hdfStationID").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtStatus").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtOutletName").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtOutletNumber").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd1").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd2").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd3").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtPostCode").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd1").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd2").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd3").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtTelNo").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtFaxNo").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtEMail").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtContactPerson").value + ";";
    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtDepotCode").value + ";";
    
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chk24").checked + ";";
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkshop").checked + ";";
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkworkshop").checked + ";";
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkgas").checked + ";";
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkroute").checked + ";";
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkSteers").checked + ";";
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkCarWash").checked + ";";
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkInternet").checked; 
//    StationDetails += document.getElementById("ctl00_ContentPlaceHolder1_chkIsis").checked; 
 
    return StationDetails;
 }
 
 
 function AddStationPanel(TrueFalse, Lat, Lon)
 {
    
    if (TrueFalse == "True")
    {
        ClearStationPanel();
        document.getElementById("tblEdit").style.display = "";
        document.getElementById("tblSearch").style.display = "none";
        var LatLonArray = document.getElementById("ctl00_ContentPlaceHolder1_hdfCoordinates").value
        if (LatLonArray)
        {
            var LatLon = LatLonArray.split("|");
            var Lat = parseFloat(LatLon[0]);
            var Lon = parseFloat(LatLon[1]);
            
            
            var oLatLng = new AGCoord(Lat,Lon);
            var oIcon = new AGIcon();
            oIcon.image = "Images/Pin_Total_32x32_24bit.png";
            var Browser = {
                            Version: function() {
                                var version = 999; // we assume a sane browser
                                if (navigator.appVersion.indexOf("MSIE") != -1)
                                  version = parseFloat(navigator.appVersion.split("MSIE")[1]);
                                return version;
                              }
                            }
                            
            if (Browser.Version() >= 7) {
                oIcon.shadow = "Images/transparent.gif";
            }
            //oIcon.shadow = "Images/transparent.gif";
            oIcon.iconAnchor = new AGPoint(-5, -32);
            oIcon.maxHeight = 32;
            oIcon.iconSize.height =  25;
            oIcon.iconSize.width =  25;
            var oNewMarkerOptions = new AGMarkerOptions(oIcon);
            oNewMarkerOptions.draggable = true;
            oDragMarker = new AGMarker(oLatLng, oNewMarkerOptions);
            g_map.addOverlay(oDragMarker, "Point");
            AGEvent.addListener(oDragMarker, "onmouseup", SetDragLatLong);
            
            
            //var icon1 = new DraggableIcon("Images/Pin_Total_32x32_24bit.png","oDrag");
            //g_map.AddObject(icon1,Lat,Lon,-5,-32,"");
            //g_map.AddDraggableIcon(icon1,Lat,Lon,-5,-32,"DragIcon","Drag icon to exact location of Total Filling Station");
            document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value = Lat;
            document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value = Lon;
            //document.getElementById("oDrag").onmouseup = testmouseup(event);
          
            if(navigator.appName == "Microsoft Internet Explorer")
            {
                // IE
                //document.getElementById("oDrag").attachEvent("onmouseup", SetDragLatLong);
            } 
            else 
            { 
             // Mozilla, Netscape, Firefox
               //var el = document.getElementById("oDrag"); 
               //el.addEventListener("mouseup", SetDragLatLong, false);
            }
        }
    }
    else
    {
        ClearSearchPanel();
        document.getElementById("tblSearch").style.display = "";
        document.getElementById("tblEdit").style.display = "none";
        
    }
}


function SetDragLatLong()
{
    coord = oDragMarker.getCoord();
    //document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value = document.getElementById("oDrag").Lat;
    //document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value = document.getElementById("oDrag").Long;
    document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value = coord.latitude();
    document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value = coord.longitude();
}


function ClearStationPanel()
{
    document.getElementById("ctl00_ContentPlaceHolder1_txtLatitude").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtLongitude").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtStatus").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtOutletName").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtOutletNumber").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd1").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd2").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtStreetAd3").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtPostCode").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd1").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd2").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtPostAd3").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtTelNo").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtFaxNo").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtEMail").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtContactPerson").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtDepotCode").value = "";

    ResetServices();
//    document.getElementById("ctl00_ContentPlaceHolder1_chk24").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkshop").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkworkshop").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkgas").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkroute").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkSteers").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkCarWash").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkInternet").checked = false;
//    document.getElementById("ctl00_ContentPlaceHolder1_chkIsis").checked = false;
    //g_map.RemoveAllObjects();
    g_map.removeOverlay();
    g_map.removeGroupOverlay("Point");
    
}


function ClearSearchPanel()
{
    document.getElementById("ctl00_ContentPlaceHolder1_txtSearchVal").value = "";
    document.getElementById("divDSelected").innerHTML ="";
    document.getElementById("divResults").innerHTML = "";
    document.getElementById("ToFromNavigation").style.display = "none";
    NumResults = 0;
    ResultPageSize = 6;
    CurPageIndex = 0;
    //g_map.RemoveAllObjects();
    g_map.removeOverlay();
    g_map.removeGroupOverlay("Point");
}


function InsertStationDetails()
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var sDetails = StationDetailsString();
    SetServiceDetailString();
    var url = "AjaxHandleAdmin.aspx?type=insertStation&stationDetails="+ sDetails + "&Services=" + CheckedServiceID + "&num=" + Math.random();
    xmlHttp.onreadystatechange=ReceiveStationInsertResults;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function ReceiveStationInsertResults()
{
    if (xmlHttp.readyState==4)
    {
       var sResult = xmlHttp.responseText;
       switch (sResult)
       {
            case "Success" :
                document.getElementById("lblDatabaseResult").innerHTML = "Record successfully added";
                //document.getElementById("lblDatabaseResult").style.display = "none";
                break;
                
            case "Failed" :
                document.getElementById("lblDatabaseResult").innerHTML = "Failed to add record - please retry";
                //document.getElementById("lblDatabaseResult").style.display = "none";
                break;
       }
       AddStationPanel('False');
    }
}


function DeleteStation()
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    sStationID = document.getElementById("ctl00_ContentPlaceHolder1_hdfStationID").value ; 
    var url = "AjaxHandleAdmin.aspx?type=deleteStation&stationID="+sStationID + "&num=" + Math.random();
    xmlHttp.onreadystatechange=RecieveStationDeleteResults;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function RecieveStationDeleteResults()
{
    if (xmlHttp.readyState==4)
    {
       var sResult = xmlHttp.responseText;
       switch (sResult)
       {
            case "Success" :
                document.getElementById("lblDatabaseResult").innerHTML = "Record successfully deleted";
                //document.getElementById("lblDatabaseResult").style.display = "none";
                break;
                
            case "Failed" :
                document.getElementById("lblDatabaseResult").innerHTML = "Failed to delete record - please retry";
                //document.getElementById("lblDatabaseResult").style.display = "none";
                break;
       
       
       }
       ShowHideProjectDetails('False');
       //g_map.RemoveAllObjects();
       g_map.removeOverlay();
       g_map.removeGroupOverlay("Point");
    }
}

function switchPanel(Panel)
{
    switch (Panel)
    {
        case "Edit" :
            window.location = "EditStation.aspx";
            break;
            
        case "Add" :
            window.location = "AddStation.aspx";
            break;
            
        case "Users" :
            window.location = "Services.aspx";
            break;
            
            case "Reports" :
            window.location = "Reports.aspx";
            break;
    }
}


function InsertUserDetails()
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var sDetails = UserDetailsString();
    var url = "AjaxHandleAdmin.aspx?type=insertService&Services="+sDetails + "&num=" + Math.random();
    xmlHttp.onreadystatechange=ReceiveServiceResults;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function InsertServiceDetails()
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var sDetails = ServiceDetailsString();
    var url = "AjaxHandleAdmin.aspx?type=insertService&Services="+sDetails + "&num=" + Math.random();
    xmlHttp.onreadystatechange=ReceiveServiceResults;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}

 function UpdateUserDetails()
 {
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var sDetails = UserDetailsString();
    if (sDetails != "")
    {
       
        if (document.getElementById("ctl00_ContentPlaceHolder1_hdUserID").value)
        {
            document.getElementById("divError").innerHTML = "Record successfully updated";
            var url = "AjaxHandleAdmin.aspx?type=updateUser&userDetails="+sDetails + "&num=" + Math.random();
            xmlHttp.onreadystatechange=ReceiveUserResults;
            xmlHttp.open("GET",url,true);
            xmlHttp.send(null);

        }
        else
        {
            InsertUserDetails();
        }
    }
    else
    {
        //document.getElementById("divError").style.display = "";
        document.getElementById("divError").innerHTML = "All fields must be completed.";
    
    }
 }
 
 
 function UpdateServiceDetails()
 {
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var sDetails = ServiceDetailsString();
    if (sDetails != "")
    {
       
        if (document.getElementById("ctl00_ContentPlaceHolder1_hdServiceID").value)
        {
            document.getElementById("divError").innerHTML = "Record successfully updated";
            var url = "AjaxHandleAdmin.aspx?type=updateService&Services="+sDetails + "&num=" + Math.random();
            xmlHttp.onreadystatechange=ReceiveServiceResults;
            xmlHttp.open("GET",url,true);
            xmlHttp.send(null);

        }
        else
        {
            InsertServiceDetails();
        }
    }
    else
    {
        //document.getElementById("divError").style.display = "";
        document.getElementById("divError").innerHTML = "All fields must be completed.";
    
    }
 }
 
 
 function ServiceDetailsString()
{
    var ServiceDetails = "";
    
    ServiceDetails += document.getElementById("ctl00_ContentPlaceHolder1_hdServiceID").value + ";";
    if (document.getElementById("ctl00_ContentPlaceHolder1_txtName").value != "")
    {
        ServiceDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtName").value + ";";
    }
     else
    {
        ServiceDetails = "";
        return ServiceDetails;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_hdCategoryID").value != "")
    {
        ServiceDetails += document.getElementById("ctl00_ContentPlaceHolder1_hdCategoryID").value + ";";
    }
     else
    {
        ServiceDetails = "";
        return ServiceDetails;
    }
 
    return ServiceDetails;
 }
 
 
 function DeleteUser()
 {
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    document.getElementById("divError").innerHTML = "Record successfully deleted";
    var sDetails = document.getElementById("ctl00_ContentPlaceHolder1_hdUserID").value;
    var url = "AjaxHandleAdmin.aspx?type=deleteUser&userID="+sDetails + "&num=" + Math.random();
    xmlHttp.onreadystatechange=ReceiveUserResults;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
 
 }


function ReceiveUserResults()
{
    if (xmlHttp.readyState==4)
    {
       var sResult = xmlHttp.responseText;
       
       switch (sResult)
       {
           
            case "Success" :
                
                if (document.getElementById("ctl00_ContentPlaceHolder1_hdUserID").value != "")
                {
                    ClearUser();
                    document.getElementById("divError").innerHTML = "Record successfully updated";
                }
                else
                {
                    ClearUser();
                    document.getElementById("divError").innerHTML = "Record successfully added";
                }
                break;
                
            case "Failed" :
                document.getElementById("divError").innerHTML = "Failed to update record - please retry";
                break;
       }
    }
}


function ReceiveServiceResults()
{
    if (xmlHttp.readyState==4)
    {
       var sResult = xmlHttp.responseText;
       
       switch (sResult)
       {
           
            case "Success" :
                
                if (document.getElementById("ctl00_ContentPlaceHolder1_hdServiceID").value != "")
                {
                    ClearService();
                    document.getElementById("divError").innerHTML = "Record successfully updated";
                }
                else
                {
                    ClearService();
                    document.getElementById("divError").innerHTML = "Record successfully added";
                }
                break;
                
            case "Failed" :
                document.getElementById("divError").innerHTML = "Failed to update record - please retry";
                break;
       }
    }
}



function UserDetailsString()
{
    var UserDetails = "";
    
    UserDetails += document.getElementById("ctl00_ContentPlaceHolder1_hdUserID").value + ";";
    if (document.getElementById("ctl00_ContentPlaceHolder1_txtName").value != "")
    {
        UserDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtName").value + ";";
    }
     else
    {
        UserDetails = "";
        return UserDetails;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_txtSurname").value != "")
    {
        UserDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtSurname").value + ";";
    }
     else
    {
        UserDetails = "";
        return UserDetails;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_txtUserName").value != "")
    {
        UserDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtUserName").value + ";";
    }
     else
    {
        UserDetails = "";
        return UserDetails;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_txtPassword").value != "")
    {
        UserDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtPassword").value + ";";
    }
     else
    {
        UserDetails = "";
        return UserDetails;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_hdStationID").value != "")
    {
        UserDetails += document.getElementById("ctl00_ContentPlaceHolder1_hdStationID").value + ";";
    }
     else
    {
        UserDetails = "";
        return UserDetails;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_txtUserFillStation").value != "")
    {
        UserDetails += document.getElementById("ctl00_ContentPlaceHolder1_txtUserFillStation").value;
    }
     else
    {
        UserDetails = "";
        return UserDetails;
    }
 
    return UserDetails;
 }
 
 
function ShowEmail()
{

    document.getElementById("Email").style.display = '';
}
function CloseEmail()
{
    document.getElementById("Email").style.display = 'none';
}


function SendEmail()
{
    var url
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    bbox = GetBBOX();
        //mapSize = g_map.GetSize(); 
        //centroid = g_map.GetMapCentroid();
        centroid = g_map.getCentre()
        centre = centroid.latitude() + "," + centroid.longitude();
        routedirection = document.getElementById("DivDirections");
    if(wayPoint != "")
    {
        arrTemp = wayPoint.split("$");
        arrFrom = arrTemp[0].split("|");
        arrTo = arrTemp[1].split("|");
        //bbox = g_map.GetBoundingBox();
//        bbox = GetBBOX();
//        //mapSize = g_map.GetSize(); 
//        //centroid = g_map.GetMapCentroid();
//        centroid = g_map.getCentre()
//        centre = centroid.latitude() + "," + centroid.longitude();
//        routedirection = document.getElementById("DivDirections");
        url  = "AjaxSendEmail.aspx?WayPoints=" + wayPoint+ "&centroid="+centre+"&BBox="+bbox+"&destinationcoords="+arrTo+"&origincoords="+arrFrom+"&EMailAddress="+document.getElementById("txtEmail").value+"&origindescription="+document.getElementById("StartDesc").innerHTML+"&destinationdescription="+document.getElementById("EndDesc").innerHTML+ "&Preference="+g_RoutePreference +"&num="+Math.random();
    }
    else
    {
    
        url  = "AjaxSendEmail.aspx?centroid="+centre+"&BBox="+bbox+"&destinationcoords=&origincoords="+RouteLat+"|"+RouteLon+"&EMailAddress="+document.getElementById("txtEmail").value+"&origindescription="+document.getElementById("StartDesc").innerHTML+"&destinationdescription=" +"&Preference="+g_RoutePreference + "&num="+Math.random();
    }
    xmlHttp.onreadystatechange=SendEmailAjax;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function SendEmailAjax()
{
    if (xmlHttp.readyState==4)
    {
       Result =xmlHttp.responseText;
       document.getElementById("txtEmail").value = "";
      CloseEmail();
       alert("Map Mailed");
    }
}


 
 function ShowSMS()
{

    document.getElementById("SMS").style.display = '';
}
function CloseSMS()
{
    document.getElementById("SMS").style.display = 'none';
}

function SendSMS()
{
    var url
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    if(wayPoint != "")
    {
        arrTemp = wayPoint.split("$");
        arrFrom = arrTemp[0].split("|");
        arrTo = arrTemp[1].split("|");
        url  = "AjaxSendSMS.aspx?destinationcoords="+arrTo+"&origincoords="+arrFrom+"&Number="+document.getElementById("txtCellNr").value+"&origindescription="+document.getElementById("StartDesc").innerHTML+"&destinationdescription="+document.getElementById("EndDesc").innerHTML+"&num="+Math.random();
    }
    else
    {
    
        url  = "AjaxSendSMS.aspx?destinationcoords=&origincoords="+RouteLat+"|"+RouteLon+"&Number="+document.getElementById("txtCellNr").value+"&origindescription="+document.getElementById("StartDesc").innerHTML+"&destinationdescription=&num="+Math.random();
    }
    xmlHttp.onreadystatechange=SendSMSAjax;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    
}

function SendSMSAjax()
{
    if (xmlHttp.readyState==4)
    {
       Result =xmlHttp.responseText;
       document.getElementById("txtCellNr").value = "";
       CloseSMS()
       alert("Message Sent");
    }
}

function CalculateRadiusBB(Lat,Lon)
{
    var BottomLeftLat = 0;
    var BottomLeftLong = 0;
    var TopRightLat = 0;
    var TopRightLong = 0;
    
    BottomLeftLat = Lat - 0.6;
    BottomLeftLong = Lon - 0.6;
    TopRightLat = Lat + 0.6;
    TopRightLong = Lon + 0.6;
    
    var QuickBBox = BottomLeftLong + "," + BottomLeftLat + "," + TopRightLong + "," + TopRightLat;
    //g_map.SetMap(QuickBBox);
    GetFeaturePoints(Lat, Lon, QuickBBox);
}


function getQuickLink(Lat, Lon)
{
    //var LinkBoundB = CalculateRadiusBB(Lat,Lon);
}


function GetFeatureInfo(latitude,longitude,boundingBox) 
{
    var coordinate = new AGCoord(latitude, longitude);
    var pixels = g_map.GetPixelFromCoordinate(coordinate);
    var dimensions = g_map.GetSize();
    
    GetJSONData("GetLayerInfo.aspx", "parseJSON", pixels.x, pixels.y, boundingBox, dimensions.width, dimensions.height);
}


function GetFeaturePoints(latitude,longitude,boundingBox) 
{
    var dimensions = g_map.GetSize();
    GetPointsJSONData("GetLayerInfo.aspx", "parsePointsJSON", boundingBox, dimensions.width, dimensions.height);
}



function GetPointsJSONData(url, callBackName, boundingBox, width, height)
{                
    if (url.indexOf("?") > -1)
        url += "&jsonp=" 
    else
        url += "?jsonp=" 
    url += callBackName + "&";
    url += "type=Points&";
    url += "bb="
    url += boundingBox + "&";
    url += "width="
    url += width + "&";
    url += "height="
    url += height + "&";
    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);
}       


function GetJSONData(url, callBackName, iPixel, jPixel, boundingBox, width, height)
{                
    if (url.indexOf("?") > -1)
        url += "&jsonp=" 
    else
        url += "?jsonp=" 
    url += callBackName + "&";
    url += "i="
    url += iPixel.toString() + "&";
    url += "j="
    url += jPixel.toString() + "&";
    url += "bb="
    url += boundingBox + "&";
    url += "width="
    url += width + "&";
    url += "height="
    url += height + "&";
    url += "type=Info&";
    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);
}        

 function parseJSON(JSONText)
{
    var obj = eval( "(" + JSONText + ")");
  
	for (i = 0; i < obj.attributes.length; i++)
	{
//	    if (obj.attributes[i].name == "SITE_NUMBE")
//	    {
//	        SiteNo = obj.attributes[i].value;
//	        
//	        var HTMLToDisplay = "<div class='InfoPoint'><b>Project Name</b><br/>";
//		    HTMLToDisplay += "East London - Braelynn Ext 10 - 649 subs<br/><br/>";
//	        HTMLToDisplay += "<b>Site No : </b><br/>";
//	        HTMLToDisplay += SiteNo + "<br/><br/>";
//	        HTMLToDisplay += "<img style=' margin-left:5px' src='images/2_photos.gif' /><a href='#' onclick='javascript:showSitePhotos(\"" + SiteNo + "\")' >View Photo's</a><br/><br/>";
//	        HTMLToDisplay += "</div>";
//	        g_MainMap.AddPoint("imagery/images/cameraRed.png","img1", Latitude, Longitude,-5,-19, "View Photo", HTMLToDisplay);
//	    }
	}
} 


 function parsePointsJSON(JSONText)
{
    var obj = eval( "(" + JSONText + ")");
  
	for (i = 0; i < obj.attributes.length; i++)
	{
//	    if (obj.attributes[i].name == "SITE_NUMBE")
//	    {
//	        SiteNo = obj.attributes[i].value;
//	        
//	        var HTMLToDisplay = "<div class='InfoPoint'><b>Project Name</b><br/>";
//		    HTMLToDisplay += "East London - Braelynn Ext 10 - 649 subs<br/><br/>";
//	        HTMLToDisplay += "<b>Site No : </b><br/>";
//	        HTMLToDisplay += SiteNo + "<br/><br/>";
//	        HTMLToDisplay += "<img style=' margin-left:5px' src='images/2_photos.gif' /><a href='#' onclick='javascript:showSitePhotos(\"" + SiteNo + "\")' >View Photo's</a><br/><br/>";
//	        HTMLToDisplay += "</div>";
//	        g_MainMap.AddPoint("imagery/images/cameraRed.png","img1", Latitude, Longitude,-5,-19, "View Photo", HTMLToDisplay);
//	    }
	}
} 


function DrawRouteStations()
{
    xmlHttp1=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var url = "AJAXSearchStations.aspx?BBox="+GetBBOX() + "&Services=" + CheckedServiceID + "&num=" + Math.random();
    xmlHttp1.onreadystatechange=ReceiveRouteStations;
    xmlHttp1.open("GET",url,true);
    xmlHttp1.send(null);
}

function ReceiveRouteStations()
{

    if (xmlHttp1.readyState == 4)
    {
        
        var arr_received = xmlHttp1.responseText;
        var Coord = arr_received.split("|");
        g_map.removeOverlay();
        g_map.removeGroupOverlay("Point");
        //g_map.RemoveAllObjects();
        for(var i = 0; i < Coord.length; i++)
        {
            var str = Coord[i].split(";");
            if(str[0].length > 0)
            {
            
                 var oLatLng = new AGCoord(parseFloat(str[1]),parseFloat(str[2]));
                 var oIcon = new AGIcon();
                 oIcon.image = "Images/Pin_Total_32x32_24bit.png";
                 var Browser = {
                            Version: function() {
                                var version = 999; // we assume a sane browser
                                if (navigator.appVersion.indexOf("MSIE") != -1)
                                  version = parseFloat(navigator.appVersion.split("MSIE")[1]);
                                return version;
                              }
                            }
                            
                if (Browser.Version() >= 7) {
                    oIcon.shadow = "Images/transparent.gif";
                }
                 //oIcon.shadow = "Images/transparent.gif";
                 oIcon.iconAnchor = new AGPoint(-5, -32);
                 oIcon.maxHeight = 32;
                 oIcon.iconSize.height =  25;
                 oIcon.iconSize.width =  25;
                 var oNewMarkerOptions = new AGMarkerOptions(oIcon);
                 marker = new AGMarker(oLatLng, oNewMarkerOptions);
                 g_map.addOverlay(marker, "Point");  
                 
                 infodisplay = new AGInfoDisplayOptions();
                 infodisplay.height = 150;
                 infodisplay.width = 150;
                 pointObj = document.createElement("div");
                 pointObj.innerHTML = "<table><tr><td><img src='images/Pin_Total_16x16_24bit.gif'/></td><td style='v-align:center'><strong>Service Station<strong></td></tr></table>"+
                                      str[0]+"<br/><br/><a href='#' onclick='javascript:ShowStationDetails(\"" + str[3] + "\");'>View Details</a><br/><br/>";
                 marker.bindInfoDisplay(pointObj, infodisplay);
            
            
             //g_map.AddPoint("Images/Pin_Total_32x32_8bit.png","img1", parseFloat(str[1]),parseFloat(str[2]),-5,-32,
             //               "<table><tr><td><img src='images/logoSmall.gif'/></td><td style='v-align:center'><strong>Service Station<strong></td></tr></table>",
             //               str[0]+"<br/><br/><a href='#' onclick='javascript:ShowStationDetails(\"" + str[3] + "\");'>View Details</a><br/><br/>");
            }

        }
     }
}


function GetBBOX()
 {
    var oBoundingBox = g_map.getBoundingBox();
    var oSouthWestCoords = oBoundingBox.getSouthWest();
    var oNorthEastCoords = oBoundingBox.getNorthEast();
    var boundingBox = oSouthWestCoords.longitude() + "," + oSouthWestCoords.latitude() + "," + oNorthEastCoords.longitude() + "," + oNorthEastCoords.latitude();    
    
    return boundingBox;
 }
 
 
 function ResetMap()
 {
    wayPoint = "";
    //oDirection.clear();
    RouteType = "";
    RouteLat = "";
    RouteLon = "";
    RouteLocation = "";
    
    var oLatLng = new AGCoord(-28.2751829172523, 25.0430317799304);
	g_map.centreAndScale(oLatLng, 5);
	g_map.removeOverlay();
    g_map.removeGroupOverlay("Point");
    if (oDirection != null) oDirection.clear();
    //g_map._dd.clear();
    //oDirection.clear();
    
    //g_map.DrivingDirections.Clear();
    //g_map.RemoveAllObjects();
    //g_map.CentreAndScale(-28.5751829172523,24.0430317799304,0);
 }
 
 function ResetMapHome()
 {
    g_map.removeGroupOverlay("Point");
    var oLatLng = new AGCoord(-28.2751829172523, 25.0430317799304);
	g_map.centreAndScale(oLatLng, 5);
    DrawStations();
 }
 
 function ResetStationFinder()
 {
    CloseBox();
    bSearch = false;
    document.getElementById("rbLocation").checked = true;
    document.getElementById("divShowStationResults").style.display = 'none';
    ResetMap();
    ResetServices();
    document.getElementById("ctl00_ContentPlaceHolder1_txtSearchVal").value = "";
    document.getElementById("divResults").innerHTML = "";
    document.getElementById("lblNumberResults").innerHTML = "";
    document.getElementById("divStationResults").innerHTML = "";
    document.getElementById("lblStationNumberResults").innerHTML = "";
    //document.getElementById("chk24").checked = false;
    //document.getElementById("chkshop").checked = false;
    //document.getElementById("chkworkshop").checked = false;
    //document.getElementById("chkgas").checked = false;
    //document.getElementById("chkroute").checked = false;
    //document.getElementById("chkSteers").checked = false;
    //document.getElementById("chkCarWash").checked = false;
    //document.getElementById("chkInternet").checked = false;
    //document.getElementById("chkIsis").checked = false;
    document.getElementById("ctl00_ContentPlaceHolder1_hdfToFrom").value = "";
    document.getElementById("divDSelected").innerHTML ="";
    document.getElementById("divDrivingDirections").style.display = 'none';
    document.getElementById("ToFromNavigation").style.display = "none";
    NumResults = 0;
    ResultPageSize = 6;
    CurPageIndex = 0;
 
 }
 
 function ResetServices()
 {
//    iNumServices = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").cells.length;
//    for (var i = 0; i <  iNumServices; i++)
//    {
//        cellElement = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").cells[i];
//        cellElement.lastChild.firstChild.checked = false;
//    }
//    
    
    iNumRows = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows.length;
    CheckedServiceID = "";
    for (var i = 0; i <  iNumRows; i++)
    {
        iNumCells = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows[i].cells.length;
        for (var j = 0; j < iNumCells; j++)
        {
            cellElement = document.getElementById("ctl00_ContentPlaceHolder1_tblServices").rows[i].cells[j];
            cellElement.firstChild.firstChild.checked = false;
        }
    }
 
 
 
 }
 
 
 function ResetMapSearch()
 {
    bSearch = false;
    g_ProvinceBB = "";
    ResetMap();
    CloseBox();
    ResetServices();
    document.getElementById("lblNumberResults").innerHTML = "";
    document.getElementById("divStationResults").innerHTML = "";
    document.getElementById("lblStationNumberResults").innerHTML = "";
    document.getElementById("divShowStationResults").style.display = 'none';
    document.getElementById("ctl00_ContentPlaceHolder1_txtTown").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtSuburb").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtStreet").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtTown").value = "";
    document.getElementById("divResults").innerHTML = "";
    document.getElementById("divDSelected").innerHTML ="";
    document.getElementById("lblNumberResults").innerHTML = "";
    bSearch = false;
 }
 
 
 function ResetRouteFinder()
 {
    ResetMap();
    g_map.removeGroupOverlay("Toll1");
    CloseBox();
    CloseBox2();
    document.getElementById("ctl00_ContentPlaceHolder1_txtFromSearchVal").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_txtToSearchVal").value = "";
    document.getElementById("divResults").innerHTML = "";
    document.getElementById("DivEndResults").innerHTML = "";
    document.getElementById("StartDesc").innerHTML = "";
    document.getElementById("EndDesc").innerHTML = "";
    document.getElementById("ctl00_ContentPlaceHolder1_hidStart").value = "";
    document.getElementById("ctl00_ContentPlaceHolder1_hidEnd").value = "";
    document.getElementById("divDSelected").innerHTML ="";
    document.getElementById("DivDirections").innerHTML ="";
    document.getElementById("ToFromNavigation").style.display = "none";
    NumResults = 0;
    ResultPageSize = 6;
    CurPageIndex = 0;
    document.getElementById("EndToFromNavigation").style.display = "none";
    ToNumResults = 0;
    ToResultPageSize = 6;
    ToCurPageIndex = 0;
    bSearch = false;
    _startDesc = "";
    _startLat = "";
    _startLon = "";
    _endDesc = "";
    _endLat = "";
    _endLon = "";
    wayPoint = "";
    RouteType = "";
    RouteLat = "";
    RouteLon = "";
    RouteLocation = null;
    oDirections = null;
    sDescription = "";
    oDirection = null;
    CheckedServiceID = "";
 }
 
 function RouteFinder()
 {
    ResetMap();
 
 
 }
 
 
 function ShowMapPanel()
 {
//    window.location = "Reports.aspx?AggrType=Year";
//    g_ReportType = "MapStats";
    window.location = "Reports.aspx?Type=MapStats";
    g_ReportType = "MapStats";
 }
 
 
 function ShowAuditPanel()
 {
    window.location = "Reports.aspx?Type=AuditStats";
    g_ReportType = "AuditStats";
 }
 
 function ShowVisitPanel()
 {
    window.location = "Reports.aspx?Type=VisitStats";
    g_ReportType = "VisitStats";
 }
 
 
 function ShowStationDetails(iStationID)
 {
    //var printUrl = "StationDetails.aspx?CentLat="+midPoint.latitude+"&CentLon="+midPoint.longitude+"&Scale="+g_map.GetScale()+"&desc="+description+"&orgLon="+orgLongitude+"&orgLat="+orgLatitude+"&orgDesc="+originDescription+"&destLon="+destLongitude+"&destLat="+destLatitude+"&destDesc="+destinationDescription;
    var printUrl = "StationDetails.aspx?StationID=" + iStationID;
    width=490;
    height=370;
    popupobj= window.open(printUrl,null, "resizable=no,scrollbars=yes,top=200,left=300,width="+width+",height="+height);
    popupobj.focus();
    if(navigator.appName == "Microsoft Internet Explorer")
    {
      // IE
      popupobj.location.reload();
    }
 }
 
 
function EnterKeyHandler(e,btn)
{
    // process only the Enter key
    var Key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
    //if (e.keyCode == 13)
    if (Key == 13)
    {
        
        // cancel the default submit
        e.returnValue=false;
        e.cancel = true;
        // submit the form by programmatically clicking the specified button
        
        btn.click();
        return false;
    }
} 

function Logout()
{
    window.location = "Logout.aspx";
}


//Handles the navigation bar at the bottom of the search result list;
function SetNavbar()
{
	document.getElementById("ToFromNavigation").style.display='block';
	//Get the total number of pages
	var tot_pages = (parseInt(NumResults / ResultPageSize)) + 1;
	document.getElementById("PageIndexText").innerHTML= 'Page ' + (parseInt(CurPageIndex)+ 1) + '/' + tot_pages;

	//Set the to and from images
	//Previous button
	if(CurPageIndex > 0 && ResultPageSize < NumResults)
		document.getElementById("btnPrevResult").src="Images/Btn_Previous.jpg";
	else
		document.getElementById("btnPrevResult").src="Images/Btn_Previous_light.jpg";

	//Next button
	if((CurPageIndex + 1) < tot_pages )
		document.getElementById("btnNextResult").src="Images/Btn_Next.jpg";
	else
		document.getElementById("btnNextResult").src="Images/Btn_Next_light.jpg";	
}


function SetEndNavbar()
{
	document.getElementById("EndToFromNavigation").style.display='block';
	//Get the total number of pages
	var tot_pages = (parseInt(ToNumResults / ToResultPageSize)) + 1;
	document.getElementById("EndPageIndexText").innerHTML= 'Page ' + (parseInt(ToCurPageIndex)+ 1) + '/' + tot_pages;

	//Set the to and from images
	//Previous button
	if(ToCurPageIndex > 0 && ToResultPageSize < ToNumResults)
		document.getElementById("btnToPrevResult").src="Images/Btn_Previous.jpg";
	else
		document.getElementById("btnToPrevResult").src="Images/Btn_Previous_light.jpg";

	//Next button
	if((ToCurPageIndex + 1) < tot_pages )
		document.getElementById("btnToNextResult").src="Images/Btn_Next.jpg";
	else
		document.getElementById("btnToNextResult").src="Images/Btn_Next_light.jpg";	
}



function ClearPageIndex()
{
	CurPageIndex=0;
}

function GetNextResults(SearchFunction)
{
	//Check for upper boundary
	if(CurPageIndex < parseInt(NumResults / ResultPageSize))
	{
		CurPageIndex++;
		switch (SearchFunction)
		{
		    case "SearchAddress" :
		        SearchAddress();
		        break;
		        
		    case "SearchEndAddress" :
		        SearchEndAddress();
		        break;
		        
		    case "SearchStartAddress" :
		        SearchStartAddress();
		        break;
		        
		    case "SearchUser" :
		        //SearchUser();
		        SearchServices();
		        break;
		        
		}
	}
	else
		alert("No more results.");	
}

function GetPreviousResults(SearchFunction)
{
	//Check for upper boundary
	if(CurPageIndex > 0)
	{
		CurPageIndex--;
		switch (SearchFunction)
		{
		    case "SearchAddress" :
		        SearchAddress();
		        break;
		        
		    case "SearchEndAddress" :
		        SearchEndAddress();
		        break;
		        
		    case "SearchStartAddress" :
		        SearchStartAddress();
		        break;
            
            case "SearchUser" :
                SearchServices();
		        //SearchUser();
		        break;		        
		}
	}
	else
		alert("No more results.");	
}


function GetEndNextResults(SearchFunction)
{
	//Check for upper boundary
	if(ToCurPageIndex < parseInt(ToNumResults / ToResultPageSize))
	{
		ToCurPageIndex++;
		switch (SearchFunction)
		{
		    case "SearchAddress" :
		        SearchAddress();
		        break;
		        
		    case "SearchEndAddress" :
		        SearchEndAddress();
		        break;
		        
		    case "SearchStartAddress" :
		        SearchStartAddress();
		        break;
		}
	}
	else
		alert("No more results.");	
}

function GetEndPreviousResults(SearchFunction)
{
	//Check for upper boundary
	if(ToCurPageIndex > 0)
	{
		ToCurPageIndex--;
		switch (SearchFunction)
		{
		    case "SearchAddress" :
		        SearchAddress();
		        break;
		        
		    case "SearchEndAddress" :
		        SearchEndAddress();
		        break;
		        
		    case "SearchStartAddress" :
		        SearchStartAddress();
		        break;
		}
	}
	else
		alert("No more results.");	
}


function MarbilMapCount()
{
    var BoundBox = GetBBOX();
    var MapSize = g_map.getSize();
    
    var sMarbilUrl = "http://196.35.70.12:80/MarbilServer/MapLog?ClientID=19~Source=TotalNavigator~Version=1.0~MapServerIdentifier=http://ms1.afrigis.co.za/mapserver/im.aspx~BoundingBox=" + BoundBox +"~MapWidthPx=" + MapSize.width + "~MapHeightPx=" + MapSize.height + "~UserIdentifier=telkomsa.net~UserLocationLon=28.234080~UserLocationLat=-25.746670";
    var url = "AJAXHandleAdmin.aspx?type=marbil&marbilurl="+sMarbilUrl+ "&num=" + Math.random();
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        //alert ("Your browser does not support AJAX!");
        return;
    } 

    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    
}

function ShowManual()
{

    window.open('Total Navigator Manual.pdf', true ,'resizable=yes,scrollbars=yes,top=150,left=200,status=1,width=700,height=500,toolbar=no');

}


function ShowAdminManual()
{

    window.open('Total Navigator Administrator.pdf', true ,'resizable=yes,scrollbars=yes,top=150,left=200,status=1,width=700,height=500,toolbar=no');

}




