


// Global variables
var gbCheckTime = false; 	// set to true to enable time checking
var gbDebug = false; 	// se to true to turn on debuging
var gTimeInc = 20000; 	// Milliseconds between waypoints i.e. 20 seconds = 20000
var gExit = 0;          //Using this to try to force an exit from javascript execution.
var MapWidthType = 0    //0 % 1 = number
var MapHeightType = 1    //0 % 1 = number
var MapWidth = 97;
var MapHeight = 600;

var oMarkerEventInfo;

var osMap = null;
var gridProjection = null;
var MarkerEventRegistered = 0;
var MyText;
var ChooseIndex = -1;
var PlaceName = "Cheddar";
var WindowState = 3;  //3 check used tile count, 1 enter place, 2 pick from found list, 6 get GPX, 7 export GPX, //20 Convert Longitude to Easting

var gLocations;

//Global variables are defined here.

var aLat = new Array(2000);
var aLon = new Array(2000);
var aName = new Array(2000);
var aDesc = new Array(2000);
var aMarker = new Array(2000);  //Marker objects.
var aID = new Array(2000);      //Used to identify which marker has been clicked.
var ArrayIndex = 0;
var MyStatus = 0;
var MyChild;

var middleLon = -1.0000;
var middleLat = 51.0000;
//Left mouse button function 0 Show info, 1 Add, 2 Delete, 3 Not used
var ClickMode = 0;
var leftFunction = 0;
var SelectMarkerIndex = 0;
var LastMarkerIndex = 0;        //Allows state of the mark drop down to be kept.
                                //This is the index of the last added or editted marker.
var cName = "";
var cDesc = "";
var clickedMarker;
var LastMouseMode = 0;

var GPXInputFile = "";
var GPXExportFile = "";
var SearchName = "Bamford";

var DistanceStart = 0;

//Control position strings

var pxTop = "1px";
var pxButton = "3px";


// GPX input variables.
//
var latlongmarker;
var pLat = new Array(2000);
var pLon = new Array(2000);
var pName = new Array(2000);
var pDesc = new Array(2000);
var pArrayIndex = 0;



//Make sure all the new user generated points are zero.

for (a = 0; a < 2000; a++) {
    pLat[a] = 0;
    pLon[a] = 0;
    pName[a] = "";
    pDesc[a] = "";
    aLat[a] = 0;
    aLon[a] = 0;
    aName[a] = "";
    aDesc[a] = "";
    aMarker[a] = null;
    aID[a] = "";
}

document.body.style.backgroundColor = "white";
document.body.style.color = "black";
document.body.style.fontfamily = "Verdana, Arial, Helvetica, sans-serif";
document.body.style.fontsize = "10px";

// Workaround so that script works with Firefox 3.0 
//  and Safari 3.1. Can be removed once OpenSpace
//  is based on v2.6 (or later) of OPenLayers.
try {
    OpenLayers.Renderer.SVG.prototype.supported = function() {
        var svgFeature = "http://www.w3.org/TR/SVG11/feature#";
        return (document.implementation &&
           (document.implementation.hasFeature("org.w3c.svg", "1.0") ||
            document.implementation.hasFeature(svgFeature + "SVG", "1.1") ||
            document.implementation.hasFeature(svgFeature + "BasicStructure", "1.1")));
    };
}
catch (e) {
    alert("An error occurred setting FF3 and Safari3\nversion fix for old version\nof OpenLayers\nYou may get a version warning.");
}

	
	

MyText = "Extending web page functionality<br /><br />";
showstatusdiv(MyText);


var MapDiv;
    

try {
    MapDiv = document.getElementById("map");
        try {
            if (MapDiv != null) {
                document.body.removeChild(MapDiv);
                //MyText += "Success removed the map div<br />";
                //showstatusdiv(MyText);
                }

            }
            catch (e) {
             //alert("An error occurred trying to remove the 'map' div");
            }
    }
    catch (e) {
        alert("This web page does not appear\nto contain a 'map' div");
}

try {
    document.body.innerHTML = "";
}
catch (e) {
    alert("Error: unable to clear this web pages contents");
}

    

        var TopDiv = document.createElement('div');
        if (TopDiv !=null)
        {
	     
            TopDiv.setAttribute("id", "TheTopDiv");
            TopDiv.style.border = "1px solid black";
            TopDiv.style.height = "100px";
            TopDiv.style.width = "400px";
            var TopText = "<p>OS Map</p>"
            TopDiv.innerHTML = TopText;
            
            TopText = "<font size=\"2\">Your map will appear in the div below:<br />The map width will be the width of your browser window.</font>";
            TopDiv.innerHTML += TopText;
            document.body.appendChild(TopDiv);
	     }


 
        // create a new div element
        // and give it some content
        //var newDiv = document.createElementNS('map', 'html:div');
        //var newDiv = document.createElementNS("http://www.w3.org/1999/xhtml", "html:div");
	     //newDiv = document.createElementNS(XHTML_NS, "div");
	     var Oldstyle = 0;
	     if (Oldstyle == 1) {
	         var newDiv = document.createElement('div');


	         if (newDiv != null) {
	             newDiv.setAttribute("id", "map");
	             newDiv.style.border = "1px solid black";
	             document.body.appendChild(newDiv);

	             //MyText += "Success added the map div<br />";
	             //showstatusdiv(MyText);

	         }
	         else {
	             MyText += "Failed to add the map div<br />";
	             showstatusdiv(MyText);
	         }
	     }
	     else {

	         FloatingMapDiv();
	         
	     }

        document.URL
        //MyText += "document.URL = " + document.URL +"<br />";
        //showstatusdiv(MyText);
        
        MyText += "Select a place name<br />";
        showstatusdiv(MyText);
       
function onResult(locations)
{
    ChooseIndex = -1;
    gLocations = locations;

    if (locations != null && locations.length > 0) {
        WindowState = 2;
        MyText = "";
        showstatusdiv(MyText);
        return;
   }
   else
     {
        //The place was not found.
        if (PlaceName === null) {
            PlaceName = "";
        }
        MyText = "No places matching<br />" + PlaceName + "<br />were found.<br />Please try again.<br />";
        showstatusdiv(MyText);
        //var Result = prompt("No matching places were found\nwould you like to try again ?\nyes = yes\nanything else = no", "yes");
        //if (Result === "yes") {
        //    GetPlace();
        //}

    }
    
}
function GetPlace() {

    if (PlaceName === null) {
        PlaceName = "Cheddar";
    }

        if (PlaceName != null) {
            if (PlaceName.length > 0) {
                var gazetteer = new OpenSpace.Gazetteer();
                // Query the gazetteer and call the callback function
                gazetteer.getLocations(PlaceName, onResult);
            }
        }

}


function GetTheMap(locations) {

    
    if (osMap == null) {
        //only need to do this once
        //don't need several maps.

        osMap = new OpenSpace.Map('map');

        if (osMap != null) {
            
            osMap.events.register("click", osMap, addNew);
 
            MyText += "Success obtained an osMap<br />";
            showstatusdiv(MyText);
            
        }
        else {
            MyText += "Failed to obtained an osMap<br />osMap == null<br />";
            showstatusdiv(MyText);
        }
    }

        gridProjection = new OpenSpace.GridProjection();

        if (gridProjection != null) {
            //MyText += "Success got the gridProjection<br />";
            //showstatusdiv(MyText);

        }
        else {
            MyText += "Failed to get the gridProjection<br />";
            showstatusdiv(MyText);
        }

        //osMap.zoomTo(8);
        osMap.setCenter(locations[ChooseIndex].location, 7);
 
}


/**
*
* return the OSGB values for the lat long
* 
*/
function getOSGB(lon, lat) {
            var pos;
                var gridProjection = new OpenSpace.GridProjection();

                var lonlat = new OpenLayers.LonLat(lon, lat);
                pos = gridProjection.getMapPointFromLonLat(lonlat);

            return (pos);
        }

function hidestatusdiv() {
    var statusbox;
    try{
    statusbox = document.getElementById("statusbox");
    if (statusbox != null) {
	document.body.removeChild(statusbox);
    }
    }
    catch(e){}
}

function results(tilesUsed, maxTiles) {

    hidestatusdiv();
    z = document.body.appendChild(document.createElement("div"));
    WindowOutline(z)
    z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: 56px; right: 0px; width:180px;\"><span ><input type=\"button\" value=\"Continue\" style=\"font-weight: bold; width:160px;  margin-right:20px; \" id=\"ExtraButton\" name=\"ExtraButton1\" onclick=\"SetMode1()\"/></span></div>';

    z.innerHTML += "Site tile usage.<br />";
    z.innerHTML += "Each web site has a daily tile limit.<br />";
    z.innerHTML += "Once this limit has been reached<br />";
    z.innerHTML += "it can no longer display maps.<br /><br />";
    z.innerHTML += document.URL + "<br /><br />"; 
  // Draw results on screen in overlay
    z.innerHTML += "<DIV style=\"width: 250px; height:75px; color: black; background: white; font-size: 16px;\">" +
                        "Tiles Used: " + tilesUsed + " of " + maxTiles + " </DIV>";
}

function SetMode1() {
    WindowState = 1;
    showstatusdiv("Enter a place name to center the map on<br />and then click the <b>Search</b> button");
}
function SetMode2() {
    WindowState = 2;
    showstatusdiv("");
}

function SetMode3() {
    WindowState = 3;
    showstatusdiv("");
}

function SetMode4() {
    WindowState = 4;
    showstatusdiv("");
}

function SetMode5() {
    WindowState = 5;
    statusbox = document.getElementById("map");
    if (statusbox != null) {
        statusbox.style.top = "200px";
    }
    //The click position is out of place after moving the map div.
    //try this to fix it.
    osMap.updateSize();

    showstatusdiv("");
}

function WindowOutline(z) {
    z.id = "statusbox";
    z.style.position = "absolute";
    if (self.pageYOffset != null) {
        z.style.top = self.pageYOffset + "px";
    } else if (document.documentElement.scrollTop != null) {
        z.style.top = document.documentElement.scrollTop + "px";
    }
    z.style.width = "800px";
    z.style.left = "0px";
    z.style.background = "#ffffff";
    z.style.border = ".3em solid #ff0000";
    z.style.padding = ".3em 1.3em .3em .3em";
    z.style.zIndex = "1000";
    z.style.height = "115px";
    z.style.color = "black";

    z.innerHTML = '<div style=\"position: absolute;  border: 1px solid black; top: 0px; right: 0px; \"><span style=\"padding: .3em; font-weight: bold;\"><a style=\"text-decoration: none;\" title=\"Close control window\" href=\"#\" onclick=\"javascript:hidestatusdiv();\">X</a></span></div>';
    //Left click type drop down menu.
    SelectText = '<div style=\"width:180px; height:45px; position: absolute; border: 1px solid black; top: 2px; right: 33px; \"><span align=\"left\" align=\"top\" style=\"padding: .3em;\">Menu</span ><br /><span style=\"padding: .3em;\"><select  id=\"MenuDropDown\" name=\"MenuDropDown\"  width=\"100px\" onchange=\"SetMenuMode()\">'
    SelectText += "<option value=\"0\">";
    SelectText += "<option value=\"1\">1 Search for place";
    SelectText += "<option value=\"2\">2 Edit markers";
    SelectText += "<option value=\"3\">3 Import GPX";
    SelectText += "<option value=\"4\">4 Export GPX";
    SelectText += "<option value=\"5\">5 Numeric marker names";
    SelectText += "<option value=\"6\">6 Marker distances";
    SelectText += "<option value=\"11\">11 Mode 1 test";
    SelectText += "<option value=\"12\">12 Mode 2 test";
    SelectText += "<option value=\"13\">13 Mode 3 test";
    SelectText += "<option value=\"14\">14 Mode 4 test";
    SelectText += "<option value=\"15\">15 Mode 5 test";
    SelectText += "<option value=\"20\">20 Convert Co-ordinates";
    SelectText += "<option value=\"30\">30 Print";
    SelectText += "<option value=\"31\">31 'map' div size";
    SelectText += "<option value=\"32\">32 Shrink control window";
    SelectText += "<option value=\"33\">33 Bookmark version";
    SelectText += "<option value=\"40\">40 Debug";

    SelectText += '</select></span></div>';
    z.innerHTML += SelectText;
    z.innerHTML += "<br />";
    
}

