function globalVariables()
{
	// preload images
	 img = new Image();				img.src = 'images/tpLogo.gif';
	 loadImg = new Image();			loadImg.src='images/loader07.gif';
	 dots = new Image();				dots.src = 'images/marker10.png';
	 loader = new Image();			loader.src = 'images/loader.gif';

	 blueBanner = new Image();		blueBanner.src = 'images/banner_200.gif';
	 blueBanner2 = new Image();		blueBanner2.src = 'images/banner_235_new.gif';
	 blueBanner4 = new Image();		blueBanner4.src = 'images/banner_400.gif';
	 blueBanner6 = new Image();		blueBanner6.src = 'images/banner_600.gif';

	 sliderVert = new Image();		sliderVert = 'images/slider_image.jpg';
	 sliderHoriz = new Image();		sliderHoriz = 'images/slider_image_horiz.jpg';
     myslider = [];
	 chartImages = new Image();		
	 symbol = new Image();			symbol='images/target_small.gif'; 
	 terrSymbol = new Image();		terrSymbol='images/home.png'; 
	 
	 geomkeyFalg = false;   popupFlag = false;
	 zoom = true;  putStyles = false;
	 currentDrapeStyle = '';
	 progressBarVer = 'progBar';
	 boundary = '';  lastAddress = '';  lastAccuracy = -1;  boundarySld = '';
	 newSldTerritory = null;
	 infoTempHidden = false;
	 addRemove=false;
	 dataStore = 'ABS';
	 ozBoxGeog = null;
	 rangesDone = false;
	 cs=":";
	 nativeCoords = false;
	 defaultSrs = "EPSG:900913";
	 defaultIntensity = 10;
	 defaultRadius = 20;
	 defaultOpacity = 0.5;
	 

	 click = null;  polly = false;
	 allAtts = false;
	 allX = new Array();  allY = new Array(); pt = new Array();
	 allPoints = new Array();
	 xCoo = new Array(); yCoo = new Array();
	 attNames = new Array(); 
	 format = new Array(); 
	 tooltip = new Array();
	 targetNames = new Array();
	 targetFormat = new Array();
	 targetTooltip = new Array();
	 targetFilter = new Array();
	 targetSummit = new Array();
	 markerColor = new Array();
	 markerClass = new Array();
	 filteredColors = new Array();
	 searchTarget = new Array();

	currentFilterLevel = null;
	currentFilterlayer = null;
	currentFilterTheme = null;
	standardColorScheme = true;
	
	currentXmlRow = -1;
	currentTerrRow = -1;
	allTerritories = false;
	allSldTerritory = null;
	territorySolidBorder = true;
	currentTerritory='';
	newTerritoryAdded=false;
	noOfXml = 0;
	noOfTerr = 0;
	filePrefix = '';
	//editorFlag=false;
	serachButtId = 'searchDD';
	usermarkers = false;
	currentBasemap = null;
	inputNew = null;
	selectedColor = null;
	searchPolygonSet = false;
	currentPolyType = 0;

	classDescArray = new Array();
	classCodeArray =  new Array();
	colorBdyArray =  new Array();
	colorFillArray =  new Array();
	fillOpacArray =  new Array();
	lineWeightArray =  new Array();

	// controls and layers section
	markers = null;
	marker=null;
	innerBoundaries=null;
	innerSldTerritory=null;
	vectorLayer = null;  vectorLayer1 = null;  vectorLayer2 = null; vectorLayer3 = null;  vectorLayer4 = null;
	DemoDrape=null;
	heat=null;
	PolygonLayer = null;
	DrapeHighlight=null;
	SelectHighlight = null;
	userMarkers = null;
	currentDrapeLayer = null;
	reportHolderId = null;
	bodyId = null;
	xmlPublished = false;
	
	boundary = null; innerBoundaries = null;
	territory = null;
	councilsMask = null; 
	maskLayer = null; 
	polygonLayer = null;
	labelLayer = null;
	collectlayer = null;
	userdata=false;
	sldHighlightFile= null;
	
	// get the territory specific attributes
	territoryBounds = null;	
	terrMarkers = null;
	terrLabels=null;
	territoryLoc = null;
	terrPopup = null;
	territory = null;
	allTerritories = null;
	allTerritoriesLayer = null;

	territoryFileName = '';
	territoryDateEntered = '';
	territoryDataLayer = '';
	territoryAttName = '';
	territoryAttCode = '';
	territorySrs = '';
	territoryFilter = new Array();
	territoryNames = new Array();
	territoryBboxes = new Array();
	baseCoords = new Array();
	boundary=null;
	allTerritoriesLayer=null;
	allTerritoriesBounds = null;
	territoryActive = false;
	newTerritory=true;
	territoryDataLayerAll = '';


	territoryBbox = '';
	territoryCode = '';
	territoryName = '';
	territoryContact = '';
	territoryAddress = '';
	territoryLocation = '';
	territoryAbstract = '';
	territoryFillColor = 'FF0000';
	territoryFillOpacity = '0.3';
	territoryStrokeColor = 'FF0000';
	territoryStrokeWidth = '5';
	territoryPolygonName = '';
	polypikaTempHidden = false;
	printLegend=true;
	
	//-- controls 
	terrSelectControl = null;
	circClick=null;
	rectClick=null;
	drawControls=null;
	noticeControl=null;
	printMap = null;
	map = null;
	control=null;  dragControl=null;  polyDragControls = null;
	polyControl = null;  drawpolyDragControl = null;


	 firstTime=true;
	 pickMode = false;
	 sldOffset = null;
	 drapeId = '';  drapeCache = '';  currentDrapeId = '';
	 vectorFilter='byClass';
		
	// set up all the global iables/arrays
	 controlFile = drapes;
	 spMerc = ''; 
	 xStart = ''; 
	 yStart = ''; 
	 ozBox =[];
	 gfiParams = '';
	 activeLayerName= '';

	 drapeAtts = null;
	 currentFile = null;
	 report = true;
	 list = false;
	 width = 1000;
	 height = 1000;
	 radius = 1000;
	 oldHeight = 1000;
	 oldWidth = 1000;
	 oldRadius = 1000;
	 oldId = '';
	 searchType = 'Intersects';
	 dragable = false;
	 layersLoading = 0;
	 ll=0.0;  ur=0.0;

	 overrideAttribute = '';
	 uniqueKeyAttribute = null;
	 
	 eventsLog = null;
	 ajaxRequest=null;  gfiXmlFile='';
	 Request = null;
	 error='';
	 newAttribute = null;
	 oldAttribute = null;
	 DrapeHighlight = null;
	 oldTempCache = '';
	 newCsvFile = '';
	 newAllCsvFile = '';
	 currentCollection = null;
	 polypikaMode = false;
	 currentElectorate = '';

	 stamp = null;
	 collect=null;
	 serviceBase = meshBlocksBase;
	 fln = '';
	 attName = '';  labelName = ''; 
	 laylineSld = null;
	 layWmslayer = null;
	 drapeWmslayer = null;
	 infoForm = null;
	 win=null;
	 rad = 0; 
	 count = 1; 
	 IE=false;
	 zml=20;
	 opacityValue=1.0;
	 opacityValue2 = 1.0;
	 symbols = '';
	 labelsRequired;

	// initialise the legend css iables
	 legendBackground = "legendBackground";
	 legHolder = "legHolder";
	 legend = 'legend';
	 legendTitle = "legendTitle";
	 legendTable = "legendTable";
	 legendBox = "legendBox";
	 legendText = "legendText";
	 tableBody = "tBody";
	 tdCell = "tdCell";
	 message = "messHolder";
	 newOpacity = '';
	 dvbdy1="dvbdy1";  dvhdr1="dvhdr1";
	// messHolder = null;

	// initialise the drape iables
	 wmslayer = null;
	 theme = null;
	 themeTitle = null;
	 themeDir = null;	
		themeLayer = null;
		layName = null;
		layFile = null;
		layStyle = null;
		layType = null;
		layTitle = null;
	 layOp = null;
	 laySldLoc = null;
	 layId = null;
	 newSldOpen = true;

	 defs= new Array(); 
	 content=new Array();

	 thisCenter = null;  thisZoom = null;

	 tempFiles = [];
	 temp =[];
	 mess='mess';
	 newSldOpe=false;

	 sldTitleData = ''
	 path = '';

	 selectedMenu = 3;  upFileName ='';
	 
	 roadsLoaded=false;
	 loggedIn =  false;
	 attributeInfo = [];  gfilename = '';
	 reasons=[];    map = null;  sldOpac = null;  wmscdev = null; 
	 lgaSld=null;  lgaMask=null;  mouseLoc = null;
	 htmls=[];  legendHide=null;  legendLoad=null;  activeLegend="legend";
	 currentSldFile=null;  currentDrape=null; Highlight=null; 
	 
	

	 infoForm = null;  currentDrapeFile=null;
	 lineSld=null;

	// LanduseHighlight;  CensusHighlight;	 NZmeshblocksHighlight;  nnttHighlight;
	 layer_style=null;  style_island=null; 
	 CouncilsMask=null;  allLayers=null; 
	 newSldFile=null;  maskSld = '';  currentSld=null;  lgaFile='';  newColl='';

	 CouncilsBdy=null;
	 electoralBdy=null;
	 stateElectoralBdy=null;
	 Postcodes=null
	 Suburbs=null;
	 ILOCdrape=null;  ILOCHighlight=null;
	 IAREdrape=null;  IAREHighlight=null;
	 IREGdrape=null;  IREGHighlight=null;
	 IndigenousLoc=null;
	 IndigenousAreas=null;
	 IndigenousRegions=null;
	 Roads=null;
	 Cadastre=null;
	 Bathymetry=null;
	 Imagery=null;
	 maskColor = '#000000';


	 PolyTag = "gml:Polygon";
	 ExteriorTag = "gml:exterior";
	 InteriorTag = "gml:interior";
	 LinearRingTag = "gml:LinearRing";
	 PosListTag = "gml:posList";

	// queryLayers='MESHBLOCKS:ABS';
	 sldUrl = '';
	 newFileName=''; 
	 newStyleName='';
	 oldFileName='';
	 getFile = '';

	 cadUrl=null;	 ABS2006=null;  akaBase=null;  tpLga=null;
	 BBox='';
	 loRange= [];  midRange=[];  hiRange=[];
	 nn=null;
	 legendLoad=null; 
	 bounds = null;

	 loLat='';  hiLat='';  loLng='';  hiLng=''; 
	 centLat = 0.0;  centLon = 0.0; 
	 sumLat = 0.0;
	 sumLng = 0.0;
	 leg=null;
			
	 userOverlayFile=null;
	 fileUploaded = false;  xmlFileActive = false;
	 uploadFilename=null;
	 Tree = new Array;
	 totalTreeLength=0;
	 popup = null; 
	 currentPopup=null;
	 collectLayer=null;

	 maxOpacity = 1;
	 minOpacity = 0;
	 myslider = [];
	 terrslider = [];
	 fadeLayer=''; 	
	 lastKnownPosition = 1.0;
	 lastKnownPosition2 = 1.0;

	 newCollSld=null;
	 collection=null;
	 filter='';
	 newSld = '';

	 vectors = null;   selectStyle=null;  
	 //onFeatureSelect=null;  onFeatureUnselect=null;  
	 styleMap=null; template=null;
	 
	 dragControl=null;
	 drawControls = null;  
	 dragBoxControl=null;
	 selectControl = null;  
	 click = null;
	 selectedFeature = null;   
	 control = null;  
	 dragItControl = null;

	 pointFeature = new Array();
	 recNo = new Array();
	 oldLocation = new Array();
	 sortedPoints = new Array();
	 range = new Array();
	 sortedRange = new Array();
	 sortedRecNo = new Array();
	 sortedOldLoc = new Array();
	 current = 0;
	 feature = null;

	 // geocode section
	 geocoder=null;
	 rg = null;
	 geocodedFile = null;
	 geocodedCsv = null;
	 geocodeLayerName = 'Address';
	 csvHeadRows = '';  csvAddrCols='';  csvLatlonCols='';  csvSymbolCol='';  csvChartCol='';
	 address='';
	 newAdd = '';  newDesc = '';
	 newAcc = 0;
	 acc='';
	 empty = '';

/*	 G_GEO_SUCCESS = null;
	 G_GEO_MISSING_ADDRESS=null;
	 G_GEO_UNKNOWN_ADDRESS=null;
	 G_GEO_UNAVAILABLE_ADDRESS=null;
	 G_GEO_BAD_KEY=null;
	 G_GEO_TOO_MANY_QUERIES=null;
	 G_GEO_SERVER_ERROR=null; 
*/
	// error messages for Google Maps geocoder
	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.";
	 
	  accuracyDesc = 
	[
		'Unknown location', 
		'Country level', 
		'State level', 
		'Local Govt level', 
		'Town/City level', 
		'Post code level', 
		'Street level', 
		'Intersection level', 
		'Address level', 
		'Premise level'
	]
	// list of basemaps to be loaded
	 googleMap=null;  googleDem=null;  googleHyb=null;  googleSat=null;  aero = null;  bingShaded=null;  osmap=null;  numaps=null; gtopo30=null; nearmap = null;  TerraPagesCache=null; 
	 psmaBasemap2 = null;
	 ym=null;  mm=null;  ve=null;  veAerial=null; mapnik = null;  kamap=null;  yahoo=null;
	 googleMap2 = null;

	// baseMapsList = ['GoogleMaps', 'GoogleHills', 'GoogleHybrid', 'GoogleSat', 'NuMaps', 'NearMap']; 
	// baseMapsIds = ['gm','gd','gh','gs','nm','near'];
	// baseMapsLayers = ['googleMap','googleDem','googleHyb','googleSat','numaps','nearmap'];
	
	//baseMapsList = ['GoogleMaps', 'GoogleHills', 'GoogleHybrid', 'GoogleSat', 'OpenStreetMap', 'NearMap']; 
	//baseMapsIds = ['gm','gd','gh','gs','osm','near'];
	//baseMapsLayers = ['googleMap','googleDem','googleHyb','googleSat','osmap','nearmap'];

	//baseMapsList = ['GoogleMaps', 'GoogleHills', 'GoogleHybrid', 'GoogleSat', 'OpenStreetMap', 'GTOPO30']; 
	//baseMapsIds = ['gm','gd','gh','gs','osm','gtopo30'];

	baseMapsList = ['GoogleMaps', 'NearMap', 'GoogleSat', 'GoogleHybrid', 'GoogleHills', 'OpenStreetMap']; 
	baseMapsIds = ['gm','near', 'gs',  'gh', 'gd', 'osm'];
	//baseMapsLayers = ['googleMap','googleDem','googleHyb','nearmap','osmap','gtopo30'];

	// baseMapsList = ['GoogleMaps', 'GoogleHills', 'GoogleHybrid', 'NuMaps']; 
	// baseMapsIds = ['gm','gd','gh','nm'];
	// baseMapsLayers = ['googleMap','googleDem','googleHyb','numaps'];

	// should get this info from the mySql database!
	//polygonList = ['NONE','Cadastre','Meshblocks','Collection Districts','Suburbs','Postcodes','Local Governments', 'State Election', 'Commonwealth Election', 'Remoteness Areas', 'GP Divisions', 'OATSIH Planning'];

	 polygonList = ['NONE','Cadastre','Meshblocks','Collection Districts','Suburbs','Postcodes','Local Governments', 'State Election', 'Commonwealth Election'];

	 xmlTitlesList = new Array();
	 xmlAbstractList = new Array();
	 xmlValuesList = new Array();

	optionValues = [" ", "=", "!=", "&gt;", "&gt;=", "&lt;", "&lt;="];
	optionAlias = ["", "=", "!=", ">", ">=", "<", "<="];
	optionDesc = ["select", 'EQ  =', 'NE  !=', 'GT  >', 'GE  >=', 'LT  <', 'LE  <='];
	optionTitle = ["select from the list below","Equal To","Not Equal To","Greater Than","Greater Than Or Equal To","Less Than","Less Than Or Equal To"];

	optionValues2 = ["(", ")", "+", "-", "*", "/"];
	optionDesc2 = ['LB  (', 'RB  )', 'ADD  +', 'SUB  -', 'MULT  *', 'DIV  /'];
	optionTitle2 = ["Left Bracket","Right Bracket","Add","Subtract","Multiply","Divide"];
	
	optionValues3 = ["None", "AND", "OR"];
	optionAlias3 = ["None", "AND", "OR"];
	optionTitle3 =	["no following rule segment", "Logical AND", "Logical OR"];

	lineWeights = [0,1,2,3,4,5,6,7,8,9];
	opacityOps = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0];

	colorArray = ['A6CEE3','1F77B4','B2DF8A','33A02C','FB9A99','E31A1C','FDBF6F','FF7F00','CAB2D6','E31A1C','377DB8','4DAF4A','984EA3','FF7F00','FFFF33','A65628','F781BF'];

