
//List of layers to be added by mapserver
//use the format "input id" : "mapserver layer name"
//FS boundary layer is included in the function LayersChanged()
var layerHash = {
"Theme_EUNIS" : "_EUNIS,_EUNISMASK",
"ThemeCoastalPhysiographic" : "CoastalPhysiographic",
"Theme_OffshoreTopographic" : "_OffshoreTopographic",
"Theme_ChartedBathymetry" : "_ChartedBathymetry",
"Theme_BathymetryLines" : "_BathymetryLines",
"Theme_BGSconfidence" : "_BGSconfidence",
"Theme_BGSSediment" : "_BGSSediment",
"Theme_BGSrock": "_BGSmultibeam,_BGSinferred,_BGSrocksamples",
"Theme_SSTmay" : "_SSTmay",
"Theme_BAP" : "_BAP",
"Theme_Zostera" : "_Zostera",
"Theme_n2k_all" : "_n2k_all",
"Theme_n2k_marine" : "_n2k_marine",
"Theme_UKlimits" : "_UKlimits",
"Theme_MCZprojectboundaries" : "_MCZprojectboundaries",
"Theme_ICESfishing" : "_ICESfishing",
"Theme_ICESstats" : "_ICESstats",
"Theme_FisheriesRestrictions" : "_FisheriesRestrictions",
"Theme_BigFisheriesRestrictions" : "_BigFisheriesRestrictions",
"Theme_Windfarms" : "_Windfarms",
"Theme_Wavehub" : "_Wavehub",
"Theme_AllCommercial" : "_AllCommercial",
"Theme_LobsterPotting" : "_LobsterPotting",
"Theme_AllDivers" : "_AllDivers",
"Theme_AllAnglers" : "_AllAnglers"
}


var gPolyMode = false;
var gsFeatureTypeID = -1;
var lineWeight = 4;
var lineOpacity =.5;
var fillOpacity =.4;
var mapStartCentreY = 50.5;
var mapStartCentreX = -4.0;
var InfoWindow = "";
var polyPoints = [];
var reasons = [];

var geocoder = null;
var GeoAccuracy = [];
var ovcontrol;

//km distance for search result to be included
var mapMaxDistanceKmForSearch = 100;

var webhost= "www.fs.no-ip.com";
var mapLayers = '';
var polyCtrl;

// Location of feature to be used after cloning
var mxCenter;
var myCenter;

var map;

var mapDataLayerURL = 'http://www.fs.no-ip.com/scripts/mapserv.exe?map=D:/Websites/fs2/mapserver/map/WMSFS.map&ESDMGIF=True';

var pageMapWidth = 0;
var pageMapHeight = 0;

var gutterPixelSize = 200; //used for groundoverlay of data

var currentOverlayCenter;//current lat long of groundOverlay (mapData) center point
var currentOverlayZoom; //zoom level current overlay was created for
var overlayBounds = '';
var dataOverlay = '';
var baseOverlay = '';
var baseOverlayOpacity = '1';//doesn't handle 0
var showBaseMap = 1; // 0/1 flag used to decide whether to load client base map or not. Set on loadMapType (google) and used in loadWMSLayers to determine which to load.

var PolyObjects = new Array();

function CloseFeaturesForm() {
    try {
        UpdateFeaturesList();
        map.closeInfoWindow();
        removeMarkerPolys();
        mapLayers =  tempLayers ;
        getWMS();
        //var cp = new GLatLng(mapStartCentreY,mapStartCentreY);
      //  map.setCenter(new GLatLng(50.5, -4.0), 8); 
       // polyCtrl.polygButtonClick.off();
    }
    catch (e) {
        alert(e.message + "CloseFeaturesForm()");
    }
}

function MapObjectSelect(x, y, sFeatureID) {
    var pt = new GLatLng(parseFloat(y), parseFloat(x));
    if (disableInfoTool == false) {
        addInfoTipMarker(pt, sFeatureID);

    }
}