function MarkerEditInputs(z) {

    //Marker index dropdown.
    SelectText = '<div style=\"width:170px; height:26px; position: absolute; border: 1px solid black; top: ' + pxTop + '; left: 10px;\"><span style=\" margin-left: 10px; font-weight: bold; \">Marker index</span><select  id=\"SelectMarker\" name=\"D1\"  " style=\" margin-left: 10px;  margin-top: 2px; width:50px;  \" onchange=\"SetMarkerDisplay()\">'
    SelectText += "<option value=\"\">";
    for (i = 1; i <= ArrayIndex; i++) {
        SelectText += "<option value=\"" + i + "\">" + i;
    }
    SelectText += '</select></div>';
    z.innerHTML += SelectText;

    z.innerHTML += '<div style=\"margin-top: 10px; position: absolute; border: 1px solid black; height: 25px; width:450px; right: 365px;\"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Marker name</span ><span ><input type=\"text\" size = \"40\" style=\"margin-top: 1px; margin-right: 1px; position: relative; font-weight: bold; left:130px  \"  id=\"InputPointName\" name=\"PointName\" /></span></div>';
    z.innerHTML += '<div style=\"margin-top: 40px; position: absolute; border: 1px solid black; height: 25px; width:450px; right: 365px;\"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Marker desc.</span ><span ><input type=\"text\" size = \"40\" style=\"margin-top: 1px; margin-right: 1px; position: relative; font-weight: bold; left:130px  \"  id=\"InputPointDesc\" name=\"PointDesc\" /></span></div>';
    z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: ' + pxButton + '; right: 500px; width:80px;\"><span ><input type=\"button\" value=\"Delete\" style=\"font-weight: bold; width:60px; margin-right:20px; \" id=\"MarkerDelete\"  onclick=\"DeleteMarker()\"/></span></div>';
    z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: ' + pxButton + '; right: 400px; width:80px;\"><span ><input type=\"button\" value=\"Save\" style=\"font-weight: bold; width:60px; margin-right:20px; \" id=\"PointSave\"  onclick=\"SavePoint()\"/></span></div>';
    z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: ' + pxButton + '; right: 250px; width:132px;\"><span ><input type=\"button\" value=\"Remove all\" style=\"font-weight: bold; width:100px; margin-right:2px; \" id=\"remove\"  onclick=\"RemoveAllRefresh()\"/></span></div>';
  
}

function SetMarkerDropdown() {

    if (LastMarkerIndex > ArrayIndex) {
        LastMarkerIndex = ArrayIndex;
    }

    if (ArrayIndex > 0) {

        document.getElementById("SelectMarker").selectedIndex = LastMarkerIndex;
        if (LastMarkerIndex > 0) {
            document.getElementById("InputPointName").value = aName[LastMarkerIndex - 1];
            document.getElementById("InputPointDesc").value = aDesc[LastMarkerIndex - 1];
        }
    }
    else {
        LastMarkerIndex = 0;
        document.getElementById("SelectMarker").selectedIndex = 0;
        document.getElementById("InputPointName").value = "";
        document.getElementById("InputPointDesc").value = "";

    }
}

function SmallButton(z) {

    z.style.position = "absolute";
    z.style.top = "1px";
    z.style.width = "15px";
    z.style.zIndex = "1000";
    z.style.left = "0px";
    z.style.background = "#ffffff";
    //z.style.border = ".1em solid #000000";
    z.style.border = ".1em solid blue";
    z.style.padding = "0.1em 0.1em 0.1em 0.1em";
    z.style.height = "15px";
    z.style.color = "blue";

    z.innerHTML = '<div style=\"position: absolute;  border: 0px solid white; top: 0px; right: 0px; \"><span style=\" font-weight: bold;\"><a style=\"text-decoration: none;\" title=\"Display control window\" href=\"#\" onclick=\"javascript:SetMode5();\"><></a></span></div>';
    
    statusbox = document.getElementById("TheTopDiv");
    if (statusbox != null) {
        document.body.removeChild(statusbox);
    }

    statusbox = document.getElementById("map");
    if (statusbox != null) {
        statusbox.style.top = "25px";
        //The click position is out of place after moving the map div.
        //try this to fix it.
        osMap.updateSize();
        
    }

}
function RemoveAllRefresh() {
    RemoveAll();
    showstatusdiv("");
}

function RemoveAll() {
         osMap.clearMarkers();

         //var markersarray = osMap.markerLayer.markers;
         //alert("3 osMap.markerLayer.markers length = " + markersarray.length);
         
    //Make sure all the new user generated points are zero.

    for (a = 0; a < 2000; a++) {
        pLat[a] = 0;
        pLon[a] = 0;
        pName[a] = "";
        pDesc[a] = "";
        aLat[a] = 0;
        aLon[a] = 0;
        aName[a] = "";
        aDesc[a] = "";
        aMarker[a] = null;
        aID[a] = "";
        
    }
    ArrayIndex = 0;
    pArrayIndex = 0;
    LastMarkerIndex = 0;
    SelectMarkerIndex = 0;

    //Cant have here because we need to 
    //keep the pasted gpx for GPX import.
    //showstatusdiv("");       
    
}

function DeleteMarker() {
  
    if (LastMarkerIndex < 1) {
        alert("Error: the drop down does not refer to a marker.\nIt is zero.")
        return;
    }
    
    try {
        //removeMarker removes the marker from the display
        //and removes from osMap.markerLayer.markers.
          var dMarker = osMap.markerLayer.markers[(LastMarkerIndex - 1)];
           osMap.removeMarker(dMarker);
    }
    catch (e) {
        alert("DeleteMarker() 1\nosMap.removeMarker(dMarker);\nfailed");
    }

    try {
        //This might not be need ?
        aMarker[(LastMarkerIndex - 1)].events.destroy();
    }
    catch (e) {
        alert("DeleteMarker() 2\naMarker[(LastMarkerIndex-1)].events.destroy();\nfailed");
    }
   
    var Index;
    for (Index = (LastMarkerIndex - 1); Index < ArrayIndex; Index++) {
        aMarker[Index] = aMarker[Index + 1];
        aDesc[Index] = aDesc[Index + 1];
        aName[Index] = aName[Index + 1];
        aLat[Index] = aLat[Index + 1];
        aLon[Index] = aLon[Index + 1];
        aID[Index] = aID[Index + 1];


    }
    
    if (ArrayIndex > 0) {
        //Remove the last option from the select control.
        //document.getElementById("SelectMarker").options[ArrayIndex] = null;

        ArrayIndex--;
        //document.getElementById("SelectMarker").length = ArrayIndex;
        //if (document.getElementById("SelectMarker").length > 0) {
        //    document.getElementById("SelectMarker").remove(document.getElementById("SelectMarker").length - 1);
        //}

        while (document.getElementById("SelectMarker").length) {
            document.getElementById("SelectMarker").remove(0);
        }

        SelectText += "<option value=\"\">";
        for (i = 1; i <= ArrayIndex; i++) {
            document.getElementById("SelectMarker").options[i] = new Option( "" + i + "",i);
        }
 
        if (LastMarkerIndex > ArrayIndex) {
            LastMarkerIndex = ArrayIndex;
        }
    }
    else {
        LastMarkerIndex = 0;
        //document.getElementById("SelectMarker").length = 0;
        if (document.getElementById("SelectMarker").length > 0) {
            document.getElementById("SelectMarker").remove(document.getElementById("SelectMarker").length - 1);
        }

    }

    if (ArrayIndex > 0) {

        document.getElementById("SelectMarker").selectedIndex = LastMarkerIndex;
        if (LastMarkerIndex > 0) {
            document.getElementById("InputPointName").value = aName[LastMarkerIndex - 1];
            document.getElementById("InputPointDesc").value = aDesc[LastMarkerIndex - 1];
        }
    }
    else {
        LastMarkerIndex = 0;
        document.getElementById("SelectMarker").selectedIndex = 0;
        document.getElementById("InputPointName").value = "";
        document.getElementById("InputPointDesc").value = "";
        
    }
   
}

function LeftClickMenu(z) {
    //Mouse left click type drop down menu.
    var SelectText = '<div style=\"width:180px; height:50px; position: absolute; border: 1px solid black; top: 50px; right:33px;\"><span align=\"left\" align=\"top\" style=\"padding: .3em;\">Mouse click function</span ><br /><span style=\"padding: .3em;\"><select  id=\"SelectMenu\" name=\"D1\"  width=\"50px\" onchange=\"SetClickMode()\">'
    SelectText += "<option value=\"0\">";
    SelectText += "<option value=\"1\">1 Info";
    SelectText += "<option value=\"2\">2 Add marker";
    SelectText += "<option value=\"3\">3 Delete Marker";
    SelectText += "<option value=\"4\">4 Not used";

    SelectText += '</select></span></div>';
    z.innerHTML += SelectText;
 
}
function SetLeftClickDropdown() {
    //Set the menu to the current ClickMode.
    document.getElementById("SelectMenu").selectedIndex = ClickMode;
}

function GPXInputControls(z) {

    z.innerHTML += '<div style=\"position: absolute; width:65%; border: 1px solid black; top: 0px; left: 30px; margin-top:25px; \"><span ><textarea style=\"font-weight: bold; height: 400px; width:98%;\" id=\"InputGPX\" name=\"iInputGPX\"></textarea></span></div>';
    z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top:60px; right: 25px; width:205px;\"><span >Paste your GPX into the text box and click the button<input type=\"button\" value=\"GetGPX\" style=\"font-weight: bold; width:80px; margin-left:65px;margin-top:5px; margin-bottom:5px; \" id=\"GetGPX\"  onclick=\"onGetGPX()\"/></span></div>';

}


function GPXOutputControls(z) {
    var TheText;
    TheText = '<div style=\"position: absolute; width:65%; border: 1px solid black; top: 0px; left: 30px; margin-top:25px; \"><span ><textarea style=\"font-weight: bold; height: 400px; width:98%;\" id=\"OutputGPX\" name=\"iOutputGPX\"></textarea></span></div>';
    TheText += '<div style=\"position: absolute; border: 1px solid black; top:60px; right: 25px; width:205px;\"><span >Choose an output GPX type.';
    TheText += '<input type=\"button\" value=\"Route\" style=\"font-weight: bold; width:115px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"GPXRoute\"  onclick=\"onGPXRoute()\"/>';
    TheText += '<input type=\"button\" value=\"Track\" style=\"font-weight: bold; width:115px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"GPXTrack\"  onclick=\"onGPXTrack()\"/>';
    TheText += '<input type=\"button\" value=\"Waypoint\" style=\"font-weight: bold; width:115px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"GPXWpt\"  onclick=\"onGPXWpt()\"/>';
    TheText += '<input type=\"button\" value=\"GPSSC Route\" style=\"font-weight: bold; width:115px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"GPSSCRoute\"  onclick=\"onGPXGPSSC()\"/>';
    TheText += '</span></div>';
    z.innerHTML += TheText;
}

function MarkerDistances(z) {
    TableDistances(z);
}

function TableDistances(z) {
    var LoopEnd;
    var DistanceX;
    var DistanceY;
    var DistanceZ;
    var DistanceTotal;
    var TheText;
    TheText = '<div style=\"position: absolute; width:65%; border: 1px solid black; top: 0px; left: 30px; margin-top:25px; \" id=\"TableArea\" ></div>';
    TheText += '<div style=\"position: absolute; border: 1px solid black; top:60px; right: 25px; width:205px;\"><span >Marker distances.';
    TheText += '<input type=\"button\" value=\"Km to clipboard\" style=\"font-weight: bold; width:145px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"onkmclipboard\"  onclick=\"PlainDistances(z)\"/>';
    TheText += '<input type=\"button\" value=\"Miles to clipboard\" style=\"font-weight: bold; width:145px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"Miles\"  onclick=\"onTDMiles(z)\"/>';
    TheText += '<input type=\"button\" value=\"Back\" style=\"font-weight: bold; width:115px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"Back\"  onclick=\"onTDBack()\"/>';
    TheText += '<input type=\"button\" value=\"Forward\" style=\"font-weight: bold; width:115px; margin-left:45px;margin-top:5px; margin-bottom:5px; \" id=\"Forward\"  onclick=\"onTDForward()\"/>';
    
    z.innerHTML += TheText;
    DistanceTotal = 0;
    DistanceZ = 0;
    DistanceStart = 0;

    TheText = "Marker distances in km.<br /><table >"
    TheText += "<tr>";
    TheText += "<td>" + "id..." + "</td>";
    TheText += "<td>" + "Total..." + "</td>";
    TheText += "<td>" + "Leg..." + "</td>";
    TheText += "<td>" + "Name..." + "</td>";
    TheText += "<td>" + "Desc..." + "</td>";
    TheText += "</tr>";
    
    if (ArrayIndex < (DistanceStart + 15)) {
        LoopEnd = ArrayIndex;
    }
    else {
        LoopEnd = (DistanceStart + 15);
    }


    for (a = 0; a < LoopEnd; a++) {
        TheText += "<tr>";
        DistanceX = 0;
        DistanceY = 0;
        if (a > 0) {
            var MapPoint1 = getOSGB(aLon[a - 1], aLat[a - 1]);
            var MapPoint2 = getOSGB(aLon[a], aLat[a]);
            DistanceX = MapPoint1.getEasting() - MapPoint2.getEasting();
            DistanceY = MapPoint1.getNorthing() - MapPoint2.getNorthing();

            DistanceZ = Math.sqrt(Math.pow(DistanceX, 2) + Math.pow(DistanceY, 2));

            DistanceTotal += DistanceZ;

        }
        TheText += "<td>" + a + "</td>" + "<td>" + parseFloat((DistanceTotal / 1000).toFixed(3)) + "</td>" + "<td>" + parseFloat((DistanceZ / 1000).toFixed(3)) + "</td>";
        TheText += "<td>" + aName[a] + "</td>";
        TheText += "<td>" + aDesc[a] + "</td>";
        TheText += "</tr>";

    }
    TheText += "</table>";

    document.getElementById("TableArea").innerHTML = TheText;
}