// Deep Analysis Tool
// The probably should be defined in an external database?
	configRequest= '';
	configParams = '';
	newFile=null;
	saveTotalName = '';
	parentFlag = false;
	analysisData = null;
	filterData = null;
	currentPath = 'cw';
	numaMin = 0;
	numaMax=1000;
	steps=10;
	
	// standard colour schemes
	colorRange = new Array();
	colorRange[0] = 'FFF5F0,FEE0D2,FCBBA1,FC9272,FB6A4A,EF3B2C,CB181D,A50F15,67000D'; // red scheme
	colorRange[1] = 'F7FBFF,DEEBF7,C6DBEF,C6DBEF,6BAED6,4292C6,2171B5,08519C,08306B'; // blue scheme
	colorRange[2] = 'F7FCFD,E5F5F9,CCECE6,99D8C9,66C2A4,41AE76,238B45,006D2C,00441B'; // green scheme


}

// function to load all attributes into arrays from a describeFeatureType request
function loadAttributesForLayer(layerName, ptr)	
{
	// load all attributes from laers that have been totals_crossreferenced
	ajaxRequest = getAttributeSchema(meshBlocksBase, layerName);
	//alert(ajaxRequest.status)
	if (ajaxRequest.status == 200)
	{
		buildAttributeArrays(ajaxRequest);
		// load all the attributes for this layer
		k=0; bboxReached=false;
		for(var i=0; i<attNames.length ;i++)
		{
			if(bboxReached)
			{	listOfThemes [ptr] [k] = attNames[i];	k++;	}
			else
			{	if(attNames[i] == 'BBOX'){bboxReached=true;}	}		
		}
	}
}
/*
function forceBasemap(base, xStart, yStart, startZoom)
{
	
	alert('force : xstart = '+xStart+"  ystart = "+yStart+" startZoom = "+startZoom);
	// set to the selected basemap
	currentBasemap = null;
	swapBase(base);
}
*/
//--------------- OpenLayers Map Initialisation ------------------------	
function openLayersLoad()
{
	genLoadStatus('Loading Application ....',true, '');
	// avoid pink tiles
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
	OpenLayers.Util.onImageLoadError = function() { this.style.display = "none"; }
	eventsLog = OpenLayers.Util.getElement("eventsLogID");
	layersLoading = 0;
	//OpenLayers.ImgPath = "http://js.mapbox.com/theme/dark/";
	
	//--------------- OpenLayers Map setup ------------------------	
	if (srs == defaultSrs)	//------------- sphericalMercator option
	{
		spMerc = true; 
		res = 156543.0339280410;
		xStart = 14881372.0; 
		yStart= -3003669.0;

		//xStart = 16788580.0 
	    //yStart= -4093480.0;

		units = "m";
		ozBox = [-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892]
		//ozBox = [10090000,  -6477000,  19940000,  -792500]; // all of Australia & NZ
		bounds = new OpenLayers.Bounds(ozBox[0],  ozBox[1],  ozBox[2],  ozBox[3])
		//ozBox = [-20037508,  -20037508,  20037508,  20037508.34]; // all of Australia
		//ozBox = [16743378, -4043518, 16882952, -3973578]; // just Sydney
		//ozBox = [14181820, -3350999, 17356708, -1169180]; // NT and Qld
		var options = 
		{
			projection: srs,  
			units: units,  
			controls:[],  
			maxResolution: res,  
			displayProjection: new OpenLayers.Projection("EPSG:4326"), 
			//numZoomLevels: 22,  
			maxExtent: bounds
		};
		map = new OpenLayers.Map('map', options);
		var startCoord = new OpenLayers.LonLat(xStart,  yStart);
		var startZm = startZoom;
	}
	else if(srs == "EPSG:4326" )						//------------ standard geographicals option
	{
		// var xStart = 134.824; var yStart= -26.037; // centre of Oz
		spMerc=false; 
		res = 0.703125;
		xStart = 138.54; 
		yStart= -34.9;
		uinits = 'degrees';
		ozBox = [104.0,  -70.0,  180.0,  0.0] // Australia and NZ
		bounds = new OpenLayers.Bounds(ozBox[0],  ozBox[1],  ozBox[2],  ozBox[3])
		var options = 
		{
			projection:srs,  
			controls:[],  
			units:units,  
			maxResolution: res,  
			//numZoomLevels: 22,
			maxExtent: new OpenLayers.Bounds(ozBox[0],  ozBox[1],  ozBox[2],  ozBox[3])
		};
		map = new OpenLayers.Map('map', options);
		var startCoord = new OpenLayers.LonLat(xStart,  yStart);
		var startZm = 10;
		
	}
	else
	{	alert(srs+' coordinate system not supported [epsg:900913 & epsg:4326 supported]'); return;}
	
	// Pre load all basemaps
	loadAllBasemaps();
	
	// set to the selected basemap
	currentBasemap = null;
	//alert('swapbase : xstart = '+xStart+"  ystart = "+yStart+" startZoom = "+startZoom);
	//swapBase(startBasemap);
	//alert('setting opacity of basemap');
	//googleMap.setOpacity(0.1);
	//for (var i=10;i<0 ; i--){googleMap.setOpacity(parseFloat(i/10)); pause(100)}
	//alert('making basemap invisible');
	//for (var i=1;i<10 ; i++){googleMap.setOpacity(parseFloat(i/10)); pause(100)}
	//googleMap.setVisibility(false);

	//alert('resetting basemap');
	//googleMap.setVisibility(true);
	//googleMap.setOpacity(1.0)
	
	// Navigation controls
	map.addControl(new OpenLayers.Control.Navigation());
	map.addControl(new OpenLayers.Control.PanZoomBar({div:$('zoomControl')}));
	map.addControl(new OpenLayers.Control.LayerSwitcher());
	//map.addControl(new OpenLayers.Control.NavToolbar({div:$('mouseControl')}));
	map.addControl(new OpenLayers.Control.MousePosition({div:$('mousePos')}));
	map.addControl(new OpenLayers.Control.Scale("scale"));
	map.addControl(new OpenLayers.Control.Attribution({div:$('openStreetMapPos')}));
	var historyPanel = new OpenLayers.Control.Panel({ div: document.getElementById("panel")});
	map.addControl(historyPanel);
	var history = new OpenLayers.Control.NavigationHistory();
	map.addControl(history);
	historyPanel.addControls([history.next,  history.previous]);

	// ---------- make sure that this app only ever places framed clouds at top right ---------
	map.Z_INDEX_BASE['Popup'] = 10000;
	OpenLayers.Popup.FramedCloud.prototype.fixedRelativePosition = true; 
	OpenLayers.Popup.FramedCloud.prototype.relativePosition = "tr"; 

	// add the temp vector layer - why?
	PolygonLayer = new OpenLayers.Layer.Vector("Temp Polygon Layer");
    map.addLayer(PolygonLayer);
	PolygonLayer.setZIndex(map.Z_INDEX_BASE['Popup'] - 1000);
	//alert(polygonLayer.getZIndex());

	// ---------------- Google Maps geocoder --------------------      
	geocoder = new GClientGeocoder();
	//rg = new GReverseGeocoder();
	//rg.setBaseCountry(country);
	
	// if requested in URL go to the address or location
	// NB address is seleceted if both are requested
	if(userAddress != '')
	{	document.getElementById('search').value = userAddress; 
		geocodeAddress(country, 'geocoder', 'search', 'selector', 'selForm', 'selBox', 'messHolder', srs, '');	
	}
	else if(start != '')
	{	geocodeAddress(country, 'geocoder', 'search', 'selector', 'selForm', 'selBox', 'messHolder', srs, start);		}
	else {map.setCenter(startCoord,  startZoom);}
	
	//  -------------- Styling for vector data ----------------
	// we want opaque external graphics and non-opaque internal graphics
	layer_style = OpenLayers.Util.extend({},  OpenLayers.Feature.Vector.style['default']);
	layer_style.fillOpacity = 0.1;
	layer_style.strokeOpacity = 1;
	layer_style.strokeWidth = 2;
	layer_style.strokeColor = "#FF0000";
	layer_style.hoverStrokeColor = "#00FF00";
	//layer_style.fillColor = "#FF0000";
		
	select_box = OpenLayers.Util.extend({},  layer_style); 
   // select_box.fillColor = "#FFFFFF";
	select_box.fillOpacity = 0.1;
	select_box.strokeWidth = 4.0;
	select_box.strokeOpacity = 1;
	select_box.strokeColor = "#0000FF";
	//select_box.hoverStrokeColor = "#FF0000";
	//select_box.hoverFillColor = "#FF0000";
	//select_box.strokeColor = "#0000FF";

	bounding_box = OpenLayers.Util.extend({},  layer_style); 
   // select_box.fillColor = "#FFFFFF";
	bounding_box.fillOpacity = 0;
	bounding_box.strokeWidth = 2.0;
	bounding_box.strokeOpacity = 0.5;
	bounding_box.strokeColor = "#FF0000";

	circles = OpenLayers.Util.extend({}, layer_style);
	circles.fillOpacity = 0;
	circles.strokeWidth = 2.0;
	circles.strokeOpacity = 1;
	circles.strokeColor = "black";

	// ---------------- Set up the doubleclick and click getfeatureinfo handler -------------------
	//dblClickGetFeatureInfo();
/*	clickGetFeatureInfo();
	click = new OpenLayers.Control.Click();          
	map.addControl(click);
    click.activate();
*/
	// ---------------- Set up the zoom events ------------------
	//alert('tile Size = '+map.getTileSize());
	//alert('res = '+map.getResolution());
	// now convert pixels to lat longs
	//		var pixel = new OpenLayers.Pixel(256, 256);
	//		var lonlat = map.getLonLatFromPixel(pixel); 
	//		alert(lonlat)

	map.events.register('zoomend', null, function(evt) 
	{		
		controlLayerVisibility();
		//activateControls('zoomEvent');
		Event.stop(evt);
    });
	
	zoomEvent();
	moveEvent();

	//---------------- Initialise function dependent stuff ---------------------
	
	// get DDrape data for search engine
	if(ddrapesFlag) 
	{	
		// create the DrapeTree
		buildTheDrapePickaTree();
		prepareSearch();
	}

	if(upLoadFlag) 
	{
		//makeSelectFilesControl('useroverlays/preGeocoded/', 'xmlEnter', 'Addresses', 'name','upload');
		// -- force the first group of LGAs into Select Box -->
		loadLgas("lgaSelBox:3", "AB:3",  "A to B");
	}

	if(territoryFlag)
	{
		prepareTerritorySearch();
		
		// set up the default territory layer for displaying territories
		terrPathSld = "gov/default_territory.xml";
		allTerrPathSld = "gov/nolines_territory.xml";
		territorySld = applicationBase+"inc/sld/"+terrPathSld;
		allTerritoriesSld = applicationBase+"inc/sld/"+allTerrPathSld;
		territoryMarkers = false;
		
		// initialise the territory layers
		createTerritoryLayer();
		createAllTerritoriesLayer();

		// temp - launch territory amanger
		showHideAllTerritories("showAllTerr"); toggleControl('expand:6')
	}
	
	genLoadStatus('', false, '');
	loaded=true;
	firstTime=true;
	
	// set focus on Go To entry box
	if(document.getElementById('search')) {document.getElementById('search').focus();}

	// launch instructions if requested - default is off
	if(openWithInstructions){toggleControl('expand:5');}

	resetZlevels();

	// set up the point symbol styling of uploaded pouints
	setupSymbols() ;

}