function ShowPolyTool(bVis) {
    try {
        xVisibility('polygonControl', bVis);
        xVisibility('addPolygonDiv', bVis);
        xVisibility('addPolygon', bVis);
    }
    catch(e) {
    }
}
var mylink;
var mapClickListener;
function FeatureTypeSwitch(_type) {
    MarksType = "";
    if (_type == "DP") {
        
        mapClickListener = GEvent.addListener(map, 'click', mapClick);
        
        displayMessage('Click on the map to draw your shape', 'Interactive Map', '300');
        /*if (location.href == "http://www.fs.no-ip.com/tom.aspx" || location.href == "http://www.fs.no-ip.com/tom.aspx#") {
        	displayMessage('Click on the map to draw your shape', 'Interactive Map', '300');
        //	alert("Click on the map to draw your shape.");
        } else {
        	alert("Click on the map to draw your shape");
        }*/

       
    } else if (_type == "SF") {
	    GetWMSMarkerPolys();
    }

    var meta = document.getElementById('Meta');
    meta.innerHTML = "";
}


function onkey(event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13) {
        //alert(keyCode);
        document.getElementById("btn_Search").focus();
        document.getElementById("btn_Search").click();
        
    }



}

function searchmap() {
    //alert(showAddress(xGetElementById('address').value));
    //alert(xGetElementById('address').value);

    showAddress(xGetElementById('address').value); return false
}

function checkUserdetails() {

    GDownloadUrl('CheckUserdetails.aspx', function(data, responseCode) {
        if (responseCode == 200) {
            var xml = data;
            if (xml.length > 0) {
                var sWKT = xml.split(':')[0];
                var sName = xml.split(':')[1];
                if (sWKT == 'TRUE') {

                    

                        getUserChoices();
                       



                } else {

                    location = sName;


                }
            }
        }

    });

}

function getUserChoices() {

    var meta = document.getElementById('Meta');
    var ifr = document.createElement('iframe');
    ifr.setAttribute("id", "if1");
    ifr.setAttribute("scrolling", "no");
    ifr.setAttribute("frameborder", "no");
    ifr.style.border = "none";
    ifr.setAttribute("src", "DetailsMarks.aspx");
    ifr.style.width = "200px"
    ifr.style.height = "120px";
    ifr.style.position = "absolute";
    ifr.style.top = (screen.height/2 - 200) + "px";
    ifr.style.left = (screen.width/2 - 200) + "px";
  //  alert(ifr.style.top + " " + ifr.style.left);
    ifr.style.zIndex = 9000001;
    meta.appendChild(ifr);




}
var marksWindow;
function GetMarksChoices(cp,cmd) {
    GDownloadUrl('DetailsMarks.aspx?cmd=' + cmd, function(data, responseCode) {
        if (responseCode == 200) {
         marksWindow =    map.openInfoWindowHtml(cp, data);
        } else {

         //   location = sName;


        }



    });


}
var disableInfoTool = false;
function CreateNewFeature(sFeatureTypeID) {
    disableInfoTool = true;
    gsFeatureTypeID = sFeatureTypeID;

    // Show polytool and select by default
    // map.clearOverlays();
    checkUserLogRole();
    removeTempPoly();
    polyPoints = [];
    redraw();
    
    checkUserdetails();

       

    
   

  
        

    
}

function DrawSingleFeature(sFeatureID) {
    var theDate = new Date();
    GDownloadUrl('WKTSingleFeatureResponder.aspx?FeatureID=' + sFeatureID + '&TimeStamp=' + theDate.valueOf(),
    function(data, responseCode) {
        if(responseCode == 200) {
	        var xml = data;
	        if(xml.length > 0) {
		        var sWKT = xml.split(':')[0];
		        var sName = xml.split(':')[1];
		        var sFeatureTypeID = xml.split(':')[2];

		        sWKT = sWKT.replace("POLYGON((","");
		        sWKT = sWKT.replace("))","");
		        aWKT = sWKT.split(",");

		        var alatlngs = new Array;

		        for (var j = 0; j<aWKT.length; j++) {
		            aPt = aWKT[j].split(" ");
		            var gPt = new GLatLng(parseFloat(aPt[1]), parseFloat(aPt[0]));
		            alatlngs[j]=gPt;
		        }

              
            }
        }
        else if(responseCode == -1) {
            alert("Data request timed out. Please try later.");
        } 
        else {
            alert("Request resulted in error.\n Request returned :- \n" + data);
        }
    });
}