function onTDMiles(z) {
    var DistanceX;
    var DistanceY;
    var DistanceZ;
    var DistanceTotal;
    var TheText;
    TheText = '<span ><textarea style=\"font-weight: bold; height: 400px; width:98%;\" id=\"OutputGPX\" name=\"iOutputGPX\"></textarea></span>';
    document.getElementById("TableArea").innerHTML = TheText;
    DistanceTotal = 0;
    DistanceZ = 0;

    TheText = "Marker distances in miles.\n"
    for (a = 0; a < ArrayIndex; a++) {
        DistanceX = 0;
        DistanceY = 0;
        if (a > 0) {
            var MapPoint1 = getOSGB(aLon[a - 1], aLat[a - 1]);
            var MapPoint2 = getOSGB(aLon[a], aLat[a]);
            DistanceX = MapPoint1.getEasting() - MapPoint2.getEasting();
            DistanceY = MapPoint1.getNorthing() - MapPoint2.getNorthing();

            DistanceZ = Math.sqrt(Math.pow(DistanceX, 2) + Math.pow(DistanceY, 2));

            DistanceTotal += DistanceZ;

        }
        TheText += a + " Tot: " + parseFloat((DistanceTotal / 1609.344).toFixed(3)) + " leg: " + parseFloat((DistanceZ / 1609.344).toFixed(3)) + " ";
        TheText += aName[a];
        TheText += " " + aDesc[a] + "\n";
    }



    document.getElementById("OutputGPX").value = TheText;

    try {
        window.clipboardData.setData("Text", TheText);
        alert("The marker distances have been copied into the windows paste buffer.");

    }
    catch (e) {
        //This try is only here to allow the page in other browsers.
    }


}

function onTDForward(z) {
    var LoopEnd;
    var DistanceX;
    var DistanceY;
    var DistanceZ;
    var DistanceTotal;
    var TheText;
   DistanceTotal = 0;
   DistanceZ = 0;
   if (ArrayIndex > (DistanceStart+15)) {
       DistanceStart += 15;
   }

    TheText = "Marker distances in km.<br /><table >"
    TheText += "<tr>";
    TheText += "<td>" + "id..." + "</td>";
    TheText += "<td>" + "Total..." + "</td>";
    TheText += "<td>" + "Leg..." + "</td>";
    TheText += "<td>" + "Name..." + "</td>";
    TheText += "<td>" + "Desc..." + "</td>";
    TheText += "</tr>";
    //Get the total for all marker distances 
        //before the start of the list.
    for (a = 0; a < DistanceStart; a++) {
        DistanceX = 0;
        DistanceY = 0;
        if (a > 0) {
            var MapPoint1 = getOSGB(aLon[a - 1], aLat[a - 1]);
            var MapPoint2 = getOSGB(aLon[a], aLat[a]);
            DistanceX = MapPoint1.getEasting() - MapPoint2.getEasting();
            DistanceY = MapPoint1.getNorthing() - MapPoint2.getNorthing();

            DistanceZ = Math.sqrt(Math.pow(DistanceX, 2) + Math.pow(DistanceY, 2));

            DistanceTotal += DistanceZ;

        }
    }

    if (ArrayIndex < (DistanceStart + 15)) {
        LoopEnd = ArrayIndex;
    }
    else {
        LoopEnd = (DistanceStart + 15);
    }

    for (a = DistanceStart; a < LoopEnd; a++) {
        TheText += "<tr>";
        DistanceX = 0;
        DistanceY = 0;
        if (a > 0) {
            MapPoint1 = getOSGB(aLon[a - 1], aLat[a - 1]);
            MapPoint2 = getOSGB(aLon[a], aLat[a]);
            DistanceX = MapPoint1.getEasting() - MapPoint2.getEasting();
            DistanceY = MapPoint1.getNorthing() - MapPoint2.getNorthing();

            DistanceZ = Math.sqrt(Math.pow(DistanceX, 2) + Math.pow(DistanceY, 2));

            DistanceTotal += DistanceZ;

        }
        TheText += "<td>" + a + "</td>" + "<td>" + parseFloat((DistanceTotal / 1000).toFixed(3)) + "</td>" + "<td>" + parseFloat((DistanceZ / 1000).toFixed(3)) + "</td>";
        TheText += "<td>" + aName[a] + "</td>";
        TheText += "<td>" + aDesc[a] + "</td>";
        TheText += "</tr>";

    }
    TheText += "</table>";
    document.getElementById("TableArea").innerHTML = TheText;

}

function onTDBack(z) {
    var LoopEnd;
    var DistanceX;
    var DistanceY;
    var DistanceZ;
    var DistanceTotal;
    var TheText;
    DistanceTotal = 0;
    DistanceZ = 0;
    if (DistanceStart >14) {
        DistanceStart -= 15;
    }

    TheText = "Marker distances in km.<br /><table >"
    TheText += "<tr>";
    TheText += "<td>" + "id..." + "</td>";
    TheText += "<td>" + "Total..." + "</td>";
    TheText += "<td>" + "Leg..." + "</td>";
    TheText += "<td>" + "Name..." + "</td>";
    TheText += "<td>" + "Desc..." + "</td>";
    TheText += "</tr>";
    //Get the total for all marker distances 
    //before the start of the list.
    for (a = 0; a < DistanceStart; a++) {
        DistanceX = 0;
        DistanceY = 0;
        if (a > 0) {
            var MapPoint1 = getOSGB(aLon[a - 1], aLat[a - 1]);
            var MapPoint2 = getOSGB(aLon[a], aLat[a]);
            DistanceX = MapPoint1.getEasting() - MapPoint2.getEasting();
            DistanceY = MapPoint1.getNorthing() - MapPoint2.getNorthing();

            DistanceZ = Math.sqrt(Math.pow(DistanceX, 2) + Math.pow(DistanceY, 2));

            DistanceTotal += DistanceZ;

        }
    }
    if (ArrayIndex < (DistanceStart + 15)) {
        LoopEnd = ArrayIndex;
    }
    else {
        LoopEnd = (DistanceStart + 15);
    }


    for (a = DistanceStart; a < LoopEnd; a++) {
        TheText += "<tr>";
        DistanceX = 0;
        DistanceY = 0;
        if (a > 0) {
            MapPoint1 = getOSGB(aLon[a - 1], aLat[a - 1]);
            MapPoint2 = getOSGB(aLon[a], aLat[a]);
            DistanceX = MapPoint1.getEasting() - MapPoint2.getEasting();
            DistanceY = MapPoint1.getNorthing() - MapPoint2.getNorthing();

            DistanceZ = Math.sqrt(Math.pow(DistanceX, 2) + Math.pow(DistanceY, 2));

            DistanceTotal += DistanceZ;

        }
        TheText += "<td>" + a + "</td>" + "<td>" + parseFloat((DistanceTotal / 1000).toFixed(3)) + "</td>" + "<td>" + parseFloat((DistanceZ / 1000).toFixed(3)) + "</td>";
        TheText += "<td>" + aName[a] + "</td>";
        TheText += "<td>" + aDesc[a] + "</td>";
        TheText += "</tr>";

    }
    TheText += "</table>";
    document.getElementById("TableArea").innerHTML = TheText;

 
}

function PlainDistances(z) {
    var DistanceX;
    var DistanceY;
    var DistanceZ;
    var DistanceTotal;
    var TheText;
    TheText = '<span ><textarea style=\"font-weight: bold; height: 400px; width:98%;\" id=\"OutputGPX\" name=\"iOutputGPX\"></textarea></span>';
    document.getElementById("TableArea").innerHTML = TheText;
    DistanceTotal = 0;
    DistanceZ = 0;

    TheText = "Marker distances in km.\n"
    for (a = 0; a < ArrayIndex; a++) {
        DistanceX = 0;
        DistanceY = 0;
        if (a > 0) {
            var MapPoint1 = getOSGB(aLon[a-1], aLat[a-1]);
            var MapPoint2 = getOSGB(aLon[a], aLat[a]);
            DistanceX = MapPoint1.getEasting() - MapPoint2.getEasting();
            DistanceY = MapPoint1.getNorthing() - MapPoint2.getNorthing();

            DistanceZ = Math.sqrt(Math.pow(DistanceX, 2) + Math.pow(DistanceY, 2));

            DistanceTotal += DistanceZ;
            
        }
        TheText += a + " Tot: " + parseFloat((DistanceTotal / 1000).toFixed(3)) + " leg: " + parseFloat((DistanceZ / 1000).toFixed(3)) + " ";
        TheText += aName[a];
        TheText += " " + aDesc[a] + "\n";
    }


    
    document.getElementById("OutputGPX").value = TheText;

    try {
        window.clipboardData.setData("Text", TheText);
        alert("The marker distances have been copied into the windows paste buffer.");

    }
    catch (e) {
        //This try is only here to allow the page in other browsers.
    }

}


function ConvertLongitude(z) {

    var IText = "";
    IText += '<div style=\"position: absolute; height:32px; width:35%; border: 1px solid black; left: 30px; margin-top:25px; \"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Latitude</span ><span ><input  type=\"text\" style=\"position: absolute; margin-top:1px; font-weight: bold; height: 25px; width:130px; right:1px;\" id=\"InputLat\" name=\"iInputLat\"></input></span></div>';
    IText += '<div style=\"position: absolute; height:32px; width:35%; border: 1px solid black; left: 30px; margin-top:63px; \"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Longitude</span ><span ><input  type=\"text\" style=\"position: absolute; margin-top:1px; font-weight: bold; height: 25px; width:130px; right:1px;\" id=\"InputLon\" name=\"iInputLon\"></input></span></div>';
    //IText += '<div style=\"position: absolute; height:32px; width:35%; border: 1px solid black; left: 30px; margin-top:100px; \"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Northing</span ><span ><input  type=\"text\" style=\"position: absolute; margin-top:1px; font-weight: bold; height: 25px; width:130px; right:1px;\" id=\"InputNorthing\" name=\"iInputNorthing\"></input></span></div>';
    IText += '<div style=\"position: absolute; height:32px; width:35%; border: 1px solid black; left: 30px; margin-top:100px; \"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Northing</span ><span ><input  type=\"text\" style=\"position: absolute; margin-top:1px; font-weight: bold; height: 25px; width:130px; right:1px;\" value=' + '122766 ' + '  id=\"InputNorthing\" name=\"iInputNorthing\"></input></span></div>';
    IText += '<div style=\"position: absolute; height:32px; width:35%; border: 1px solid black; left: 30px; margin-top:138px; \"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Easting</span ><span ><input  type=\"text\" style=\"position: absolute; margin-top:1px; font-weight: bold; height: 25px; width:130px; right:1px;\" value=' + '470267 ' + ' id=\"InputEasting\" name=\"iInputEasting\"></input></span></div>';
    IText += '<div style=\"position: absolute; border: 1px solid black; top:50px; right: 260px; width:205px; \"><span >Lat/Lon to N/E<input type=\"button\" value=\"Lat/Lon to N/E\" style=\"font-weight: bold; width:140px; margin-left:65px;margin-top:5px; margin-bottom:5px; \" id=\"ToEN\"  onclick=\"onToEN()\"/></span></div>';
    IText += '<div style=\"position: absolute; border: 1px solid black; top:130px; right: 260px; width:205px; \"><span >N/E to Lat/Lon<input type=\"button\" value=\"N/E to Lat/Lon\" style=\"font-weight: bold; width:140px; margin-left:65px;margin-top:5px; margin-bottom:5px; \" id=\"ToLatLon\"  onclick=\"onLatLon()\"/></span></div>';
    z.innerHTML += IText;
    //z.getElementById("InputEasting").value = "880267";
    //document.getElementById("InputEasting").value = "470267";
    //document.getElementById("InputNorthing").value = "223341";
    
}
function onGetGPX() {
    RemoveAll();
    MyParse();
}