//------------------------- layer loading events -------------------
function registerEvents(layer) 
{	
	if(layer.name != '' && layer.name != null)
	{
		layer.events.register("loadstart",  layer,  function() 
		{
			if (layersLoading == 0) 
			{	eventsLog.style.display='block';   }
			layersLoading++;
		});
		layer.events.register("loadend",  layer,  function() 
		{
			layersLoading--;
			if (layersLoading == 0) 
			{	 eventsLog.style.display='none';   }
		});
	}
}

function registerLoadWheel(layer,  wheelId)
{
	//alert('layer name in registerLoadWheel = '+layer.name)
	if(layer.name != '' && layer.name != null)
	{
		layer.events.register("loadstart",  layer,  function() 
		{
			if(document.getElementById(wheelId)){document.getElementById(wheelId).style.display='block';  }
			eventsLog.style.display='block'; 
		});
		layer.events.register("loadend",  layer,  function() 
		{
			if(document.getElementById(wheelId)){document.getElementById(wheelId).style.display='none';  }
			eventsLog.style.display='none';  
		});
	}
}




 //--------------- Function to swap divs given a user selected div ------------------------//
function swapDiv(id)
{
	var divNumber = id.split("d");
	for (var i=0; i<4; i++)
	{	
		if (i == divNumber[1])
		{	
			document.getElementById('Div'+id).style.display='block';
			document.getElementById(id).style.backgroundColor='#EAF5ED';
			document.getElementById(id).style.color='black';
			if (id == 'd2' && firstTime) {openLayersLoad(); firstTime=false;}
		}
		else
		{
			document.getElementById('Divd'+i).style.display='none'; 
			document.getElementById('d'+i).style.backgroundColor='transparent';
			document.getElementById('d'+i).style.color='gray';
		}
	}
}