function searchPostcode(sPostcode, X, Y) {
    
	GDownloadUrl("http://" + webhost + "/ESDMSpatialServices/ESDMspatialServices.asmx/GetXYFromPostcode?sValue=" + sPostcode + "&sCurrentCoord=" + X + " " + Y + "&iMaxRows=10", function(data, responseCode) {
        if(responseCode == 200) {
		    var xml = GXml.parse(data);
		    var postcodes = xml.documentElement.getElementsByTagName("Location");
		    if (postcodes.length > 0) {
			    lng = GXml.value(postcodes[0].getElementsByTagName("X").item(0));
			    lat = GXml.value(postcodes[0].getElementsByTagName("Y").item(0));
			    place(lat,lng,16,sPostcode);
		    }
		    else {
			    showNonPostcodeAddress(sPostcode);
		    }
		}
        else if(responseCode == -1) {
            alert("Data request timed out. Please try later.");
        }
        else {
            alert("Request resulted in error.\n Request returned :- \n" + data);
        }
	});
}

function place(lat,lng,zoomlevel,label) {
    var point = new GLatLng(lat,lng);
    if (zoomlevel>8){
        map.setCenter(point,zoomlevel); 
    } else {
        map.setCenter(point,GeoAccuracy[zoomlevel]);
    }
    map.addOverlay(createMarker(point, label));
    document.getElementById("message").innerHTML = "";
}

// create a marker at the given point w/ the given label
function createMarker(point, label) {
    
    var marker = new GMarker(point);
    GEvent.addListener(marker, "click", function() {
       marker.openInfoWindowHtml(label);
    });
    return marker;
}

function showAddress() {
    var search = document.getElementById("address").value;

    if (search != '') {
 	    var pt = map.getCenter();
 	    searchPostcode(search,pt.lng(),pt.lat());
 	}
}
 
function showNonPostcodeAddress(search) {
    //search = search + " ,UK";
    // ====== Perform the Geocoding ======        
    geocoder.getLocations(search, function (result) {
        var pCentre = new GLatLng(mapStartCentreY,mapStartCentreX);
        var mapViewCentre = map.getCenter();
        if (result.Status.code == G_GEO_SUCCESS) {
            // ===== If there was more than one result, "ask did you mean" on them all =====
            if (result.Placemark.length > 1) { 
                // Loop through the results
                var j=0;
                for (var i=0; i<result.Placemark.length; i++) {
                    var p = result.Placemark[i].Point.coordinates;
                    var pt = new GLatLng(p[1],p[0]);
                    var dist = Math.floor(pt.distanceFrom(pCentre)/1000);
                    var dist2 = Math.floor(pt.distanceFrom(mapViewCentre)/1000);
                    if (dist<mapMaxDistanceKmForSearch) {
                        if (j==0) {
                            document.getElementById("message").innerHTML = "Did you mean:";
                        }
                        j=j+1;
                        document.getElementById("message").innerHTML += "<br>"+(j)+": <a href='javascript:place(" +p[1]+","+p[0]+","+ result.Placemark[i].AddressDetails.Accuracy +",\"" +search + "\")'>"+ result.Placemark[i].address+" ("+dist+" km)</a>";
                    }
                }
                if (j==0) {
                    document.getElementById("message").innerHTML = "No matching locations found";
                }
            }
            // ===== If there was a single marker =====
            else {
                document.getElementById("message").innerHTML = "";
                var p = result.Placemark[0].Point.coordinates;
                var pt = new GLatLng(p[1],p[0]);
                var dist = Math.floor(pt.distanceFrom(pCentre)/1000);
                if (dist<mapMaxDistanceKmForSearch) {
                    place(p[1],p[0],result.Placemark[0].AddressDetails.Accuracy,search);
                } else {
                    document.getElementById("message").innerHTML = "No matching locations found";
                }
            }
        }
        // ====== Decode the error status ======
        else {
            var reason="Code "+result.Status.code;
            if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code];
            } 
            alert('Could not find "'+search+ '" ' + reason);
        }
    });
}