//In conversion dialog mode 8 converts a WGS84 lon lat to a OSGB36 easting.
function onToEN() {
    var lat = parseFloat(document.getElementById("InputLat").value);
    var lon = parseFloat(document.getElementById("InputLon").value);
    
    //getMapPointFromLonLat	Convert an WGS84 point into a OSGB36 grid point
    var lonlat = new OpenLayers.LonLat(lon, lat);
    var mapPoint = gridProjection.getMapPointFromLonLat(lonlat);
    document.getElementById("InputEasting").value = parseFloat(mapPoint.getEasting().toFixed(4));
    document.getElementById("InputNorthing").value = parseFloat(mapPoint.getNorthing().toFixed(4));
}

function onLatLon() {
    var Easting = parseFloat(document.getElementById("InputEasting").value);
    var Northing = parseFloat(document.getElementById("InputNorthing").value);
    var ResultPair = MyOSGridToLatLong(Easting, Northing)
    document.getElementById("InputLat").value = parseFloat(ResultPair.lat).toFixed(6);
    document.getElementById("InputLon").value = parseFloat(ResultPair.lon).toFixed(6);
}

function LonLatToEN(lon, lat) {

    
    var EN = new LatLon;
    
    //WGS84 to OSGrid EN.
    var lonlat = new OpenLayers.LonLat(lon, lat);
    var mapPoint = gridProjection.getMapPointFromLonLat(lonlat);
    EN.lat = mapPoint.getNorthing();
    EN.lon = mapPoint.getEasting();
    return (EN);

    //returns a two var array of easting and northing see below for usage
    //var ENTemp = LonLatToEN(lon,lat);
    //var ENFinish = new NorthEast;
    //ENFinish.Easting = ENTemp[0];
    //ENFinish.Northing = ENTemp[1];
    //document.getElementById("InputEasting").value = ENFinish.Easting;
    //document.getElementById("InputNorthing").value = ENFinish.Northing;
}
function ENtoLonLAT(Easting, Northing) {
       
    return (MyOSGridToLatLong(Easting, Northing));
   
    //returns a two var array of longitude and latitude see below for usage
    //var ResultPair = MyOSGridToLatLong(Easting, Northing)
    //document.getElementById("InputLat").value = ResultPair.lat;
    //document.getElementById("InputLon").value = ResultPair.lon;


}


function showstatusdiv(boxcontents) {
    //1 enter place
    //2 pick from found list
    //3 check used tile count
    //4 Marker edit dialog
    //5
    //6 get GPX
    //7 export GPX
    //20 Convert Longitude to Easting
    //30 Print
    //31.9 map div size.
    //32.10 Reduce control window to a small button.
    //40 Debug";
    //6.12 Distances between markers.


    var z;

    //alert("WindowState = " + WindowState);
    if (WindowState === 3)   //3 check used tile count, 1 enter place, 2 pick from found list,
    {

        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);

        z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: 70px; right: 30px; width:120px;\"><span ><input type=\"button\" value=\"Continue\" style=\"font-weight: bold;  margin-right:20px; \" id=\"ExtraButton\" name=\"ExtraButton1\" onclick=\"SetMode1()\"/></span></div>';

        z.innerHTML += "Checking site tile usage please wait.<br />";
        // Create a new service
        try {
            var supportService = new OpenSpace.SupportService();
        }
        catch (e) {
            //This try is only here to allow the page to run offline.
        }
        try {
            supportService.getTileCount(results);
        }
        catch (e) {
            //This try is only here to allow the page to run offline.
        }



    }
    else if (WindowState === 1)   //1 enter place, 2 pick from found list, 
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);

        //z.innerHTML += '<div style=\"position: absolute; width:50%; border: 1px solid black; top: 3px; right: 235px;\"><span ><input type=\"text\"  value=\"Compton\" style=\"font-weight: bold; width:98%;\"  id=\"Input1\" name=\"MyInput1\" /></span></div>';
        z.innerHTML += '<div style=\"position: absolute; width:50%; border: 1px solid black; top: 3px; right: 235px;\"><span ><input type=\"text\"  value=\"\" style=\"font-weight: bold; width:98%;\"  id=\"Input1\" name=\"MyInput1\" /></span></div>';
        z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: 40px; right: 235px; width:80px; \"><span ><input type=\"button\" value=\"Search\" style=\"font-weight: bold; width:60px;  margin-right:20px; \" id=\"ExtraButton\" name=\"ExtraButton1\" onclick=\"MyClick()\"/></span></div>';
        //Mouse left click type drop down menu.
        LeftClickMenu(z);
        z.innerHTML += boxcontents;

        document.getElementById("Input1").value = SearchName;
        //document.getElementById("Input1").textContent. = SearchName;
        //document.getElementById("Input1").innerText = SearchName;



    }
    else if (WindowState === 2)   //1 enter place, 2 pick from found list, 
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);

        SelectText = '<div style=\"position: absolute; width:250px; margin-top:40px; height:25px; position: absolute; border: 1px solid black;  right:33px;\"><span ><select  id=\"SelectLocation\" name=\"D1\"  width=\"100%\" onchange=\"SetLocation()\">'
        SelectText += "<option value=\"0\">";
        try {
            for (var i = 0; i < gLocations.length; i++) {
                // Extract result fields
                SelectText += "<OPTION VALUE=\"" + (i + 1) + "\">" + i + " " + gLocations[i].name + "," + gLocations[i].county; ;
            }

        }
        catch (e) {
            //This try is only here to allow the page to run offline.
        }

        SelectText += '</select></p></span></div>';
        z.innerHTML += SelectText;

        z.innerHTML += boxcontents;

        try {
            if (gLocations != null && gLocations.length > 0) {

                MyText = "Place name search results<br />";
                MyText += "Choose one of the results<br />";
                MyText += "using the drop down list<br />";
                MyText += "to display the map.<br /><br />";
                for (i = 0; i < gLocations.length; i++) {
                    // Extract result fields
                    var PlaceText = i + " of " + gLocations.length + "\n";
                    PlaceText += gLocations[i].name;
                    PlaceText += " " + gLocations[i].county;
                    PlaceText += "\n" + gLocations[i].location;
                    //PlaceText += " " + gLocations.toCoordString();
                    MyText += "<font size=\"1\">" + PlaceText + "</font><br />";
                }
                z.innerHTML += MyText;
            }
        }
        catch (e) {
            //This try is only here to allow the page to run offline.
        }


    }
    else if (WindowState === 4)   //Marker edit dialog 
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        MarkerEditInputs(z);
        LeftClickMenu(z);
        z.innerHTML += boxcontents;

        SetMarkerDropdown();
        SetLeftClickDropdown();
    }
    else if (WindowState === 5)   //1 enter place, 2 pick from found list, 5 marker info/edit
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);

        MarkerEditInputs(z);

        LeftClickMenu(z);

        z.innerHTML += boxcontents;
        SetMarkerDropdown();
        SetLeftClickDropdown();

    }
    else if (WindowState === 6)   //6 get GPX
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        z.style.height = "140px";
        GPXInputControls(z);
        z.innerHTML += boxcontents;
    }
    else if (WindowState === 7)   //7 export GPX
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        z.style.height = "250px";
        GPXOutputControls(z);
        z.innerHTML += boxcontents;
    }
    else if (WindowState === 8)   //20 Convert Longitude to Easting
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        ConvertLongitude(z);
        z.innerHTML += boxcontents;
        z.style.height = "300px";
    }
    else if (WindowState === 9)   //31.9 map div size
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        z.innerHTML += "Choose the dimensions for the map div.<br />note: when printing the map the div must fit inside the print page otherwise the<br />map will be missing.";

        z.innerHTML += '<div style=\"margin-top: 15px; position: absolute; border: 1px solid black; height: 25px; width:500px; right: 300px;\"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Width</span ><span ><input type=\"text\" size = \"10\" style=\"margin-top: 1px; margin-right: 1px; position: relative; font-weight: bold; left:130px  \"  id=\"DivWidth\" name=\"iDivWidth\" /></span><span style=\"position: absolute; font-weight: bold;  width:30px; right: 200px;\" >Numeric</span ><span ><input type=\"checkbox\" size = \"10\" style=\"margin-top: 1px; margin-right: 1px; position: absolute; font-weight: bold; right: 120px;\"  id=\"DivCheckWidthNumeric\" name=\"iDivCheckWidthNumeric\" onclick="SetDivCheckWidthNumeric()" /></span></span><span style=\"position: absolute; font-weight: bold;  width:30px; right: 50px;\" >%</span ><span ><input type=\"checkbox\" size = \"10\" style=\"margin-top: 1px; margin-right: 1px; position: absolute; font-weight: bold; right: 20px;\"  id=\"DivCheckWidthPerc\" name=\"iDivCheckWidthPerc\" onclick="SetDivCheckWidthPerc()" /></span></div>';
        z.innerHTML += '<div style=\"margin-top: 55px; position: absolute; border: 1px solid black; height: 25px; width:500px; right: 300px;\"><span style=\"position: absolute; font-weight: bold; left:10px; width:150px; \" >Height</span ><span ><input type=\"text\" size = \"10\" style=\"margin-top: 1px; margin-right: 1px; position: relative; font-weight: bold; left:130px  \"  id=\"DivHeight\" name=\"iDivHeight\" /></span><span style=\"position: absolute; font-weight: bold;  width:30px; right: 200px;\" >Numeric</span ><span ><input type=\"checkbox\" size = \"10\" style=\"margin-top: 1px; margin-right: 1px; position: absolute; font-weight: bold; right: 120px;\"  id=\"DivCheckHeightNumeric\" name=\"iDivCheckHeightNumeric\" onclick="SetDivCheckHeightNumeric()" /></span></span><span style=\"position: absolute; font-weight: bold;  width:30px; right: 50px;\" >%</span ><span ><input type=\"checkbox\" size = \"10\" style=\"margin-top: 1px; margin-right: 1px; position: absolute; font-weight: bold; right: 20px;\"  id=\"DivCheckHeightPerc\" name=\"iDivCheckHeightPerc\" onclick="SetDivCheckHeightPerc()" /></span></div>';
        z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: ' + pxButton + '; right: 400px; width:120px;\"><span ><input type=\"button\" value=\"Default\" style=\"font-weight: bold; width:100px; margin-right:20px; \" id=\"DivDefault\"  onclick=\"SetDivDefault()\"/></span></div>';
        z.innerHTML += '<div style=\"position: absolute; border: 1px solid black; top: ' + pxButton + '; right: 250px; width:120px;\"><span ><input type=\"button\" value=\"Save\" style=\"font-weight: bold; width:80px; margin-right:20px; \" id=\"DivSave\"  onclick=\"SaveDivDimensions()\"/></span></div>';

        z.style.height = "180px";

        document.getElementById("DivWidth").value = MapWidth;
        document.getElementById("DivHeight").value = MapHeight;
        if (MapWidthType == 1) { //0 % 1 = number
            document.getElementById("DivCheckWidthNumeric").checked = true;
            document.getElementById("DivCheckWidthPerc").checked = false;

        }
        else {
            document.getElementById("DivCheckWidthNumeric").checked = false;
            document.getElementById("DivCheckWidthPerc").checked = true;

        }

        if (MapHeightType == 1) { //0 % 1 = number
            document.getElementById("DivCheckHeightNumeric").checked = true;
            document.getElementById("DivCheckHeightPerc").checked = false;

        }
        else {
            document.getElementById("DivCheckHeightNumeric").checked = false;
            document.getElementById("DivCheckHeightPerc").checked = true;

        }
    }
    else if (WindowState === 10)   //32.10 Reduce control window to a small button.
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        SmallButton(z);
    }
    else if (WindowState === 11)   //33.11 Bookmark version and date.
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        z.innerHTML += "<br />Version 1.02 29-July-2009<br />"
        z.innerHTML += 'For more information visit the web page<br /><a href="http://www.stevematt.f9.co.uk/osmap/osbookmark.html"  target="_blank" >http://www.stevematt.f9.co.uk/osmap/osbookmark.html</a><br />';
        z.innerHTML += boxcontents;
        //z.style.height = "250px";
    }
    else if (WindowState === 12)   //6.12 Distances between markers.
    {
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        z.style.height = "500px";
        MarkerDistances(z);
        
    }

    else {
        alert("Unknown window state");
        WindowState = 3;
        hidestatusdiv();
        z = document.body.appendChild(document.createElement("div"));
        WindowOutline(z);
        LeftClickMenu(z)
        z.innerHTML += "<br />This window state is unknown<br />State = " + WindowState;
    }



}