function cleanup()
{
	// delete all working files	
	if(newFileName != '' || newFileName != 'undefined' || newFileName != null)
	{	deleteit(newFileName);	}

	// remove any existing temp DDrape file 
	if(getFile)	
	{	
		var parts = getFile.split('newSld_');
		if(parts.length >1)
		{
			deleteit(getFile);
		}
	}
	
	if(newCsvFile != '' || newCsvFile != 'undefined' || newCsvFile != null)
	{	deleteit(newCsvFile);	}
	if(newAllCsvFile != '' || newAllCsvFile != 'undefined' || newAllCsvFile != null)
	{	deleteit(newAllCsvFile);	}
	
	if(newSldFile != '' || newSldFile != 'undefined' || newSldFile != null)
	{	deleteit('data/'+newSldFile);	}

	if(sldHighlightFile)
	{	deleteit('sld/'+sldHighlightFile); sldHighlightFile=null;}
	
	if(gfiXmlFile != '' || gfiXmlFile != 'undefined' || gfiXmlFile != null)
	{	deleteit(gfiXmlFile); 	}
	
	if(boundarySld != '' || boundarySld != 'undefined' || boundarySld != null)
	{	var parts = boundarySld.split('inc/')
		deleteit(parts[1]);
	}
	// delete any previous sld file and any similar cache 
	if ( newSldTerritory )	
	{	
		deleteit(newSldTerritory);		
		var cacheDir = newSldTerritory.split('sld/')[1];
		purgeDrapeCache(cacheDir, '');
	}
	
	if(allSldTerritory)
	{	
		deleteit(allSldTerritory);	
		var cacheDir = allSldTerritory.split('sld/')[1];
		purgeDrapeCache(cacheDir, '');
	}
	//if(lgaFile != '')
	//{	deleteit('data/'+lgaFile);	}
	if(userMarkers != null)
	{	killAllMarkers(); 
		//alert('about to delete uploaded files in numapsUtils');
		deleteAllUploadedFiles("lrad1")
	}
	if (maskSld){deleteit(maskSld);}

}