function GetFeatureColour(sFeatureTypeID) {
    switch (sFeatureTypeID) {
        case '1': return "#FF0000"; break
        case '2': return "#00FF00"; break
        case '3': return "#0000FF"; break
        case '4': return "#FFFF00"; break
    }
    return "#FFFFFF";
}

function addInfoTipMarker(pt, sFeature) {
    var theDate = new Date();
    if (tempDiveMarkers.length > 0) {
        removetempDiveMarkers();

    }
    changePointColor(sFeature);
    GDownloadUrl('DetailsContainer.aspx?FeatureCode=' + sFeature + '&TimeStamp=' + theDate.valueOf(),

    function(data, responseCode) {
        if (responseCode == 200) {
            InfoWindow = map.openInfoWindowHtml(pt, data)
        }
        else if (responseCode == -1) {
            alert("Data request timed out.  Please try later.");
        }
        else {
             alert("Request resulted in error.\n Request returned :- \n" + data);
            
        }
    });
}

function layerCheckBoxClicked(checkBoxName) {
    // We do not allow the user to select layers from both Inshore/Offshore and Stable/Mobile
    /*	Edited by Tom. Content stripped as no longer relevant. Still calls LayersChanged in case function called somewhere else */

	var updateLayers = true;
        LayersChanged();
}



function GetWMSMarkerPolys() {

    document.getElementById("message").innerHTML = "";
    tempLayers = mapLayers;
   // mapLayers = "";
    mapLayers = mapLayers + ",Marks";
    //document.write(CustomGetGroundOverlay(overlayBounds, gutterPixelSize, '70', mapDataLayerURL, mapLayers));
    getWMS();
    getmarkerPolys();

   
}

function getWMS() {
	var loadImg = document.getElementById("loadingImgData");

	if (loadImg != null) {
	   loadImg.style.visibility = "visible";
	}

    // Get height and width of mapDiv
    var mapDiv = document.getElementById("map");
    if (mapDiv != null) {
	    pageMapWidth = mapDiv.clientWidth;
	    pageMapHeight = mapDiv.clientHeight;
    }

	if (gutterPixelSize>0) {
		overlayBounds = extendBounds(pageMapWidth, pageMapHeight, gutterPixelSize);
	}
	else {
		overlayBounds = map.getBounds();
	}

	wmsImg = new Image(pageMapWidth, pageMapHeight);
	if (mapLayers != '') {
	    // Set image location and add image after it has finished loading
	    wmsImg.src = CustomGetGroundOverlay(overlayBounds, gutterPixelSize, '70', mapDataLayerURL, mapLayers);
	    wmsImg.onload = function() {wmsDataLoaded();}
	}
	else {
	    // Remove any overlay image
	    wmsDataLoaded();
	}

    currentOverlayCenter = map.getCenter(); 
	currentOverlayZoom = map.getZoom();
}

function wmsDataLoaded() {
    if (dataOverlay != '') {
		map.removeOverlay(dataOverlay);
	}

	if (mapLayers != '') {
	    dataOverlay = new GGroundOverlay(wmsImg.src, overlayBounds);
        map.addOverlay(dataOverlay);
    }

    var loadImg = document.getElementById("loadingImgData"); 
    if (loadImg != null) {
		loadImg.style.visibility = "hidden";
	}
}

function extendBounds(pageMapWidth, pageMapHeight, gutterPixels) {
    //pixels is the number of extra pixels you want in gutter
    //remember mapserver can't return more than 2048x2048   
    //NOTE: base map even less - depends on km distance it needs to calculate on the server 
    //since we're only using client base map on close zoom, gutterPixels ~200 seems to work        
	if (((pageMapWidth + (2 * gutterPixels)) > 2048) || ((pageMapHeight + (2 * gutterPixels)) > 2048)) {
		alert('Your map is too big - please reduce the size');
	}            

	var x1 = map.getBounds().getSouthWest().lng();
	var x2 = map.getBounds().getNorthEast().lng();
	var y1 = map.getBounds().getSouthWest().lat();
	var y2 = map.getBounds().getNorthEast().lat();
	var newBnds;
	var newSW;
	var newNE;

    xdiff = Math.abs(x2-x1);
    ydiff = Math.abs(y2-y1);

    x1 = x1 - (xdiff * (gutterPixels/pageMapWidth));
    x2 = x2 + (xdiff * (gutterPixels/pageMapWidth));

    y1 = y1 - (ydiff * (gutterPixels/pageMapHeight));
    y2 = y2 + (ydiff * (gutterPixels/pageMapHeight));

    newSW = new GLatLng(y1,x1);
    newNE = new GLatLng(y2,x2);

    newBnds = new GLatLngBounds(newSW,newNE) ;

    return newBnds;
}