function SetDivDefault() {

    document.getElementById("DivCheckHeightNumeric").checked = true;
    document.getElementById("DivCheckHeightPerc").checked = false;
    MapWidthType = 0; //0 % 1 = number
    
    document.getElementById("DivCheckWidthNumeric").checked = false;
    document.getElementById("DivCheckWidthPerc").checked = true;
    MapHeightType = 1;  //0 % 1 = number
    
    document.getElementById("DivWidth").value = 97; MapWidth = 97;
    document.getElementById("DivHeight").value = 600; MapHeight=600;

    if (MapWidthType == 1) { //0 % 1 = number
        document.getElementById("DivCheckWidthNumeric").checked = true;
        document.getElementById("DivCheckWidthPerc").checked = false;

    }
    else {
        document.getElementById("DivCheckWidthNumeric").checked = false;
        document.getElementById("DivCheckWidthPerc").checked = true;

    }

    if (MapHeightType == 1) { //0 % 1 = number
        document.getElementById("DivCheckHeightNumeric").checked = true;
        document.getElementById("DivCheckHeightPerc").checked = false;

    }
    else {
        document.getElementById("DivCheckHeightNumeric").checked = false;
        document.getElementById("DivCheckHeightPerc").checked = true;

    }
    
    document.getElementById("map").style.width = "" + MapWidth + "%";
    document.getElementById("map").style.height = "" + MapHeight + "px";
    //The click position is out of place after moving the map div.
    //try this to fix it.
    osMap.updateSize();


}

function SavePoint() {

    aName[LastMarkerIndex - 1] = document.getElementById("InputPointName").value;
    aDesc[LastMarkerIndex - 1] = document.getElementById("InputPointDesc").value;
    //Updates the Infowindow for this marker by re-registering it's mousedown event.
    SaveinfoWindow();

}

function SaveDivDimensions() {

    MapWidth = parseInt(document.getElementById("DivWidth").value);
    MapHeight = parseInt(document.getElementById("DivHeight").value);

    if (document.getElementById("DivCheckWidthNumeric").checked == true) {
        MapWidthType = 1;  //0 % 1 = number
    }
    else {
        MapWidthType = 0;  //0 % 1 = number
    }

    //Shouldn't need this
    if (document.getElementById("DivCheckWidthPerc").checked == true) {
        MapWidthType = 0;  //0 % 1 = number
    }



    if (document.getElementById("DivCheckHeightNumeric").checked == true) {
        MapHeightType = 1;  //0 % 1 = number
    }
    else {
        MapHeightType = 0;  //0 % 1 = number
    }

    //Shouldn't need this
    if (document.getElementById("DivCheckHeightPerc").checked == true) {
        MapHeightType = 0;  //0 % 1 = number
    }

    if (MapWidthType == 1)  //0 % 1 = number)
    {
        document.getElementById("map").style.width = "" + MapWidth + "px";
    }
    else {
        document.getElementById("map").style.width = "" + MapWidth + "%";
    }
    
    if (MapHeightType == 1)  //0 % 1 = number)
    {
        document.getElementById("map").style.height = "" + MapHeight + "px";
    }
    else {
        document.getElementById("map").style.height = "" + MapHeight + "%";
    }
    //The click position is out of place after moving the map div.
    //try this to fix it.
    osMap.updateSize();

}

function SetDivCheckWidthPerc() {

    if (document.getElementById("DivCheckWidthPerc").checked == true) {
        document.getElementById("DivCheckWidthNumeric").checked = false;
    }
    else {
        document.getElementById("DivCheckWidthNumeric").checked = true;

    }

}
function SetDivCheckHeightPerc() {
    if (document.getElementById("DivCheckHeightPerc").checked == true) {
        document.getElementById("DivCheckHeightNumeric").checked = false;
    }
    else {
        document.getElementById("DivCheckHeightNumeric").checked = true;

    }

}

function SetDivCheckWidthNumeric() {

    if (document.getElementById("DivCheckWidthNumeric").checked == true) {
        document.getElementById("DivCheckWidthPerc").checked = false;
    }
    else {
        document.getElementById("DivCheckWidthPerc").checked = true;

    }

}
function SetDivCheckHeightNumeric() {
    if (document.getElementById("DivCheckHeightNumeric").checked == true) {
        document.getElementById("DivCheckHeightPerc").checked = false;
    }
    else {
        document.getElementById("DivCheckHeightPerc").checked = true;

    }

}

//SetLocation
function SetLocation() {

    objSelect = document.getElementById("SelectLocation");
    if (objSelect === null) {
        alert("Failed to get list Select1 object");
        return;
    }

    ChooseIndex = objSelect.value -1;
    if (gLocations != null && gLocations.length > 0) {

        if ((ChooseIndex >= 0) && (ChooseIndex < gLocations.length)) {
            // Extract result fields
            GetTheMap(gLocations);
            
            MyText = " You chose " + ChooseIndex + "<br />";
            MyText += gLocations[ChooseIndex].name + "<br />";
            MyText += gLocations[ChooseIndex].county + "<br />";
            MyText += gLocations[ChooseIndex].location + "<br />";
            MyText += "Displaying map";
            WindowState = 1;
            showstatusdiv(MyText);
        }
    }




}


function MyClick() {
    PlaceName = document.getElementById("Input1").value;
    SearchName = PlaceName;
    GetPlace();
}

function StringBuffer() {
   this.buffer = [];
 }

StringBuffer.prototype.append = function append(string) {
   this.buffer.push(string);
   return this;
 };

StringBuffer.prototype.toString = function toString() {
   return this.buffer.join("");
 };

	
 


function displaybox(boxcontents) {
    closebox();
    var z=document.body.appendChild(document.createElement("div"));
    z.id = "gpxbox";
    z.style.position = "absolute";	
    if (self.pageYOffset != null) {	
	z.style.top = self.pageYOffset + "px";	
    } else if (document.documentElement.scrollTop != null) {
	z.style.top = document.documentElement.scrollTop + "px";	
    }
    z.style.width = "99%";
    z.style.zIndex = "1000";
    z.innerHTML = boxcontents;
}

function closebox() {
    var gpxbox;
    gpxbox = document.getElementById("gpxbox")

    if (gpxbox) {
        //Try setting to 0 so that print works.
        try {
            gpxbox.style.zIndex = "0";
        }
        catch (e) {
            alert("Could not gpxbox.style.zIndex = 0;");
        }

        document.body.removeChild(gpxbox);
    }
}

function FloatingMapDiv() {
    var z = document.body.appendChild(document.createElement("div"));
    z.id = "map";
    z.style.position = "absolute";
    z.style.top = "200px";
    //z.style.width = "97%";
    z.style.zIndex = "1000";
    z.style.left = "0px";
    z.style.background = "#ffffff";
    z.style.border = ".1em solid #000000";
    z.style.padding = ".1em 0.1em .1em .1em";
    //z.style.height = "600px";
    z.style.color = "black";

    if (MapWidthType == 1) {
        z.style.width = "" + MapWidth;
    }
    else {
        z.style.width = "" + MapWidth + "%";
    }
    if (MapHeightType == 1) {
        z.style.height = "" + MapHeight;
    }
    else {
        z.style.height = "" + MapHeight + "%";
    }

}





function loadabout() {
    var about = '<span style="font-size: x-small;"><p><a href="http://www.stevematt.f9.co.uk/googlemap/speedcamtogpx.js">speedcamtogpx</a> Extractor ' + version + '<br /></p></span>';
    
    showstatusdiv(about);
}

function errorbox(a) {
    var err = '<span style="font-size: x-small;"><p><a href="http://www.stevematt.f9.co.uk/googlemap/speedcamtogpx.js">speedcamtogpx</a> Extractor ' + version + ' (ERROR)<br /></p></span>'; 
    showstatusdiv(err);
}


/* Clean up floating point math errors */
function round(a) {
    return parseInt(a*1E+5)/1E+5;
}