function drapeBuilderLaunch()
{	
	// this is the DrapeBuilder control funstion 
	// it operates on the status of the title of controlling button in the application
	// if set to 'SHOW DrapeBuilder' - initialise/activate it
	// if set to 'HIDE DrapeBuilder' - deactivate it
	
	if(document.getElementById('editDDIn').title == 'SHOW StyleBuilder')
	{
		// DrapeBuilder activated so set the control buttons
		depressedDiv('editDDIn');
		document.getElementById('editDDIn').title ='HIDE StyleBuilder';
		
		// check to see if DrapeBuilder is already been initialised
		if(!newSldOpen)
		{
			// This initialises the DrapeBuilder panel 
			// need to pass the holding Div ID and the sld URL
			sldBuilder("mapSurround",  legendSld);
			newSldOpen=true;
		}
		else
		{
			// already built so just show it
			document.getElementById('drapeBuilder').style.display='block';
		}
	}
	else
	{
		// DrapeBuilder is being closed so set buttons and hide it
		normalDiv('editDDIn');
		document.getElementById('editDDIn').title ='SHOW StyleBuilder';
		if(document.getElementById('drapeBuilder') != null)
		{	document.getElementById('drapeBuilder').style.display='none';}
	}
}



//----------- main function to control polygon Aggregation -----------------//
function getFeatureOptionsReport()
{
	//alert('allX = '+allX.length)
	//alert('allY = '+allY.length);
	
	// check to see if the Info mode button is depressed
	var selectObject = document.getElementById('includeType');
	searchType = selectObject.options[selectObject.selectedIndex].value;
	
	//alert('search type = '+searchType)

	
	pickMode=true; 
	polypikaMode=false;
	zoomToSelectBox = true;
	nativeCoords = false;

	// deactivate the upload points controls
	if(userMarkers)
	{
		var conts=['Drag'];
		deactivateControls(conts, 'numapsUtils:getFeatureOptionsReport');
		toggleDragging('dragMarker');
	}

	drapeAtts = Datts;
/*	if(vectorLayer)	{vectorLayer.destroyFeatures(); vectorLayer = null;}
	if(DrapeHighlight) {DrapeHighlight.setVisibility(false); DrapeHighlight=null;}
	if(SelectHighlight){SelectHighlight.setVisibility(false); SelectHighlight = null;}
*/
	// filter the Datts array by SLD file 
	var k=0;
	for (var i=0; i<Datts.length  ; i++)
	{
		var components = Datts[i].split('|');
		if (applicationBase+'inc/sld/'+components[6] == currentSldFile)
		{
			drapeAtts[k]=Datts[i];
			k++;
		}
	}

	// now execute the appropriate selected method for selecting data
	//alert('currentSldFile = '+currentSldFile)
	currentFile=currentSldFile;
	report = true;
	if(polypikaMode){report = false;}
	list = false;
	radius = '';
	width = '';
	height = '';
	dragable = false;
	document.getElementById("gfiDD").title="Re-enter Polypika Mode"; 
	document.getElementById('reptContHolder').style.display='none';		
//alert('g')
	// set up different switches as required
	if(document.getElementById('sp').checked)
	{
		// single point select - default
		width = 1;
		height = 1;
		// make sure the dropdown search type is deactivated and set to Contains		
		getfeatureByPolygon(drapeAtts,  currentSldFile, report,  list, width, height, radius,  searchType, false, false, dragable);
	}
	else if(document.getElementById('sd').checked)
	{
		// shift-drag feature for standard shapes
		dragable=true;
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, false, dragable);

	}
	else if(document.getElementById('pt').checked )
	{
		// rectangle box with dimensions
		width  = document.getElementById('rectWidth').value;
		height = document.getElementById('rectHeight').value;
		dragable=true;
		//alert(width+"  X  "+height)
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, false, dragable);
	}
	else if(document.getElementById('ci').checked )
	{
		// circle
		radius = document.getElementById('circleRad').value;
		dragable=true;
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, false, dragable);
	}
	else if(document.getElementById('fp').checked )
	{
		 // freehand
		dragable=true;
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, true, false, dragable);
	}
	else if(document.getElementById('db').checked )
	{
		// database polygon feature
		if(document.getElementById('geomkey').checked)
		{	searchType=document.getElementById('geomkey').value;	}
		else 
		{	searchType=document.getElementById('keygeom').value;}
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, true, dragable); 
	}
}

function featureSelect()
{
	if(document.getElementById("sendButt2"))	{document.getElementById("sendButt2").disabled='disabled'; }
	if(document.getElementById("lgaList:2"))	{document.getElementById("lgaList:2").disabled=false;}
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").disabled='disabled'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").disabled='disabled'; }
	if(document.getElementById("includeType"))	{document.getElementById("includeType").disabled=false; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").disabled=false; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").disabled=false; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").checked='checked'; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").checked=false; }
	if(document.getElementById('sendButt'))		{document.getElementById('sendButt').title='Local Government Area select mode'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").disabled='disabled'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").disabled='disabled'; }

}

function freehandPolygonSelect()
{
	if(document.getElementById("sendButt2"))	{document.getElementById("sendButt2").disabled=false; }
	if(document.getElementById("lgaList:2"))	{document.getElementById("lgaList:2").disabled='disabled';}
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").disabled='disabled'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").disabled='disabled'; }
	if(document.getElementById("includeType"))	{document.getElementById("includeType").disabled=false; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").disabled='disabled'; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").disabled='disabled'; }
	if(document.getElementById('sendButt'))		{document.getElementById('sendButt').title='Enter freehand polygon select mode'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").disabled='disabled'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").disabled='disabled'; }

}

function pointSelect()
{
	if(document.getElementById("sendButt2"))	{document.getElementById("sendButt2").disabled=false; }
	if(document.getElementById("lgaList:2"))	{document.getElementById("lgaList:2").disabled='disabled';}
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").disabled='disabled'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").disabled='disabled'; }
	if(document.getElementById("includeType"))	{document.getElementById("includeType").disabled='disabled'; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").disabled='disabled'; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").disabled='disabled'; }
	if(document.getElementById('sendButt'))		{document.getElementById('sendButt').title='Enter single point select mode'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").disabled='disabled'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").disabled='disabled'; }

}

function shiftDragSelect()
{
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").disabled=false; }
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").focus(); }
	
	if(document.getElementById("sendButt2"))	{document.getElementById("sendButt2").disabled=false; }
	if(document.getElementById("lgaList:2"))	{document.getElementById("lgaList:2").disabled='disabled';}
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").disabled='disabled'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").disabled='disabled'; }
	if(document.getElementById("includeType"))	{document.getElementById("includeType").disabled=false; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").disabled='disabled'; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").disabled='disabled'; }
	if(document.getElementById('sendButt'))		{document.getElementById('sendButt').title='Enter shift-mouse-drag select mode'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").disabled='disabled'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").style.backgroundColor='#c3c3c3'; }

}