function load() {
    try {
        GeoAccuracy[0] = 3;
        GeoAccuracy[1] = 4;
        GeoAccuracy[2] = 8;
        GeoAccuracy[3] = 10;
        GeoAccuracy[4] = 12;
        GeoAccuracy[5] = 14;
        GeoAccuracy[6] = 14;
        GeoAccuracy[7] = 15;
        GeoAccuracy[8] = 16;

        // ====== Array for decoding the failure codes ======
        reasons[G_GEO_SUCCESS]            = "Success";
        reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
        reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
        reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
        reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
        reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
        reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

        geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode("uk");

        JdrawUserFeatures();

        // For IE6 we need to set the map size manually to a fixeed width
        var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
        if (IE6 == true) {
            xGetElementById('map').style.width = '446px';
            xGetElementById('map').style.height = '230px';
        }
        // Check the size of the map.  This is required for IE
        map.checkResize();
    }
    catch(e) {
        alert(e.message);
    }
    return true;
}

/*******************************************************************************
* Refresh the feature list
*******************************************************************************/
function UpdateFeaturesList() {
    // Turn off the polygon tool
   // polyCtrl.polygButtonClick.off();

    // Refresh the features table
    xGetElementById('RefreshUserFeatures').click();
}

/*******************************************************************************
* Clone feature and display metadta form
*******************************************************************************/
function CloneFeature(xCenter, yCenter, originalfeatureID) {
    // Save original feature position and use this to find the new one later
    checkUserLogRole()

    
        mxCenter = xCenter;
        myCenter = yCenter;
        UseCallback('Clone,' + originalfeatureID, 'Clone');

    
}




function DeleteFeature(featureID) {
    
    if (confirm('Are you sure you want to delete this feature?') == true) {
        checkUserLogRole();
       
            JDeleteFeaturePoly(featureID);
            UseCallback('Delete,' + featureID, 'Delete');

       
    
    
        
        
    }
}

function ServerCallback(featureID, context) {
    if (context == 'Clone') {
        SelectFeature(featureID);
    }
    else if (context == 'Delete') {
        JdrawUserFeatures();
    }
}

/*******************************************************************************
* Select feature on map
*******************************************************************************/
function SelectFeature(featureID) {
    checkUserLogRole()


  
        // Refresh features list
        UpdateFeaturesList();

        // Redraw user features
        JdrawUserFeatures();

        // Select map feature
        MapObjectSelect(mxCenter, myCenter, featureID);

   
}

function AddPolyTool() {
    load();
    //polyCtrl = new GPolygonControl();
   // map.addControl(polyCtrl);
   // ShowPolyTool(false);
}

function initialize() {
    try {
        if (GBrowserIsCompatible()) {
            map = new GMap2(xGetElementById("map"));

            map.setMapType(G_HYBRID_MAP);

            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            map.addControl(new GScaleControl());

            map.setCenter(new GLatLng(50.5, -4.0 ), 8);

            ovcontrol = new GOverviewMapControl();
            map.addControl(ovcontrol);

	        setTimeout("AddPolyTool();", 500);

            GEvent.addListener(map, "moveend", function () {
		        var newCenterPt = map.fromLatLngToDivPixel(map.getCenter());
		        var currentOverlayCenterPt = map.fromLatLngToDivPixel(currentOverlayCenter);
		        var diffX = currentOverlayCenterPt.x-newCenterPt.x;
		        var diffY = currentOverlayCenterPt.y-newCenterPt.y;

		        if ((Math.abs(diffX) >= gutterPixelSize) || (Math.abs(diffY) >= gutterPixelSize) || (currentMapZoom != currentOverlayZoom)) {
			        getWMS(); //client data
		        }
	        });

            GEvent.addListener(map, "zoomend", function (oldLevel, newLevel) {
	             currentMapZoom = newLevel;
	             getWMS();
	        });

	        //remember zoom level
	        currentMapZoom = map.getZoom();

	        //set overlay center & zooms
	        currentOverlayCenter = map.getCenter();
	        currentOverlayZoom = map.getZoom();
	        LoadMetaData();
        }
        else {
            alert("Sorry, the Google Maps API is not compatible with this browser");
        }
    }
    catch(e) {
        alert(e.message);
    }
    
}