function deamp(a) {
    a = a.replace(/<br *\/>(.+)/g, ", $1");
    a = a.replace(/<br *\/>/g, '');
    a = a.replace(/&#39;/g, '\'');
    a = a.replace(/\\047/g, '\'');
    a = a.replace(/\\042/g, '\"');
    a = a.replace(/&#160;/g, ' ');
    a = a.replace(/<\/*b>/g, '');
    a = a.replace(/<wbr\/*>/g, '');
    a = a.replace(/<div[^>]*?>.*?<\/div>/g, ' ');
    a = a.replace(/\\\'/g, '\''); 
    a = a.replace(/\\\"/g, '\"');
    a = a.replace(/\\x26/g, '&');
    a = a.replace(/&/g, '&amp;');  
    a = a.replace(/&amp;amp;amp;/g, '&amp;amp;');
    a = a.replace(/\\n/g, '');
    a = a.replace(/\\t/g, '');
    a = a.replace(/\s+/g, ' ');
    a = a.replace(/^\s+/, '');
    a = a.replace(/\s+$/, '');
    return a;
}

//Mouse click alert.
function addNew(evt) {

    var en;
    var easting;
    var northing;
    var pt;
    var lonlat;
    var marker;

    //alert("addNew");
    objSelect = document.getElementById("SelectMenu");
    if (objSelect === null) {
        // case 2: //2 Add
        ClickMode = LastMouseMode;
    }
    else {
        //Probably shoudn't be doing this
        //as the LastMouseMode should be correct.
        SelectMarkerIndex = parseInt(objSelect.value);
        ClickMode = parseInt(objSelect.value);
    }
 
    
    //Left mouse button function 1 Show info, 2 Add, 3 Delete, 4 Not used
    switch (ClickMode) {
//xxx
        case 2:

            try {
                en = osMap.getLonLatFromViewPortPx(osMap.events.getMousePosition(evt));
                easting = en.lon;
                northing = en.lat;
            }
            catch (e) {
                alert("addNew \nmode 2\nfailed \nen = osMap.getLonLatFromViewPortPx(osMap.events.getMousePosition(evt));");
            }
            
            //alert("addNew \nmode 2\neasting = " + en.lon + "northing = " + en.lat);
  
             try {
                pt = osMap.getLonLatFromViewPortPx(evt.xy);
            }
            catch (e) {
                alert("addNew \nmode 2\nfailed \npt = osMap.getLonLatFromViewPortPx(evt.xy);");
            }

            try {
                lonlat = gridProjection.getLonLatFromMapPoint(pt);
            }
            catch (e) {
                alert("addNew \nmode 2\nfailed \nlonlat = gridProjection.getLonLatFromMapPoint(pt);");
            }
            
            //alert("e=" + easting + " n=" + northing + "\n" +
            //  "E: " + pt.lon + "\n" +
            //  "N: " + pt.lat + "\n" +
            //  "LON: " + lonlat.lon + "\n" +
            //  "LAT: " + lonlat.lat);
            marker = addMarker(pt.lon, pt.lat, lonlat.lon, lonlat.lat);

            break;

        //this is case 3 now set to 10 to disable 
//??????????????????????????????????????????????????????????
        case 10:
            //3 Delete.
            try {
                en = osMap.getLonLatFromViewPortPx(osMap.events.getMousePosition(evt));
                easting = en.lon;
                northing = en.lat;
            }
            catch (e) {
                alert("addNew \nmode 3\nfailed \nen = osMap.getLonLatFromViewPortPx(osMap.events.getMousePosition(evt));");
            }
            //en = osMap.getLonLatFromViewPortPx(osMap.events.getMousePosition(evt));


            try {
                pt = osMap.getLonLatFromViewPortPx(evt.xy);
            }
            catch (e) {
                alert("addNew \nmode 3\nfailed \npt = osMap.getLonLatFromViewPortPx(evt.xy);");
            }

            lonlat = gridProjection.getLonLatFromMapPoint(pt);
            //alert("e=" + easting + " n=" + northing + "\n" +
            //  "E: " + pt.lon + "\n" +
            //  "N: " + pt.lat + "\n" +
            //  "LON: " + lonlat.lon + "\n" +
            //  "LAT: " + lonlat.lat);

            //Found the point.
            //contents = "User point index No. " + DIndex + "\n\n";
            //contents += getPointInfoNL(DIndex);
            var contents = "addNew \nmode 3\nDelete point ?";

            //Ask if the point should be deleted.

            if (confirm(contents)) {
                //markers.removeMarker(evt);
                //markers.destroy(evt);
                //alert("addNew \nmode 3\nDeleted the point ?");
                alert("This function has been removed");
            }
            else {
                //marker.openInfoWindowHtml(displayString);
            }


            showstatusdiv("");
            break;


        default:
            break;
    }
}
     
     
function deletePoint(pIndex)
{
    alert("deletePoint " + pIndex);
    
    if((aLat[pIndex]== 0) && (aLon[pIndex]== 0))
    {
        alert("Point " + pIndex + " is not in use ");
    }
    
    if(pIndex>ArrayIndex)
    {
        alert("Error: The point index refers to a memory location\nthat is outside the list of the used points.");
    }
    else
    {
        //Save the point info for user confirmation prompt later on.
        var userText = "User point index No. "+ pIndex +"\n\n";
        userText += getPointInfoNL(pIndex) +  "\n\nhas been deleted.";;
        

         clickedMarker.closeInfoWindow();
         clickedMarker.remove();
         

       //Shift points up one removing the point to be deleted.
        
        for (a = pIndex; a<ArrayIndex; a++)
        {
            if (a>1998)
            {
              aLat[a] = 0;  
                aLon[a] = 0;
                aName[a] = "";
                ADesc[a] = "";
                break;
            }
        
            aLat[a]= aLat[a+1];
            aLon[a]= aLon[a+1];
            aName[a]= aName[a+1];
            ADesc[a]= ADesc[a+1];
        }
        if (ArrayIndex>0)
        {
           ArrayIndex--; 
        }
         else
         {
            alert("Error: Call to deletePoint function with ArrayIndex < 0");
         }
         
         alert(userText);
    }
    
}    
   

function addMarker(easting, northing, lon, lat) {
    // British National Grid OSGB36 to WGS84
    var Mypos = gridProjection.getMapPointFromLonLat(new OpenLayers.LonLat(lon, lat));
    var lonlat = gridProjection.getLonLatFromMapPoint(Mypos);

    aLat[ArrayIndex] = lonlat.lat;
    aLon[ArrayIndex] = lonlat.lon;
    aName[ArrayIndex] = "Name " + (ArrayIndex+1);
    aDesc[ArrayIndex] = "Desc " + (ArrayIndex+1);

    var source_name = "Made by clicking";
    try {
        var pos = new OpenSpace.MapPoint(easting, northing);
    }
    catch (e) {
        //This try is only here to allow the page to run offline.
    }
    var MyDate = new Date();
    var content = "ID" + (ArrayIndex + 1) + "-" + MyDate.getHours() + "-" + MyDate.getMinutes() + "-" + MyDate.getSeconds();
    aID[ArrayIndex] = content;
    content += ":<br /><div><b>Name:</b> " + aName[ArrayIndex] + "<br /><b>Desc:</b> " + aDesc[ArrayIndex] + "<br /><b>Location:</b> " + parseFloat(easting).toFixed(4) + ", " + parseFloat(northing).toFixed(4) + "<br /><b>Lat:</b> " + parseFloat(aLat[ArrayIndex]).toFixed(6) + "<br /><b>Lon:</b> " + parseFloat(aLon[ArrayIndex]).toFixed(6) + "</div>";
    // try {
        //Have to create the markers on osMap.
        var size = new OpenLayers.Size(33, 45);
        var offset = new OpenLayers.Pixel(-16, -37);
        var infoWindowAnchor = new OpenLayers.Pixel(16, 16);

        var icon = new OpenSpace.Icon('http://openspace.ordnancesurvey.co.uk/osmapapi/img/OS/images/markers/marker_blue.png', size, offset, null, infoWindowAnchor);
        
        var marker = osMap.createMarker(pos, icon.clone(), content);
        aMarker[ArrayIndex] = marker;

        //Store the marker object so that we have
        //a reference to it
        //to allow deletion.

        //set index for edit window in mode 5.

        SelectMarkerIndex = ArrayIndex + 1;
        LastMarkerIndex = ArrayIndex + 1;
        ArrayIndex++;
        WindowState = 5;
        showstatusdiv("");
        
  
        //var markersarray = osMap.markerLayer.markers;
        //alert("2 osMap.markerLayer.markers length = " + markersarray.length);
        
        return (marker);
    //}
    //catch (e) {
        //This try is only here to allow the page to run offline.
    //}

    
    return (null);
      
}

function mousedown(evt) {
    //xxx

    //The InfoWindow is opened by the default event handler.
    
    var MyInfoWindow = oMarkerEventInfo.map.getInfoWindow();

    //Close the InfoWindow so that it does not remain behind
    //after the marker has been deleted.
    
    oMarkerEventInfo.map.closeInfoWindow();
    
    var content = MyInfoWindow.contentHTML; 	//"ID1-20-56-40:<br /><div><b>Name:</b> Name 2<br /><b>Desc:</b> Desc 2<br /><b>Location:</b> 419425.0000, 382915.0000<br /><b>Lat:</b> 53.342799<br /><b>Lon:</b> -1.709706</div>"	String
    var the_array = content.split(":");
    var contentID = the_array[0];

        for (Index = 0; Index < ArrayIndex; Index++) {
            if (aID[Index] == contentID) {
                //Need to add 1 because DeleteMarker subtracts 1.
                LastMarkerIndex = (Index + 1);
                DeleteMarker();
                return;
            }
        }

        alert("mousedown\nCould not match ID");
    //OpenLayers.Event.stop(evt);
}   

//Adds a marker copying data from the pName... variables etc.
function addPMarker(easting, northing, lon, lat) {
    var id = ArrayIndex;
    aLat[ArrayIndex] = lat;
    aLon[ArrayIndex] = lon;
    aName[ArrayIndex] = pName[ArrayIndex];
    aDesc[ArrayIndex] = pDesc[ArrayIndex];

    try {
        var pos = new OpenSpace.MapPoint(easting, northing);
    }
    catch (e) {
        //This try is only here to allow the page to run offline.
    }

    var MyDate = new Date();
    var content = "ID" + (ArrayIndex+1) + "-" + MyDate.getHours() + "-" + MyDate.getMinutes() + "-" + MyDate.getSeconds() ;
    aID[ArrayIndex] = content;
    content += ":<br /><div><b>Name:</b> " + aName[ArrayIndex] + "<br /><b>Desc:</b> " + aDesc[ArrayIndex] + "<br /><b>Location:</b> " + parseFloat(easting).toFixed(4) + ", " + parseFloat(northing).toFixed(4) + "<br /><b>Lat:</b> " + parseFloat(aLat[ArrayIndex]).toFixed(6) + "<br /><b>Lon:</b> " + parseFloat(aLon[ArrayIndex]).toFixed(6) + "</div>";
    // try {
    //Have to create the markers on osMap.
    var size = new OpenLayers.Size(33, 45);
    var offset = new OpenLayers.Pixel(-16, -37);
    var infoWindowAnchor = new OpenLayers.Pixel(16, 16);

    var icon = new OpenSpace.Icon('http://openspace.ordnancesurvey.co.uk/osmapapi/img/OS/images/markers/marker_blue.png', size, offset, null, infoWindowAnchor);

    var marker = osMap.createMarker(pos, icon.clone(), content);
    aMarker[ArrayIndex] = marker;

    //Store the marker object so that we have
    //a reference to it
    //to allow deletion.

    //set index for edit window in mode 5.

    SelectMarkerIndex = ArrayIndex + 1;
    LastMarkerIndex = ArrayIndex + 1;
    ArrayIndex++;
    WindowState = 5;
    showstatusdiv("");


    //var markersarray = osMap.markerLayer.markers;
    //alert("1 osMap.markerLayer.markers length = " + markersarray.length);

    return (marker);
    //}
    //catch (e) {
    //This try is only here to allow the page to run offline.
    //}


    return (null);
  
}


 function SetClickMode() {
     //Left mouse button marker function 1 Show info, 2 Add, 3 Delete, 4 Not used
     
     objSelect = document.getElementById("SelectMenu");
     if (objSelect === null) {
         alert("Failed to get list SelectMenu object");
         return;
     }

     ClickMode = parseInt(objSelect.value);
     switch (ClickMode) {

         case 3:
             //remove all the marker events.
             if (osMap.markerLayer.markers.length > 0) {
                 for (var i = 0; i < osMap.markerLayer.markers.length; i++) {
                     var marker = osMap.markerLayer.markers[i];

                     //Leave the infowindow popup so I can get at it.   
                     //marker.events.remove("mousedown");

                     marker.events.register("mousedown", { marker: marker }, function(evt) {
                         oMarkerEventInfo = this.marker;
                         mousedown(evt);
                     });

                 }
             }
             LastMouseMode = 3;
             break;


         case 2: //2 Add
             if (LastMouseMode == 3) {
                 reloadinfoWindow()
             }
         
             LastMouseMode = 2;
             break;
             

         default:
             if (LastMouseMode == 3) {
                 reloadinfoWindow()
             }
             LastMouseMode = 0;
             break;
             
             
     }

 }

//Select the index of the marker info to be displayed in the info/edit window in mode 5.
 function SetMarkerDisplay() {
     objSelect = document.getElementById("SelectMarker");
     if (objSelect === null) {
         alert("Failed to get list SelectMarker object");
         return;
     }

     SelectMarkerIndex = parseInt(objSelect.value);
     LastMarkerIndex = parseInt(objSelect.value);
     showstatusdiv("");
 }

 function MyParse() {
     //The text box InputGPX contains the user source GPX.
     var MyLine;
     var AllTheXML;
     var pointType;
     var a;
     var latIndex;
     var latLength;
     var lonIndex;
     var lonLength;
     var nameIndex1;
     var nameIndex2;
     var maxLoop;
     var minlon;
     var maxlon;
     var minlat;
     var maxlat;

     //Make sure all the track points are zero.

     for (a = 0; a < 2000; a++) {
         pLat[a] = 0;
         pLon[a] = 0;
         pName[a] = "";
         pDesc[a] = "";

     }

     pArrayIndex = 0;
     ArrayIndex = 0;

     AllTheXML = document.getElementById("InputGPX").value

     //Flag if it is route or track gpx file.

     latIndex = AllTheXML.search("<rte>");
     if (latIndex > -1) {
         pointType = "<rtept";
     }
     else {
         //If not a route file then presume its a track file.
         pointType = "<trkpt";
     }
     //Split the file in to seperate pieces

     var XMLArray = document.getElementById("InputGPX").value.split(pointType);
     var XMLArrayLineCount = XMLArray.length;

     maxLoop = 1999;
     if (XMLArrayLineCount < maxLoop) {
         maxLoop = XMLArrayLineCount;
     }
     else {
         alert("Your .gpx data contains " + XMLArrayLineCount + " entries.\nOnly the first 1999 will be used.");
     }

     minlon = 179;
     maxlon = -179;
     minlat = 90;
     maxlat = -90;
     
     for (a = 1; a < XMLArrayLineCount; a++) {

         latIndex = XMLArray[a].search("lat=");
         if (latIndex > -1) {
             //Need to limit the number of decimal places to six
             //otherwise the markers are not clickable.

             //Increment the count of the number of user points.
             pArrayIndex += 1;


             b = parseFloat(XMLArray[a].substring(latIndex + 5));

             pLat[a - 1] = parseFloat(b.toFixed(6));

             if (pLat[a - 1] < minlat) {
                 minlat = pLat[a - 1];
             }
             if (pLat[a - 1] > maxlat) {
                 maxlat = pLat[a - 1];
             }
         }
         else {
             pLat[a - 1] = 0;
         }

         lonIndex = XMLArray[a].search("lon=");
         if (lonIndex > -1) {
             //Need to limit the number of decimal places to six 
             //otherwise the markers are not clickable.

             b = parseFloat(XMLArray[a].substring(lonIndex + 5));

             pLon[a - 1] = parseFloat(b.toFixed(6));

             if (pLon[a - 1] < minlon) {
                 minlon = pLon[a - 1];
             }
             if (pLon[a - 1] > maxlon) {
                 maxlon = pLon[a - 1];
             }


         }
         else {
             pLon[a - 1] = 0;

         }

         // e.g. <name>Track001</name>
         nameIndex1 = XMLArray[a].search("<name>") + 6;
         nameIndex2 = XMLArray[a].search("</name>");
         if (((nameIndex1 > -1) && (nameIndex2 > -1))
                && (nameIndex2 > nameIndex1)) {
             pName[a - 1] = XMLArray[a].substr(nameIndex1, nameIndex2 - nameIndex1);
         }
         else {
             // Can't find the name so use the default.
             pName[a - 1] = "Trk" + a;
         }

         // e.g. <desc>Track001</desc>
         nameIndex1 = XMLArray[a].search("<desc>") + 6;
         nameIndex2 = XMLArray[a].search("</desc>");
         if (((nameIndex1 > -1) && (nameIndex2 > -1))
                && (nameIndex2 > nameIndex1)) {
             pDesc[a - 1] = XMLArray[a].substr(nameIndex1, nameIndex2 - nameIndex1);
         }
         else {
             //Didn't find a <desc> perhaps there's a <cmt> section
             //use that instead.
             // e.g. <cmt>Track001</cmt>
             nameIndex1 = XMLArray[a].search("<cmt>") + 5;
             nameIndex2 = XMLArray[a].search("</cmt>");
             if (((nameIndex1 > -1) && (nameIndex2 > -1))
                        && (nameIndex2 > nameIndex1)) {
                 pDesc[a - 1] = XMLArray[a].substr(nameIndex1, nameIndex2 - nameIndex1);
             }
             else {
                 // Can't find the desc or cmt so use the default.
                 pDesc[a - 1] = "Desc " + a;
             }
         }
     }


     if (pArrayIndex > 1) {
         //document.getElementById("GetDataStatus").innerHTML = "Imported " + pArrayIndex + " co-ordinates from your .gpx data.";
         alert("Imported " + pArrayIndex + " co-ordinates from your .gpx data.");
     }
     else {
         alert("No track or route points found\nexpect to find one of (<trkpt> or <rtept>).\nDid you copy a valid .gpx into white box ?");
         return;
     }

     //Make sure all the track points are zero.

     for (a = 0; a < 2000; a++) {
         aLat[a] = 0;
         aLon[a] = 0;
         aName[a] = "";
         aDesc[a] = "";
         aMarker[a] = null;
         aID[a] = "";
     }
     ArrayIndex = 0;

     if (osMap != null) {
         //fClearDirections()
         //map.clearOverlays(); //This clears everything including points,
     }
     
     //Re-add the user markers to the map.
     for (a = 0; a < pArrayIndex; a++) {
 
         //getMapPointFromLonLat	Convert an WGS84 point into a OSGB36 grid point
         var lonlat = new OpenLayers.LonLat(pLon[a], pLat[a]);
         var mapPoint = gridProjection.getMapPointFromLonLat(lonlat);
         addPMarker(parseFloat(mapPoint.getEasting()), mapPoint.getNorthing(), pLon[a], pLat[a]);
     }
   
        //Center the map on the middle of the route.
     middleLon = ((maxlon + minlon) / 2);
     middleLat = ((maxlat + minlat) / 2);
      
       //WGS84 to OSGrid EN.
    lonlat = new OpenLayers.LonLat(middleLon, middleLat);
    mapPoint = gridProjection.getMapPointFromLonLat(lonlat);
     osMap.setCenter(mapPoint, 7);
  
     WindowState = 5;
     showstatusdiv("");


 }
 
Number.prototype.toRad = function() {
// convert degrees to radians
return this * Math.PI / 180;
}

Number.prototype.toDeg = function() {
// convert radians to degrees (signed)
return this * 180 / Math.PI;
}



    
  
 /*
 * convert OS grid reference to geodesic co-ordinates
 */
// convert standard grid reference ('SU387148') to fully numeric ref ([438700,114800])

 function MyOSGridToLatLong(Easting, Northing) {
     var E = Easting, N = Northing;

     var a = 6377563.396, b = 6356256.910;              // Airy 1830 major & minor semi-axes
     var F0 = 0.9996012717;                             // NatGrid scale factor on central meridian
     var lat0 = 49 * Math.PI / 180, lon0 = -2 * Math.PI / 180;  // NatGrid true origin
     var N0 = -100000, E0 = 400000;                     // northing & easting of true origin, metres
     var e2 = 1 - (b * b) / (a * a);                          // eccentricity squared
     var n = (a - b) / (a + b), n2 = n * n, n3 = n * n * n;

     var lat = lat0, M = 0;
     do {
         lat = (N - N0 - M) / (a * F0) + lat;

         var Ma = (1 + n + (5 / 4) * n2 + (5 / 4) * n3) * (lat - lat0);
         var Mb = (3 * n + 3 * n * n + (21 / 8) * n3) * Math.sin(lat - lat0) * Math.cos(lat + lat0);
         var Mc = ((15 / 8) * n2 + (15 / 8) * n3) * Math.sin(2 * (lat - lat0)) * Math.cos(2 * (lat + lat0));
         var Md = (35 / 24) * n3 * Math.sin(3 * (lat - lat0)) * Math.cos(3 * (lat + lat0));
         M = b * F0 * (Ma - Mb + Mc - Md);                // meridional arc

     } while (N - N0 - M >= 0.00001);  // ie until < 0.01mm

    var cosLat = Math.cos(lat), sinLat = Math.sin(lat);
     var nu = a * F0 / Math.sqrt(1 - e2 * sinLat * sinLat);              // transverse radius of curvature
     var rho = a * F0 * (1 - e2) / Math.pow(1 - e2 * sinLat * sinLat, 1.5);  // meridional radius of curvature
     var eta2 = nu / rho - 1;

     var tanLat = Math.tan(lat);
     var tan2lat = tanLat * tanLat, tan4lat = tan2lat * tan2lat, tan6lat = tan4lat * tan2lat;
     var secLat = 1 / cosLat;
     var nu3 = nu * nu * nu, nu5 = nu3 * nu * nu, nu7 = nu5 * nu * nu;
     var VII = tanLat / (2 * rho * nu);
     var VIII = tanLat / (24 * rho * nu3) * (5 + 3 * tan2lat + eta2 - 9 * tan2lat * eta2);
     var IX = tanLat / (720 * rho * nu5) * (61 + 90 * tan2lat + 45 * tan4lat);
     var X = secLat / nu;
     var XI = secLat / (6 * nu3) * (nu / rho + 2 * tan2lat);
     var XII = secLat / (120 * nu5) * (5 + 28 * tan2lat + 24 * tan4lat);
     var XIIA = secLat / (5040 * nu7) * (61 + 662 * tan2lat + 1320 * tan4lat + 720 * tan6lat);

     var dE = (E - E0), dE2 = dE * dE, dE3 = dE2 * dE, dE4 = dE2 * dE2, dE5 = dE3 * dE2, dE6 = dE4 * dE2, dE7 = dE5 * dE2;
     lat = lat - VII * dE2 + VIII * dE4 - IX * dE6;
     var lon = lon0 + X * dE - XI * dE3 + XII * dE5 - XIIA * dE7;
     var test = new LatLon(lat.toDeg(), lon.toDeg(), 0);
     return OGBToWGS84(test.lat, test.lon, 0);
 }


 function OGBLatLng(lat, lon) {
     this.lat = lat;
     this.lon = lon;
 }

 function WGS84LatLng(lat, lon) {
     this.lat = lat;
     this.lon = lon;
 }

 function OGBNorthEast(east, north) {
     this.north = north;
     this.east = east;
 }

 function OGBRect(bottomLeft, topRight) {
     this.bl = bottomLeft;
     this.tr = topRight;
 }



 //convert WGS84 Latitude and Longitude to Ordnance Survey 1936 Latitude Longitude

 function WGS84ToOGB(WGlat, WGlon, height) {
     var deg2rad = Math.PI / 180;
     var rad2deg = 180.0 / Math.PI;

     //first off convert to radians
     var radWGlat = WGlat * deg2rad;
     var radWGlon = WGlon * deg2rad;
     //these are the values for WGS84(GRS80) to OSGB36(Airy)
     var a = 6378137; // WGS84_AXIS
     var e = 0.00669438037928458; // WGS84_ECCENTRIC
     var h = height; // height above datum (from $GPGGA sentence)
     var a2 = 6377563.396; // OSGB_AXIS
     var e2 = 0.0066705397616; // OSGB_ECCENTRIC 
     var xp = -446.448;
     var yp = 125.157;
     var zp = -542.06;
     var xr = -0.1502;
     var yr = -0.247;
     var zr = -0.8421;
     var s = 20.4894;

     // convert to cartesian; lat, lon are in radians
     var sf = s * 0.000001;
     var v = a / (Math.sqrt(1 - (e * (Math.sin(radWGlat) * Math.sin(radWGlat)))));
     var x = (v + h) * Math.cos(radWGlat) * Math.cos(radWGlon);
     var y = (v + h) * Math.cos(radWGlat) * Math.sin(radWGlon);
     var z = ((1 - e) * v + h) * Math.sin(radWGlat);

     // transform cartesian
     var xrot = (xr / 3600) * deg2rad;
     var yrot = (yr / 3600) * deg2rad;
     var zrot = (zr / 3600) * deg2rad;
     var hx = x + (x * sf) - (y * zrot) + (z * yrot) + xp;
     var hy = (x * zrot) + y + (y * sf) - (z * xrot) + yp;
     var hz = (-1 * x * yrot) + (y * xrot) + z + (z * sf) + zp;

     // Convert back to lat, lon
     var newLon = Math.atan(hy / hx);
     var p = Math.sqrt((hx * hx) + (hy * hy));
     var newLat = Math.atan(hz / (p * (1 - e2)));
     v = a2 / (Math.sqrt(1 - e2 * (Math.sin(newLat) * Math.sin(newLat))));
     var errvalue = 1.0;
     var lat0 = 0;
     while (errvalue > 0.001) {
         lat0 = Math.atan((hz + e2 * v * Math.sin(newLat)) / p);
         errvalue = Math.abs(lat0 - newLat);
         newLat = lat0;
     }

     //convert back to degrees
     newLat = newLat * rad2deg;
     newLon = newLon * rad2deg;

     return new OGBLatLng(newLat, newLon);

 }


 //convert Ordnance Survey 1936 Latitude Longitude to WGS84 Latitude and Longitude

 function OGBToWGS84(OGlat, OGlon, height) {
     var deg2rad = Math.PI / 180;
     var rad2deg = 180.0 / Math.PI;

     //first off convert to radians
     var radOGlat = OGlat * deg2rad;
     var radOGlon = OGlon * deg2rad;
     //these are the values for WGS84(GRS80) to OSGB36(Airy)

     var a2 = 6378137; // WGS84_AXIS
     var e2 = 0.00669438037928458; // WGS84_ECCENTRIC

     var h = height; // height above datum (from $GPGGA sentence)

     var a = 6377563.396; // OSGB_AXIS
     var e = 0.0066705397616; // OSGB_ECCENTRIC 

     var xp = 446.448;
     var yp = -125.157;
     var zp = 542.06;
     var xr = 0.1502;
     var yr = 0.247;
     var zr = 0.8421;

     var s = -20.4894;

     // convert to cartesian; lat, lon are in radians
     var sf = s * 0.000001;
     var v = a / (Math.sqrt(1 - (e * (Math.sin(radOGlat) * Math.sin(radOGlat)))));
     var x = (v + h) * Math.cos(radOGlat) * Math.cos(radOGlon);
     var y = (v + h) * Math.cos(radOGlat) * Math.sin(radOGlon);
     var z = ((1 - e) * v + h) * Math.sin(radOGlat);

     // transform cartesian
     var xrot = (xr / 3600) * deg2rad;
     var yrot = (yr / 3600) * deg2rad;
     var zrot = (zr / 3600) * deg2rad;
     var hx = x + (x * sf) - (y * zrot) + (z * yrot) + xp;
     var hy = (x * zrot) + y + (y * sf) - (z * xrot) + yp;
     var hz = (-1 * x * yrot) + (y * xrot) + z + (z * sf) + zp;

     // Convert back to lat, lon
     var newLon = Math.atan(hy / hx);
     var p = Math.sqrt((hx * hx) + (hy * hy));
     var newLat = Math.atan(hz / (p * (1 - e2)));
     v = a2 / (Math.sqrt(1 - e2 * (Math.sin(newLat) * Math.sin(newLat))));
     var errvalue = 1.0;
     var lat0 = 0;
     while (errvalue > 0.001) {
         lat0 = Math.atan((hz + e2 * v * Math.sin(newLat)) / p);
         errvalue = Math.abs(lat0 - newLat);
         newLat = lat0;
     }

     //convert back to degrees
     newLat = newLat * rad2deg;
     newLon = newLon * rad2deg;

     return new WGS84LatLng(newLat, newLon);

 }


 

 // construct a LatLon object: arguments in numeric degrees
 // note all LatLong methods expect & return numeric degrees
 // (for lat/long & for bearings)
 function LatLon(lat, lon, height) {
     if (arguments.length < 3) height = 0;
     this.lat = lat;
     this.lon = lon;
     this.height = height;
 } 
 
 // construct a NorthEast object
 function NorthEast(Northing, Easting) {
     this.Northing = Northing;
     this.Easting = Easting;
 }

 //Fills the OutputGPX div with a .gpx route list of the user points.
 function onGPXRoute() {
     var userText = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
     userText += "<gpx\n";
     userText += "version=\"1.0\"\n";
     userText += "creator=\"http://www.stevematt.f9.co.uk/osmap/\"\n";
     userText += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     userText += "xmlns=\"http://www.topografix.com/GPX/1/0\"\n";
     userText += "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0/gpx.xsd\">\n";
     userText += "<rte>\n";
     userText += "  <name>WGS84 Route</name>\n";


     for (a = 0; a < ArrayIndex; a++) {
         userText += "<rtept lat=\"" + parseFloat(aLat[a]).toFixed(6) + "\" lon=\"" + parseFloat(aLon[a]).toFixed(6) + "\">\n";
         userText += "<name>" + aName[a] + "</name>\n";
         userText += "<desc>" + aDesc[a] + "</desc>\n";
         userText += "</rtept>\n";

     }
     userText += "</rte>\n</gpx>\n";

     //document.getElementById("OutputGPX").innerText = userText;
     document.getElementById("OutputGPX").value = userText;

     try {
         window.clipboardData.setData("Text", userText);
         alert("The GPX route text has been copied into the windows paste buffer.");

     }
     catch (e) {
         //This try is only here to allow the page in other browsers.
     }

 }

 //Fills the OutputGPX div with a .gpx waypoint list of the user points.
 function onGPXWpt() {
     var userText = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
     userText += "<gpx\n";
     userText += "version=\"1.0\"\n";
     userText += "creator=\"http://www.stevematt.f9.co.uk/osmap/\"\n";
     userText += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     userText += "xmlns=\"http://www.topografix.com/GPX/1/0\"\n";
     userText += "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0/gpx.xsd\">\n";
     userText += "  <name>WGS84 Waypoint</name>\n";


     for (a = 0; a < ArrayIndex; a++) {
         userText += "<wpt lat=\"" + parseFloat(aLat[a]).toFixed(6) + "\" lon=\"" + parseFloat(aLon[a]).toFixed(6) + "\">\n";
         userText += "<name>" + aName[a] + "</name>\n";
         userText += "<desc>" + aDesc[a] + "</desc>\n";
         userText += "</wpt>\n";

     }
     userText += "</gpx>\n";

     //document.getElementById("OutputGPX").innerText = userText;
     document.getElementById("OutputGPX").value = userText;

     try {
         window.clipboardData.setData("Text", userText);
         alert("The GPX waypoint text has been copied into the windows paste buffer.");

     }
     catch (e) {
         //This try is only here to allow the page in other browsers.
     }

 }
 //Fills the OutputGPX div with a GPSSC route of the user points.
 function onGPXGPSSC() {
     var userText = ";New GPSSC Route" + "\n";

     for (a = 0; a < ArrayIndex; a++) {
         userText += parseFloat(aLon[a]).toFixed(6) + "," + parseFloat(aLat[a]).toFixed(6) + ",";


         nameIndex1 = aName[a].indexOf("<![CDATA[");

         if (nameIndex1 > -1) {
             nameIndex2 = aName[a].indexOf("]]>");
             if (nameIndex2 > -1) {
                 nameIndex1 += 9;

                 if (nameIndex2 > nameIndex1) {
                     userText += aName[a].substr(nameIndex1, nameIndex2 - nameIndex1) + ",";
                 }
                 else {
                     userText += ",";
                 }

             }
         }
         else {
             userText += aName[a] + ",";
         }

         // e.g. <![CDATA[Desc01]]> or just text

         nameIndex1 = aDesc[a].indexOf("<![CDATA[");

         if (nameIndex1 > -1) {
             nameIndex2 = aDesc[a].indexOf("]]>");
             if (nameIndex2 > -1) {
                 nameIndex1 += 9;

                 if (nameIndex2 > nameIndex1) {
                     userText += aDesc[a].substr(nameIndex1, nameIndex2 - nameIndex1) + "\n,";
                 }
                 else {
                     userText += "\n";
                 }

             }
         }
         else {
             userText += aDesc[a] + "\n";
         }


     }
     //document.getElementById("OutputGPX").innerHTML = userText;
     //document.getElementById("OutputGPX").innerText = userText;
     document.getElementById("OutputGPX").value = userText;


     try {
         window.clipboardData.setData("Text", userText);
         alert("The GPSSC route text has been copied into the windows paste buffer.");

     }
     catch (e) {
         //This try is only here to allow the page in other browsers.
     }
 }



 //Fills the OutputGPX div with a .gpx track list of the user points.
 function onGPXTrack() {

     var userText = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
     userText += "<gpx\n";
     userText += "version=\"1.0\"\n";
     userText += "creator=\"http://www.stevematt.f9.co.uk/osmap/\"\n";
     userText += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     userText += "xmlns=\"http://www.topografix.com/GPX/1/0\"\n";
     userText += "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0/gpx.xsd\">\n";
     userText += "<trk>\n"
     userText += "  <name>WGS84 Track</name>\n";
     userText += "<trkseg>";


     for (a = 0; a < ArrayIndex; a++) {
         userText += "<trkpt lat=\"" + parseFloat(aLat[a]).toFixed(6) + "\" lon=\"" + parseFloat(aLon[a]).toFixed(6) + "\">\n";
         userText += "<ele>0.0</ele>";
         userText += "<time>2008-03-30T13:00:00Z</time>\n";
         userText += "</trkpt>\n";
     }
     userText += "</trkseg>\n</trk>\n</gpx>\n";

     //document.getElementById("OutputGPX").innerText = userText;
     document.getElementById("OutputGPX").value = userText;

     try {
         window.clipboardData.setData("Text", userText);
         alert("The GPX track text has been copied into the windows paste buffer.");

     }
     catch (e) {
         //This try is only here to allow the page in other browsers.
     }


 }

 function reloadinfoWindow() {

     for (var loopx = 0; loopx < osMap.markerLayer.markers.length; loopx++) {
         var marker = osMap.markerLayer.markers[loopx];
         marker.events.remove("mousedown");
         //var MyInfoWindow = marker.map.getInfoWindow();
         //var html = MyInfoWindow.contentHTML; 	//"ID1-20-56-40:<br /><div><b>Name:</b> Name 2<br /><b>Desc:</b> Desc 2<br /><b>Location:</b> 419425.0000, 382915.0000<br /><b>Lat:</b> 53.342799<br /><b>Lon:</b> -1.709706</div>"	String
         var size = new OpenLayers.Size(200, 200);
         var html = aID[loopx] + ":<br />" + aName[loopx] + "<br />" + aDesc[loopx] + "<br />" + aLat[loopx].toFixed(6) + "<br />" + aLon[loopx].toFixed(6);
         marker.events.register("mousedown", { marker: marker, html: html, size: size }, function(evt) {
             this.marker.map.closeInfoWindow();
             this.marker.map.openInfoWindow(this.marker.icon, this.marker.lonlat, this.html, this.size);
             
             OpenLayers.Event.stop(evt);
         });         
      }
      //alert("marker.events.register'd ok");
    
 }

 //Updates the Infowindow for this marker by re-registering it's mousedown event.
 function SaveinfoWindow() {

     var loopx = LastMarkerIndex - 1; 
         var marker = osMap.markerLayer.markers[loopx];
         marker.events.remove("mousedown");
         var size = new OpenLayers.Size(200, 200);
         var html = aID[loopx] + ":<br />" + aName[loopx] + "<br />" + aDesc[loopx] + "<br />" + aLat[loopx].toFixed(6) + "<br />" + aLon[loopx].toFixed(6);
         marker.events.register("mousedown", { marker: marker, html: html, size: size }, function(evt) {
             this.marker.map.closeInfoWindow();
             this.marker.map.openInfoWindow(this.marker.icon, this.marker.lonlat, this.html, this.size);
             OpenLayers.Event.stop(evt);
         });
 }

 //5 Numeric marker names
 function SetNumericNames()
 {
     if (confirm("This will set all the marker names\nto a short number series\nsuitable for older GPS's")) {

         var Start = parseInt(prompt("Enter a start number for the series", 1));

         for (i = 0; i <= ArrayIndex; i++) {
             aName[i] = "" + Start;
             Start++;
         }
 
         reloadinfoWindow();
         alert("Marker name numbering is complete");
     }


 }
     
 function RemoveosMapMarkerEvents()
 {
     for (var loopx = 0; loopx < osMap.markerLayer.markers.length; loopx++) {
         var marker = osMap.markerLayer.markers[loopx];
         marker.events.remove("mousedown");
     }
 }  


 function DoDebug()
 {
     //any single debug code can be out in here.

     alert("There are no debug functions.");
     return;
     
    var lat  = new Array(51,52,53); 
    var lon  = new Array(1,2,3);
    var name  = new Array("N One","N two","N three");
    var desc = new Array("N junk", "N ham", "N cheese");
    
     for (a = 0; a < 3; a++) {
         aLat[a] = lat[a];
         aLon[a] = lon[a];
         aName[a] = name[a];
         aDesc[a] = desc[a];
         aMarker[a] = null;
         aID[a] = "";
     }
     ArrayIndex = a;
     alert("Made 3 fake markers");
     return;

 
 }
 
 function SetMenuMode() {
     //1 Search for place";
     //2 Edit markers";
     //3 Import GPX";
     //4 Export GPX";
     //5 Numeric marker names
     //6.12 Distances between markers.     
     //11 Mode 1 test";
     //12 Mode 2 test";
     //13 Mode 3 test";
     //14 Mode 4 test";
     //15 Mode 5 test";
     //20 Convert Longitude to Easting
     //30 Print


     objSelect = document.getElementById("MenuDropDown");
     if (objSelect === null) {
         alert("Failed to get MenuDropDown object");
         return;
     }
     
     //MenuIndex will be of type string.
     //change to int.
     MenuIndex = parseInt(objSelect.value);
 
     switch (MenuIndex) {

         case 11:
         case 12:
         case 13:
         case 14:
         case 15:
             WindowState = MenuIndex - 10;

             showstatusdiv("");
             break;

         case 1:
             WindowState = 1;    //Search for place.
             showstatusdiv("");
             break;

         case 2:             //Edit markers

             //LastMarkerIndex = 0;
             WindowState = 4;
             showstatusdiv("");
             break;

         case 3:
             WindowState = 6;    //6 get GPX.
             showstatusdiv("Get GPX");
             break;

         case 4:
             WindowState = 7;    //7 export GPX.
             showstatusdiv("Export GPX");
             break;

         case 5:

             //5 Numeric marker names
             SetNumericNames();
             showstatusdiv("");
             break;

         case 6:
             WindowState = 12;  //6.12 Distances between markers.
             showstatusdiv("");
             break;
             

         case 20:


             WindowState = 8;     //20 Convert Longitude to Easting
             showstatusdiv("Convert Longitude to/from Easting");
             break;

         case 30:


             //30 Print
             //remove both statusbox and TopDiv ready for printing.
             var statusbox;
             statusbox = document.getElementById("statusbox");

             if (statusbox != null) {
                 document.body.removeChild(statusbox);
             }

             statusbox = document.getElementById("TheTopDiv");
             if (statusbox != null) {
                 //statusbox.style.height = "1px";
                 //alert("close me");

                 document.body.removeChild(statusbox);
             }

             statusbox = document.getElementById("map");
             if (statusbox != null) {
                 statusbox.style.top = "1px";
             }
             //The click position is out of place after moving the map div.
             //try this to fix it.
             osMap.updateSize();


             //Closing these divs puts thejavascript engine in an error state
             //need to terminate javascript execution here somehow.
             //or perhaps close down other on... stuff.
             //return;
             gExit = 1;
             break;

         case 31:       //31.9 map div size.
             WindowState = 9;     
             showstatusdiv("");
             
             break;

         case 32:       //32.10 Reduce control window to a small button.
             WindowState = 10;
             showstatusdiv("");
             break;
             
         case 33:       //33.11 Bookmark version and date.
             WindowState = 11;
             showstatusdiv("");
             break;

         case 40:       //debug
             DoDebug();

             break;



     }


 }
 


		  

/* main() */

	    //googledoc = loadXMLDoc(googleurl);
	    