function standardShapesSelect()
{
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").disabled=false; }
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").focus(); }
	
	if(document.getElementById("sendButt2"))	{document.getElementById("sendButt2").disabled=false; }
	if(document.getElementById("lgaList:2"))	{document.getElementById("lgaList:2").disabled='disabled';}
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").disabled='disabled'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").disabled='disabled'; }
	if(document.getElementById("includeType"))	{document.getElementById("includeType").disabled=false; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").disabled='disabled'; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").disabled='disabled'; }
	if(document.getElementById('sendButt'))		{document.getElementById('sendButt').title='Enter standard-shapes select mode'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").disabled='disabled'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").style.backgroundColor='#c3c3c3'; }



}
function pointBoxSelect()
{
	if(document.getElementById("sendButt2"))	{document.getElementById("sendButt2").disabled=false; }
	if(document.getElementById("lgaList:2"))	{document.getElementById("lgaList:2").disabled='disabled';}
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").disabled=false; }
	if(document.getElementById("includeType"))	{document.getElementById("includeType").disabled=false; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").disabled='disabled'; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").disabled='disabled'; }
	if(document.getElementById('sendButt'))		{document.getElementById('sendButt').title='Enter rectangle box select mode to get features'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").disabled=false; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").focus(); }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").style.backgroundColor='white'; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").style.backgroundColor='white'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").style.backgroundColor='#c3c3c3';}
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").disabled='disabled'; }

}
function pointCircleSelect()
{
	if(document.getElementById("lgaList:2"))	{document.getElementById("lgaList:2").disabled='disabled';}
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").disabled='disabled'; }
	if(document.getElementById("includeType"))	{document.getElementById("includeType").disabled=false; }
	if(document.getElementById("geomkey"))		{document.getElementById("geomkey").disabled='disabled'; }
	if(document.getElementById("keygeom"))		{document.getElementById("keygeom").disabled='disabled'; }
	if(document.getElementById('sendButt'))		{document.getElementById('sendButt').title='Enter circle select mode to get features'; }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").disabled='disabled'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").disabled=false; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").focus(); }
	if(document.getElementById("rectHeight"))	{document.getElementById("rectHeight").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("rectWidth"))	{document.getElementById("rectWidth").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("circleRad"))	{document.getElementById("circleRad").style.backgroundColor='white'; }
	if(document.getElementById("shapesOptionsList"))	{document.getElementById("shapesOptionsList").disabled='disabled'; }

}
function selectTargets(buttId)
{
	var title = document.getElementById(buttId).title;
	if(title == 'show targets at locations')
	{
		document.getElementById('targetButt').className="hoverButton"	;
		document.getElementById(buttId).title='hide targets at locations';
		if(markers){markers.setVisibility(true);}
	}
	else
	{
		document.getElementById('targetButt').className="standardButton"	;
		document.getElementById(buttId).title='show targets at locations';
		if(markers){markers.setVisibility(false);}
	}
}

function toggleBoundaryLayer(title)
{
	if(title == 'show boundary at address' && boundary)
	{
		// user is asking for the layer to be toggled ON
		document.getElementById('propertyButt').className="hoverButton"	;
		document.getElementById('propertyControl').title='hide boundary at address';
		if(boundary){boundary.setVisibility(true);}
	}
	else
	{
		// user is asking for the layer to be toggled OFF
		document.getElementById('propertyButt').className="standardButton"	;
		document.getElementById('propertyControl').title='show boundary at address';
		if(boundary){boundary.setVisibility(false);}
	}
}
function removeBoundaryLayer(buttId)
{
	if(boundary){boundary.destroy(); boundary = null;}
	if(document.getElementById(buttId))			{	document.getElementById(buttId).style.display='none';	}
	if(document.getElementById('propertyButt'))	{	document.getElementById('propertyButt').className="standardButton"	;}
}

// function to get the target property boundary and jump to the geocoded location - getPolygon service
function showBoundary(buttId, point)
{
	 
	 genLoadStatus('Geocoding Address ...', true, '');
	 
	 // get the polygon type from user options
	 var selectObject = document.getElementById('polyLayers');
	 var polyLayers = selectObject.selectedIndex;

	 // first time or when accuracy high enough
	 genLoadStatus('Fetching Boundary ...', true, '');
	 if(lastAccuracy == -1 || lastAccuracy >= 8) 
	 {
		  var title = document.getElementById(buttId).title;
		  var currentAddress = document.getElementById('search01').value;
		  
		  // strip off the '?' from the service Url 
		  var service = meshBlocksBase.split('?')[0];

		  //var appsUrl = applicationBase+'cf/proxycall.cfm?';     // coldfusion version
		  var query  = 'request=numaGetBBOX&typeid='+polyLayers+'&address='+currentAddress;
		  var ajaxRequest = proxyRequest(query, '', 'GET');
		  var polyBbox = ajaxRequest.responseText;
			
		  // if a valid bbox is returned from service then zoom to the BBox
		  lastAddress = currentAddress;
		  var ords = polyBbox.split(",");
		  if(ords.length == 4 && ords.toString().length < 100)
		  {
			   // get the BBOX of the parcel into appropriate projection
			   ords[0] = parseFloat(ords[0]); 
			   ords[1] = parseFloat(ords[1]); 
			   ords[2] = parseFloat(ords[2]); 
			   ords[3] = parseFloat(ords[3] );
			   
			   // transform to google if required
			   var p = new Array();
			   if (srs == "EPSG:900913")
			   {
				// do the low left point
				p[0] = ords[0]; 
				p[1] = ords[1];
				var point = geogs2google(p);
				p = decodePoint (point);
				ords[0] = p[0];
				ords[1] = p[1];
				// now the high right point
				p[0] = ords[2];
				p[1] = ords[3];
				var point = geogs2google(p);
				p = decodePoint (point);
				ords[2] = p[0];
				ords[3] = p[1];
			   }
			   // build the BBOX parameter
			   var bboxParam = ords[0]+","+ords[1]+" "+ords[2]+","+ords[3];


					 // set map window over parcel boundary
					// bounds = new OpenLayers.Bounds(ords[0], ords[1], ords[2], ords[3]);
					// map.zoomToExtent(bounds);

					// alert('should be over area')



			   if(boundary){boundary.destroy(); boundary=null;}
			   /*
				valid parameters:
					parcelboundary:		set to true if you want to use the numaGetParcelIdSLD service
					address:			address to be used for the point in polygon requests
					typeid:				the selected polygon layer to be used for point-in-polygon
					fillcolor:			hex value of fill colour
					fillOpacity:		decimal number between 0 and 1 for opacity of fill
					fillPattern:		url of image to be used as area fill
					lineColor:			hex value of colour of the polygon boundary
					lineWeigth:			thickness in pixels of the boundary lines
					lineOpacity:		decimal number between 0 and 1 for opacity of boundary
					maxScale:			max scale [denom] at which the polygon will be shown
					minScale:			min scale [denom] at which the polygon will be shown
				*/
			   //appsUrl = numapsService + "request=numaGetParcelSLD&fillcolor=#00ff00&address="+currentAddress+polyLayers;
			   
			   // this will do an extended getMap request to execute ben's numaGetParcelSLD webservice
			   boundary = new OpenLayers.Layer.WMS.Untiled('boundary', service, 
				{
					srs: srs, 
					address:currentAddress, 
					typeid: polyLayers, 
					fillcolor: '#ff0000', 
					fillOpacity:'0.1', 
					parcelboundary:true, 
					format: 'image/png', 
					version:'1.1.3', 
					quality: 'BEST', 
					reaspect: false, 
					transparent:'true'
				});
			   boundary.addOptions(
				{
					isBaseLayer: false, 
					visibility: true, 
					wrapDateLine: true, 
					buffer: buff, 
					reproject: true, 
					tileSize: new OpenLayers.Size(tileSize,tileSize)  
				});
				   registerLoadWheel(boundary, 'loadWheelDrape');
				   map.addLayer(boundary); 
				   resetZlevels();
					 
				   // set map window over parcel boundary
				   bounds = new OpenLayers.Bounds(ords[0], ords[1], ords[2], ords[3]);
				   map.zoomToExtent(bounds);

				   // save currentAddress and set button
				   document.getElementById('propertyButt').className="hoverButton" ;
				   document.getElementById('propertyButtKill').style.display='block';
				   document.getElementById(buttId).title='hide boundary at address';
		  }
		  else
		  {
			   //jump to geocoded point and reset button
			   if(boundary){boundary.destroy(); boundary=null;}
			   map.setCenter(point, goToZoom);
			   alert('Sorry - There was a problem getting the surrounding admin boundary for this address');
		  }
	 }
	 resetZlevels();
	 genLoadStatus('', false, '');
}