function resizePanel() {
    var leftPanelDiv;
    var mapToolsDiv;
    var mapDiv;
    var ExpandMapImage;
    var ContractMapImage;
    var ExpandContractMapLabel;
    var leftPanel;
    var rightBGDiv;
    var tabsBottomDiv;

    leftPanelDiv = document.getElementById('leftPanel');
    mapToolsDiv = document.getElementById('mapTools');
    mapDiv = document.getElementById('map');
    ExpandMapImage = document.getElementById('ExpandMapImage');
    ContractMapImage = document.getElementById('ContractMapImage');
    ExpandContractMapLabel = document.getElementById('ExpandContractMapLabel');

    rightBGDiv = document.getElementById('rightBG');
    tabsBottomDiv = document.getElementById('tabsBottom');

    if (leftPanelDiv != null && mapToolsDiv != null)
    {
        if (leftPanelDiv.style.zIndex == "-1")
        {
            // Show left panel and contract map
            leftPanelDiv.style.zIndex= "1";
            leftPanelDiv.style.visibility = "visible";
            rightBGDiv.style.visibility = "visible";
            tabsBottomDiv.style.visibility = "visible";
            // Hide relevant expand/contract map image and alter text
            ExpandMapImage.style.zIndex = "1";
            ContractMapImage.style.zIndex = "0";
            ExpandContractMapLabel.textContent = "View larger map";
            ExpandContractMapLabel.innerText = "View larger map";
            mapToolsDiv.style.marginLeft = "360px";
            mapDiv.style.marginLeft = "360px";
            mapDiv.style.marginBottom = "40px";
        }
        else {
            // Hide tool panel and expand map
            leftPanelDiv.style.zIndex = "-1";
            leftPanelDiv.style.visibility = "hidden";
            rightBGDiv.style.visibility = "hidden";
            tabsBottomDiv.style.visibility = "hidden";
            // Hide relevant expand/contract map image and alter text
            ExpandMapImage.style.zIndex = "0";
            ContractMapImage.style.zIndex = "1";
            ExpandContractMapLabel.textContent = "View smaller map";
            ExpandContractMapLabel.innerText = "View smaller map";
            mapToolsDiv.style.marginLeft = "0px";
            mapDiv.style.marginLeft = "0px"; 
            mapDiv.style.marginBottom = "0px";
        }
    }

    // Notify the map that it has changed size
    map.checkResize();
}



/*******************************************************************************
* Layers have changed
*******************************************************************************/
function LayersChanged() {
	// Clear any messages as this is in the same place as the roller image
	document.getElementById("message").innerHTML = "";
	mapLayers = "";

	for (k in layerHash) {
		if (xGetElementById(k)) {
			if (xGetElementById(k).checked==true) {
				mapLayers = mapLayers + layerHash[k];
				mapLayers = mapLayers + ",";
			}
		}
	}

	// FS Boundary comes last (added manually) to ensure top layer position
	if (xGetElementById("Theme_FSBoundary").checked==true) {
		//mapLayers = mapLayers + "_FSBoundary,";
		mapLayers = mapLayers + "_FSBoundary,";
	}


	if (mapLayers.length!= 0) {
		mapLayers = mapLayers.substring(0, mapLayers.length-1);	//chop off the final comma
	}

	// Check if layer permissions need to be displayed
	getLayerPermissions(mapLayers);

	// Update map layers
	getWMS();
}

function clearAllLayers() {
	// Clear all layer checkboxes and refresh layers.
	// Now references the hash table defined at the start of this file.
	
	for (k in layerHash) {
		if (xGetElementById(k)) {
			xGetElementById(k).checked=false
		}
	}
	
	xGetElementById("Theme_FSBoundary").checked=false;  
	
	LayersChanged();
}