function resetZlevels()
{
	//if(PolygonLayer != null)	{PolygonLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -950);}
	if(markers != null)			{markers.setZIndex(map.Z_INDEX_BASE['Popup'] -1000);}

	if(vectorLayer != null)		{vectorLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);}

	if(vectorLayer2 != null)	{vectorLayer2.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);}

	if(vectorLayer3 != null)	{vectorLayer3.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);}

	if(userMarkers != null)		{userMarkers.setZIndex(map.Z_INDEX_BASE['Popup'] -4000); }

	//alert(terrMarkers)
	if(terrMarkers != null)		{terrMarkers.setZIndex(map.Z_INDEX_BASE['Popup'] -4000);}

	//if(vectorLayer4)	{vectorLayer4.setZIndex(map.Z_INDEX_BASE['Popup'] -4010);}

	if(terrLabels != null)		{terrLabels.setZIndex(map.Z_INDEX_BASE['Popup'] -4010);}

	if(boundary != null)		{boundary.setZIndex(map.Z_INDEX_BASE['Popup'] -4050);}

	if(innerBoundaries != null)	{innerBoundaries.setZIndex(map.Z_INDEX_BASE['Popup'] -4050);}	

	if(territory != null)		{territory.setZIndex(map.Z_INDEX_BASE['Popup'] -4100);}

	if(PolygonLayer != null)	{PolygonLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -4150);}
	if(labelLayer != null)		{labelLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -4150);}

	if(maskLayer != null)		{maskLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -4200);}
	
	if(allTerritoriesLayer != null)	{allTerritoriesLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -4900);}

	if(LayerObj.length > 0)
	{
		for (var i=0; i<LayerObj.length; i++)
		{
			var zindex = 5000 + parseInt(i);
			if(LabelObj[i] != null) {LabelObj[i].setZIndex(map.Z_INDEX_BASE['Popup'] -zindex);}
			var zindex = 6000 + parseInt(i);
			if(LayerObj[i] != null) {LayerObj[i].setZIndex(map.Z_INDEX_BASE['Popup'] -zindex);}
			
		}
	}

	if(DrapeHighlight != null )	{DrapeHighlight.setZIndex(map.Z_INDEX_BASE['Popup'] -8800);}
	if(SelectHighlight != null )	{SelectHighlight.setZIndex(map.Z_INDEX_BASE['Popup'] -8800);}

	if(DemoDrape  !=null)		{DemoDrape.setZIndex(map.Z_INDEX_BASE['Popup'] -9000);}
	//if(collectLayer )	{collectLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -9000);}

}	

function makeTableSelectControl(folder, holderId, xmlTag, xmlAttrib, xmlAbstractId, filePrefix)
{
	// get the list of xml files from the folder
	// e.g. folder = 'territories/' or 'useroverlays/preGeocoded/'
	ajaxRequest = null;
	ajaxRequest = getListOfFiles(folder);
	if(ajaxRequest == 'error') 
	{	// switch the buttons and form to the Input screen
		if(filePrefix == 'terr')	{changeMode('newTerr');}
		//if(filePprefix == 'upload')	{}
		return;
	}
	
	// get the names of each file and store in list array
	xmlFiles = null;
	xmlFiles = ajaxRequest.responseText.split("|");
	//alert('list of files = '+xmlFiles)
	xmlTitlesList = []; xmlValuesList = []; xmlAbstractList = [];
	if(xmlFiles.length <= 0 || xmlFiles == null) {alert('there are no files in this folder.'); changeMode('newTerr'); return;}
		
	// Prepare each file for insertion into table
	var loX = 9999999999; 
	var loY = 9999999999; 
	var hiX = -9999999999; 
	var hiY = -9999999999;
	noOfFiles = 0;
	if(filePrefix == 'terr'){	allTerritoriesBounds = new OpenLayers.Bounds(loX,loY,hiX,hiY);}
	for (var j=0; j<xmlFiles.length; j++)
	{
		var filename = applicationBase+"inc/"+folder+xmlFiles[j];
		
		// only process xml files
		var parts = filename.split('.');
		var standardExt = parts[parts.length-1].toUpperCase()
		if(standardExt == 'XML')
		{
			ajaxRequest = loadXml(filename, '', false);
			var header = ajaxRequest.responseXML.getElementsByTagName(xmlTag);
			if(header.length == 1)
			{	var name = header[0].getAttribute(xmlAttrib);
				//alert('xmlAbstract = '+xmlAbstractId)
				var xmlAbs = name;
				if(!header[0].getAttribute('abstract')) {var xmlAbs = header[0].getAttribute('abstract');}
				
			}
			else {var name = xmlFiles[j];}
			xmlTitlesList[j] = name;
			xmlAbstractList[j] = xmlAbs;
			xmlValuesList[j] = folder+xmlFiles[j];
			noOfFiles++;
			
			// get this territory BBox and extend the overall allTerritoriesBbox
			if(filePrefix == 'terr')
			{
				var thisTerritory = ajaxRequest.responseXML.getElementsByTagName('Territory');
				var thisTerrBbox = thisTerritory[0].getAttribute('territoryBbox');
				
				// split Bbox into its geometry parts
				var loleft = thisTerrBbox.split(' ')[0];
				var loXpt = parseFloat(loleft.split(',')[0]);
				var loYpt =  parseFloat(loleft.split(',')[1]);
				var topright = thisTerrBbox.split(' ')[1];
				var hiXpt =  parseFloat(topright.split(',')[0]);
				var hiYpt =  parseFloat(topright.split(',')[1]);

				// adjust min max values
				if(loXpt < loX){loX = loXpt; }
				if(loYpt < loY){loY = loYpt; }
				if(hiXpt > hiX){hiX = hiXpt; }
				if(hiYpt > hiY){hiY = hiYpt; }
			}
		}
	}

	// now overwrite the Territory Bounds with the new bounds
	if(filePrefix == 'terr')
	{
		//drawBbox(loX,loY,hiX,hiY,'magenta', true)
		//territoryBounds = null;
		allTerritoriesBounds = new OpenLayers.Bounds(loX,loY,hiX,hiY);
		//alert('after folder read = '+allTerritoriesBounds)
	}

	// check and remove the body of the table
	
	checkRemoveObject('tab:'+folder);
	var table = document.createElement('table');
	table.id='tab:'+folder; 
	table.setAttribute('id','tab:'+folder);
	//alert('id of table = '+'tab:'+folder)
	table.style.color='#000000'; 
	table.style.position='absolute'; 
	table.style.top='0px'; 
	table.style.left='0px'; 
	table.style.paddingTop='0px'; 
	table.style.paddingBottom='2px'; 
	table.style.height='auto'; 
	table.style.width='100%'; 
	table.style.borderCollapse='collapse'; 
	table.style.fontWeight='bold'; 
	table.style.fontSize='9px'; 
	table.style.backgroundColor='#FFFFFF';
	
	// now build the table body
	var tableBody = document.createElement('tbody');
	
	// list all the files in the folder here
	if (filePrefix == 'upload')		{  noOfXml = noOfFiles; }
	else if(filePrefix == 'terr')	{ noOfTerr = noOfFiles; }
	if(noOfFiles > 0)
	{
		// create each Option for the select box
		//alert('current row = '+currentXmlRow)
		for (var i=0; i<xmlTitlesList.length ; i++)
		{
			var row = document.createElement("tr");
			row.style.height='15px';
			row.id = filePrefix+'_rowNo:'+i;
			row.setAttribute('id',filePrefix+'_rowNo:'+i)
			
			// set up row status look and feel
			//alert(' current row number = '+currentXmlRow)
			//alert(' row ID = '+filePrefix+'_rowNo:'+i)
			//if(currentXmlRow == i || currentTerrRow == i)
			//{	row.className='selectedItem';		}
			//else
			//{	row.className='unselectedItem';		}
			
			// add the Open Territory/XML cell
			var openCell = document.createElement('td');
			openCell.style.width='15px';
			openCell.id = filePrefix+'_op:'+i; 
			openCell.setAttribute('id',filePrefix+'_op:'+i);	
			openCell.className='unselectedItem';
				// add the open Territory cell
				var openIt = document.createElement('img');
				openIt.src='images/open.gif';
				openIt.style.borderStyle='none';
				//openIt.style.height='100%';
				//openIt.style.width='100%';
				openIt.style.cursor='pointer';
				
				openIt.id = filePrefix+'_open:'+i; 
				openIt.value = xmlValuesList[i];
				openIt.setAttribute('id',filePrefix+'_open:'+i);
				
				openIt.style.backgroundColor = 'transparent';
				openIt.title='click here to open the file '+xmlTitlesList[i];
				if(filePrefix == 'terr')		{	bindEvent(openIt, 'click', getTerr, 'false');}
				else if(filePrefix == 'upload')	{	bindEvent(openIt, 'click', getXml, 'false');}
				openCell.appendChild(openIt);
			row.appendChild(openCell);

			// add the polygon name cell
			var nameCell = document.createElement('td');
			nameCell.id = filePrefix+'_name:'+i; 
			nameCell.setAttribute('id',filePrefix+'_name:'+i);
			//alert(filePrefix+'_name:'+i)

			nameCell.style.width='150px';
			nameCell.style.paddingLeft='2px';	
			nameCell.value = xmlTitlesList[i];
			nameCell.className='unselectedItem';
			
			// setup mouseover title
			if(xmlAbstractList[i] == '')
			{ nameCell.title = xmlTitlesList[i];}
			else
			{ nameCell.title = xmlAbstractList[i];}
			
			// setup name of cell
			var text = document.createTextNode(xmlTitlesList[i]);
			nameCell.appendChild(text);
			row.appendChild(nameCell)

			//nameCell.setAttribute("title", "header=[Published File Description] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+abs+"]");
			//nameCell.title= "header=[Published File Description] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+abs+"]";
			//nameCell.style.zIndex = 100000;		
			
	
			// add delete me cell
			var delCell = document.createElement('td');
			delCell.style.width='15px';
			delCell.className='unselectedItem';	
			delCell.id = filePrefix+'_kill:'+i; 
			delCell.setAttribute('id',filePrefix+'_kill:'+i);
				
				// add the deleteme image
				var delImg = document.createElement('img');
				delImg.src='images/deleteme.gif';
				delImg.style.borderStyle='none';
				delImg.style.cursor='pointer';
				delImg.style.backgroundColor = 'transparent';
				delImg.id = filePrefix+'_del:'+i; 
				delImg.setAttribute('id',filePrefix+'_del:'+i);
				delImg.value = xmlValuesList[i];
				delImg.title='click here to remove '+xmlTitlesList[i]+' from Territory Folder';
				bindEvent(delImg, 'click', removeThisFile, 'false');
				delCell.appendChild(delImg);
			row.appendChild(delCell);

		tableBody.appendChild(row);
		}
	}
	else
	{
		var textNode = document.createTextNode('No Territories Available');
		tableBody.appendChild(textNode);
		changeMode('newTerr');
	}
	table.appendChild(tableBody);
	document.getElementById(holderId).appendChild(table);
	
	//alert(xmlTitlesList);

	
}
function resetMenuSelection(id)
{
	// set the row to be the selected row
	var rowNo  = parseInt(id.split(":")[1]);
	filePrefix = id.split("_")[0];

	// highlight the actual row
	//alert("rowNo = "+rowNo+ " and noOfFiles = "+noOfFiles+" filePrefix = "+filePrefix);

	for (var i=0; i<noOfFiles; i++)
	{	//alert ('id= '+filePrefix+'_rowNo:'+i)
		if(rowNo == i) 
		{	
			document.getElementById(filePrefix+'_op:'+i).className = 'selectedItem';
			document.getElementById(filePrefix+'_name:'+i).className = 'selectedItem';
			document.getElementById(filePrefix+'_kill:'+i).className = 'selectedItem';
			
		}
		else
		{	document.getElementById(filePrefix+'_op:'+i).className = 'unselectedItem';
			document.getElementById(filePrefix+'_name:'+i).className = 'unselectedItem';
			document.getElementById(filePrefix+'_kill:'+i).className = 'unselectedItem';
		}
	}
}
function getXml(evt)
{
	// get the file name for this option
	var id = getThisId(evt);
	geocodedFile = document.getElementById(id).value;
	xmlFileActive = true;
	fileUploaded = false;
	firstTime=true;
	rangesDone=false;
	currentXmlRow = id.split(":")[1];

	resetMenuSelection(id);

	// display the file of points
	showUserPoints(geocodedFile, '', ''); 
	zoomExtent(zoom);

	Event.stop(evt);
}

function getTerr(evt)
{
	// get the file name for this option
	var id = getThisId(evt);
	currentTerritory = document.getElementById(id).value;
	
	// load the Territory selected
	showTerritory(currentTerritory);
	currentTerrRow = id.split(":")[1];
	resetMenuSelection(id);
	newTerritory = false;
	// initialise opacity of the territory
	terrSlider.setPosition(1.0);

	// shut down this panel
	document.getElementById('folderPanel').style.display='none';

	Event.stop(evt);
}
function removeThisFile(evt)
{
	// get the BBox for this option
	var id = getThisId(evt);
	var filePrefix = id.split('_')[0];
	//alert('filePrefix = '+filePrefix)
	var thisFileName = document.getElementById(id).value;
	//alert('filename = '+thisFileName)
	if(confirm ('Do you wish to PERMANENTLTY DELETE the File from Disk - this cannot be undone?'))
	{
		// delete the file from the folder directory
		if(!deleteit(thisFileName)){alert('file '+thisFileName+' was not deleted'); return;}

		// rebuild the territories selection panel
		//alert(filePrefix)
		if(filePrefix == 'terr')
		{	// remove this deleted territory
			removeTerritory();

			// if all territories is still set then redraw all territories
			showHideAllTerritories('showAllTerr')
			
			// make a new table control
			makeTableSelectControl(territoryFolder, 'territoriesList', 'Territory', 'territoryName', 'abstract', 'terr');
			document.getElementById('listTerr').title = 'Hide Report';
			// set the button characteristics
			if(currentTerrRow > 0){	resetMenuSelection(filePrefix+'_rowNo:'+currentTerrRow);	}
		}
		else if(filePrefix == 'upload')
		{	// remove this collection from map
			killAllMarkers();
			
			// make a new table control
			currentXmlRow = -1;
			makeTableSelectControl('useroverlays/preGeocoded/', 'publishedList', 'Addresses', 'name', 'abstract', 'upload');
			if(currentXmlRow >0 ){ resetMenuSelection(filePrefix+'_rowNo:'+currentXmlRow);	}
		}
		
	}
	
	genLoadStatus('', false, '');
	Event.stop(evt);
}

