function showHideGraph()
{
	//alert('There are '+nic+' polygons in this group')
	//alert('collection.length = '+collection.length)
	//var delta = nic - limit;
	//if (nic >= limit) {alert ("There are more than "+limit+" polygons in this collection.\n Please remove at least "+delta+" one from the collection."); return;}
	//alert(collection)
	//alert ('currentAtts = '+currentAtts)
	
	if (collection != '')
	{
		var wholeColl = collection;
		graphPopup(wholeColl, currentAtts ); 
	}
}

function mapTemplatePopup() 
{
	var bord = 30;
	var title = 'Enter your Text here (up to 200 characters)';
	// setup map annotation controls
	wdt = map.getSize().w;
	hgt = map.getSize().h;
	scale = parseInt(map.getScale());
	width = wdt + 2*bord;
	height = hgt + 5*bord;
	
	// set up location for Map box
	maptop = 4*bord;
	mapleft = bord;
	tablehgt = 3*bord;
	tablewdt = wdt;

	// set up location of map header line
	texttop = bord-15;
	textleft = bord;

	// get the current date data
	var d = new Date();
	day = d.getDate();
	month = d.getMonth()+1;
	year = d.getFullYear();

	// create the new popup window
	winmap = window.open('NuMaps','myconsole',
		'width='+width+',height='+height 
		+',alwaysRaised'
		+',menubar=0'
		+',toolbar=0'
		+',status=0'
		+',scrollbars=0'
		+',resizable=0')
	winmap.document.writeln
	(
		'<html><head><title>NuMaps Printable Map</title>'
			+'<style>'
				+'html, body {height: 100%; width: 100%; background-color:#ECE9D8;	overflow-x:hidden;	overflow-y:hidden; font-family:Verdana; font-size:9px; }'
				+'a {text-decoration:none; }'
				+'.whiteBox {border-right:1px solid #d4d4d4; border-bottom: 1px solid #d4d4d4;	border-top:1px solid gray;	border-left:1px solid gray; background-color:white;}'
				+'#printMap {background-color:#B5D6F1; width:100%; height:100%; z-index:0;}'
					
			+'</style>'
		+'</head>'
			+'<body onLoad="self.focus(); ">'
				+'<table border=0 style="position:absolute; top:'+bord+'px; left:'+bord+'px; height:'+tablehgt+'px; width:'+tablewdt+'px; border:1px solid #d2d2d2;">'
					+'<tr>'
						+'<td style="width:100px; height:20px; text-align:left; border-bottom:1px solid #d2d2d2;">'
							+'<a href="http://www.numaps.com.au" target="_blank" ><img border=0 src="images/numapsLogo_small.gif" /></a>'
						+'</td>'
						+'<td  style="height:20px;  font-weight:bold; font-style:Arial; font-size:10px; text-align:center; border-bottom:1px solid #d2d2d2;">'
							+'<textArea cols="200" rows="1" style="width:80%; height:20px; text-align:center; font-style:Arial; font-weight:bold; background-color:transparent; border-style:none; font-size:18px; ">'
								+'Enter Your Map Title Here'
							+'</textArea>'
						+'</td>'
						+'<td  style="width:120px; height:20px; text-align:right; font-size:9px; border-bottom:1px solid #d2d2d2;">'
							+'<span>'
								+'Date : '+day+"/"+month+"/"+year
							+'</span>'
						+'</td>'
					+'</tr>'

					+'<tr>'
						+'<td style="width:100px; height:20px; text-align:left; font-size:9px; border-bottom:1px solid #d2d2d2;">'
							+'<span>'
								
							+'</span>'
						+'</td>'
						+'<td  style="height:20px; text-align:center; font-size:12px; border-bottom:1px solid #d2d2d2;">'
							+'<textArea cols="200" rows="1" style="width:80%; font-size:12px; height:20px; font-style:Verdana; text-align:center; background-color:transparent; border-style:none;">'
								+title
							+'</textArea>'
						+'</td>'
						+'<td  style="width:120px; height:20px; text-align:right; font-size:9px; border-bottom:1px solid #d2d2d2;">'
							+'<span>'
								
							+'</span>'
						+'</td>'
					+'</tr>'

					+'<tr>'
						+'<td style="width:40px; height:20px; text-align:left; font-size:11px; border-bottom:1px solid #d2d2d2;">'
							+'<span>'
								+'Plan No : '
							+'</span>'

							+'<textArea cols="10" rows="1" style="top:2px; width:50px; font-size:11px; height:12px; font-style:Verdana; text-align:left; background-color:transparent; border-style:none;">'
								+'0000'
							+'</textArea>'
							
						+'</td>'
						+'<td  style="height:20px; text-align:center; font-style:Verdana; font-size:12px; border-bottom:1px solid #d2d2d2;">'
							+'<textArea cols="200" rows="1" style="width:80%; font-size:12px; height:20px; font-style:Verdana; text-align:center; background-color:transparent; border-style:none;">'
								+title
							+'</textArea>'
						+'</td>'
						+'<td  style="width:120px; height:20px; text-align:right; font-size:9px; border-bottom:1px solid #d2d2d2;">'
							+'<span>'
								+'Scale 1 : '+scale
							+'</span>'
						+'</td>'
					+'</tr>'

					+'<tr>'
						+'<td>'
						+'</td>'
					+'</tr>'
				+'</table>'
				
				
				+'<div id="canvas2" class="whiteBox" style="position:absolute; top:'+maptop+'px; left:'+mapleft+'px; height:'+hgt+'px; width:'+wdt+'px; background-color:transparent;" >'
					
					+'<div id="printMap">'
					+'</div>'

				+'</div>'
			+'</body>'
		+'</html>'
	)
	winmap.document.close();
	PrintMap();
}


// this assumes that the Map object is a JavaScript variable named "map"
// changed 20090928:
// * fixed the weird references about iframes, since they're not the usual use case
// * added the Please Wait window
// * used newer-style OpenLayers.Request.POST() for final AJAX call
//var print_wait_win = null;
function PrintMap() 
{
    //-- post a wait message
    //print_wait_win = window.open("pleasewait.html", "print_wait_win", "scrollbars=no, status=0, height=5, width=10, resizable=1");
	newMap = winmap.document.getElementById("printMap");

	// go through all layers, and collect a list of objects
    // each object is a tile's URL and the tile's pixel location relative to the viewport
    var size  = map.getSize();
    var tiles = [];
    for (layername in map.layers) 
	{
        // if the layer isn't visible at this range, or is turned off, skip it
        var layer = map.layers[layername];
        if (!layer.getVisibility()) continue;
        if (!layer.calculateInRange()) continue;
		//alert('layer.name = '+layer.name);
		
		// handle any basemap layer
		for(var i=0; i<baseMapsList.length; i++)
		{	
			if(layer.name == baseMapsList[i])	
			{	
				//alert(layer.name+' is a base layer')
				// create the base map layer in the printMap object
				if (srs == 'EPSG:900913')	//------------- sphericalMercator option
				{
					var options = 
					{
						projection: srs,  
						units: "m",  
						controls:[],  
						maxResolution: res,  
						displayProjection: new OpenLayers.Projection("EPSG:4326"), 
						//numZoomLevels: 22,  
						maxExtent: new OpenLayers.Bounds(ozBox[0],  ozBox[1],  ozBox[2],  ozBox[3])
					};
					printMap = new OpenLayers.Map(winmap.document.getElementById("printMap"), options);
				}
				else if(srs == "EPSG:4326" )						//------------ standard geographicals option
				{
					var options = 
					{
						projection:srs,  
						controls:[],  
						units:'degrees',  
						maxResolution: res,   
						maxExtent: new OpenLayers.Bounds(ozBox[0],  ozBox[1],  ozBox[2],  ozBox[3])
					};
					printMap = new OpenLayers.Map(winmap.document.getElementById("printMap"), options);
				}
				else{alert(srs+' coordinate system not supported [epsg:900913 & epsg:4326 supported]'); return;}
				
				//GoogleMaps', 'GoogleHills', 'GoogleHybrid', 'GoogleSat', 'NuMaps', 'NearMap'
				
				if (layer.name == 'GoogleMaps' && layer.getVisibility())
				{	
					googleMap2 = new OpenLayers.Layer.Google( "GoogleMaps2" , {type: G_NORMAL_MAP, sphericalMercator:spMerc} );
					googleMap2.addOptions({isBaseLayer: true, wrapDateLine: true, buffer: buff, minZoomLevel:4, numZoomLevels:20, maxZoomLevels:20, maxResolution: res });
					printMap.addLayer(googleMap2);
				}
				else if (layer.name == 'GoogleHybrid' && layer.getVisibility())
				{	
					googleHybrid2 = new OpenLayers.Layer.Google( "GoogleMaps2" , {type: G_HYBRID_MAP, sphericalMercator:spMerc} );
					googleHybrid2.addOptions({isBaseLayer: true, wrapDateLine: true, buffer: buff, minZoomLevel:4, numZoomLevels:20, maxZoomLevels:20, maxResolution: res });
					printMap.addLayer(googleHybrid2);
				}
				else if (layer.name == 'GoogleHills' && layer.getVisibility())
				{	
					googleHills2 = new OpenLayers.Layer.Google( "GoogleMaps2" , {type:  G_PHYSICAL_MAP, sphericalMercator:spMerc} );
					googleHills2.addOptions({isBaseLayer: true, wrapDateLine: true, buffer: buff, minZoomLevel:4, numZoomLevels:20, maxZoomLevels:20, maxResolution: res });
					printMap.addLayer(googleHills2);
				}
				else if (layer.name == 'GoogleSat' && layer.getVisibility())
				{	
					googleSat2 = new OpenLayers.Layer.Google( "GoogleMaps2" , {type: G_SATELLITE_MAP, sphericalMercator:spMerc} );
					googleSat2.addOptions({isBaseLayer: true, wrapDateLine: true, buffer: buff, minZoomLevel:4, numZoomLevels:20, maxZoomLevels:20, maxResolution: res });
					printMap.addLayer(googleSat2);
				}
				else if (layer.name == 'NuMaps' && layer.getVisibility())
				{	
					googleNuMaps2 = new OpenLayers.Layer.WMS.Untiled( "NuMaps" , numapsService, { sld:numapsBasemapUrl, sphericalMercator: spMerc, format: drapeImage, quality:'BEST', transparent:true} ); 
					googleNuMaps2.addOptions({isBaseLayer: true, wrapDateLine: true, buffer: buff, minZoomLevel:4, numZoomLevels:20, maxZoomLevels:20, maxResolution: res });
					printMap.addLayer(googleNuMaps2);
				}
				else if (layer.name == 'NearMap' && layer.getVisibility())
				{	
					googleNearMap2 = new OpenLayers.Layer.TMS
					(
						"NearMap",
						"http://www.nearmap.com/maps/",
						{
							type: 'png' 
							,getURL: get_my_url			// this gets the urls
							//,displayOutsideMaxExtent: true
							,sphericalMercator:spMerc
						}
					);
					googleNearMap2.addOptions(
					{	
						attribution: 'Image Base Map from Nearmap',
						//scales: [50000000,20000000,5000000,1000000,500000,250000,100000,50000,25000,10000,5000,2500,1000,500],
						isBaseLayer: true,
						buffer: buff,
						maxExtent: bounds,
						maxResolution: res, 
						units: units, 
						projection: new OpenLayers.Projection(proj),
						displayProjection: new OpenLayers.Projection(dproj),
						opacity: 1,
						minZoomLevel: 4, numZoomLevels:22, numZoomLevels:22,
						reproject: false
					});
					printMap.addLayer(googleNearMap2);
				}
				//printMap.addControl(new OpenLayers.Control.PanZoomBar());
				printMap.addControl(new OpenLayers.Control.LayerSwitcher())
				
				//alert('centre = '+map.getCenter()+' zoom = '+map.getZoom());
				printMap.setCenter(map.getCenter(), map.getZoom());
			}
			else // process all other WMS layers
			{
				//alert(layer.name+' is NOT a base layer')
				// check fo any DemographicDrape Layer
			/*	alert('drapeId = '+drapeId)
				alert('layStyle = '+layStyle)
				alert('drapeWmslayer = '+drapeWmslayer)
				alert('sldUrl = '+sldUrl)
				alert('layName = '+layName)
				alert('layFile = '+layFile)
			*/	
				// if a style DDrape then generate from database
				if(layStyle != '' &&  layStyle != 'default' && drapeWmslayer != '')
				{	
					//alert('styles')
					//alert('putstyles = '+putStyles)
					DemoDrape2 = new OpenLayers.Layer.WMS.Untiled(layName, numapsService, {layers: drapeWmslayer,  styles: layStyle,  format: drapeImage, version:'1.1.3', quality: quality, reaspect: false, transparent:'true', opacity:'0.8'});
					DemoDrape2.addOptions({isBaseLayer: false, visibility: true, wrapDateLine: true, buffer: buff, reproject: true, tileSize: new OpenLayers.Size(tileSize,tileSize) });
					//registerLoadWheel(DemoDrape2, 'loadWheelDrape');
					printMap.addLayer(DemoDrape2);	
					//map.setLayerZIndex(DemoDrape2, 0);
					//DemoDrape2.setZIndex(map.Z_INDEX_BASE['Popup'] -9000);
					
				/*	var highlightName=layName+'Highlight';	
					DrapeHighlight = new OpenLayers.Layer.WMS.Untiled( highlightName, numapsService, {layers: drapeWmslayer, styles: layStyle, format: drapeImage, version:'1.1.3', quality: quality, reaspect: false, transparent:'true' });
					DrapeHighlight.addOptions({isBaseLayer: false, visibility: false, wrapDateLine: true, buffer: buff, reproject: true });
					registerLoadWheel(DrapeHighlight, 'loadWheelDrape');
					map.addLayer(DrapeHighlight);
					//map.setLayerZIndex(DrapeHighlight, 180);
					DrapeHighlight.setZIndex(map.Z_INDEX_BASE['Popup'] -8800);
				*/
				}
				else
				{
					//DemoDrape.mergeNewParams({rand: Math.random()});
					//if this is a temp SLD the do not reset the putStyles
					//var parts = sldUrl.split('/newSld_');
					//if(parts > 1){	putStyles=false;	}
					//alert('sld')

					DemoDrape2 = new OpenLayers.Layer.WMS.Untiled(layName, numapsService, {SLD: sldUrl,  format: drapeImage, version:'1.1.3',   quality: 'BEST', reaspect: false, transparent:'true', opacity:'0.8'});		
					DemoDrape2.addOptions({isBaseLayer: false, visibility: true, wrapDateLine: true, buffer: buff,  reproject: true, tileSize: new OpenLayers.Size(tileSize,tileSize) });
					//registerLoadWheel(DemoDrape2, 'loadWheelDrape');
					printMap.addLayer(DemoDrape2);	
					//map.setLayerZIndex(DemoDrape2, 0);
					//DemoDrape2.setZIndex(printMap.Z_INDEX_BASE['Popup'] -9000);
					/*
					var highlightName=layName+'Highlight';
					DrapeHighlight = new OpenLayers.Layer.WMS.Untiled( highlightName, numapsService, {sld: sldUrl, format: drapeImage, version:'1.1.3', quality: 'BEST', reaspect: false, transparent:'true'});
					DrapeHighlight.addOptions({isBaseLayer: false, visibility: false, wrapDateLine: true, buffer: buff, reproject: true });
					registerLoadWheel(DrapeHighlight, 'loadWheelDrape');
					map.addLayer(DrapeHighlight);
					//map.setLayerZIndex(DrapeHighlight, 180);
					DrapeHighlight.setZIndex(map.Z_INDEX_BASE['Popup'] -8800);
					*/
				}

			}
		
		}
		
	}
		// add this layer to the print map window
/*
		// iterate through their grid's tiles, collecting each tile's extent and pixel location at this moment
        for (tilerow in layer.grid) {
            for (tilei in layer.grid[tilerow]) 
			{
                var tile     = layer.grid[tilerow][tilei]
                var url      = layer.getURL(tile.bounds);
                var position = tile.position;
                var opacity  = layer.opacity ? parseInt(100*layer.opacity) : 100;
                tiles[tiles.length] = {url:url, x:position.x, y:position.y, opacity:opacity};
            }
        }
    }
    // hand off the list to our server-side script, which will do the heavy lifting
    //var tiles_json = JSON.stringify(tiles);
   // var params = '&width='+size.w + '&height='+size.h + '&tiles='+escape(tiles_json) ;

	// execute the request via proxy server
	//var appsUrl = applicationBase+'cf/proxycall.cfm?';					// coldfusion version
	//var query  = 'url=json.php'+params;
	//alert(appsUrl+query)
	//ajaxRequest = fetchXml(appsUrl, query, false, 'POST');	
	//if (ajaxRequest.status != 200) {alert('error within proxyRequest function'); }

	//makePopup(fetchXml(appsUrl, query, false, 'POST'), '800', '800', 'auto')
	
	
	//window.open(proxyRequest('', query, '', 'POST'));
	
	OpenLayers.Request.POST
	(
      { url:'print.php',
        data:OpenLayers.Util.getParameterString({width:size.w,height:size.h,tiles:tiles_json}),
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        callback: function(request) 
		{
          // print_wait_win.close();
           window.open(request.responseText);
        }
      }
    );
*/
}



// function to determine if a point is inside a polygon array
function isPointInPoly(poly, pt)
{
/*	var ii;
	for(var c = false, ii = -1, l = allX.length, j = l - 1; ++ii < l; j = ii)
		((allY[ii] <= pt[1] && pt[1] < allY[j]) || (allY[j] <= pt[1] && pt[1] < allY[ii]))
		&& (pt[0] < (allX[j] - allX[ii]) * (pt[1] - allY[ii]) / (allY[j] - allY[ii]) + allX[ii])
		&& (c = !c);
	//alert('in-out indicator = '+c);
	return c;
*/
	for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
		((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
		&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
		&& (c = !c);
	return c;

}
//-----------------------load ststues reporting------------------------//
function genLoadStatus(thisMessage, wheel, timeOut)
{
	//this will write out a message to the apps status area whenever called
	var messDiv = document.getElementById('loadStatus');
	if(thisMessage != '')
	{
		checkRemoveObject('loadMessage');
		var message = document.createElement('div');
		message.id='loadMessage';
		message.setAttribute('id', 'loadMessage');
		var text = document.createTextNode(thisMessage);
		message.appendChild(text);
		message.style.position='relative';
		message.style.top='2px';
		message.style.left='0px';
		//message.style.border='1px solid red';
		messDiv.appendChild(message);
		messDiv.style.display='block';
		if (wheel)
		{	
			document.getElementById('loadWheel').style.display='block';
			if(document.getElementById('eventsLogID')){document.getElementById('eventsLogID').style.display='block';}
		}
		else
		{	document.getElementById('loadWheel').style.display='none';		}
	}
	else 
	{
		messDiv.style.display='none';
		if(document.getElementById('eventsLogID')){document.getElementById('eventsLogID').style.display='none';}
	}
}

// Get all the startup parameters and defaults
function getParams()
{
	//-------------- get the pamaters after the ? of the url submitted -----------
	params = getUrlVars();
	account='NUMAPS';
	drapes = njsResourceDir + 'drapeLists.xml';  
	layersFile = 'data/layers.xml';
	tileSize = '512'; 
	startZoom = 1;
	startScale = 14000000;
	gfiLimit = 10000;
	vectOpac = 1.0;
	nuCache = true;
	buff = 1;
	ccNo = 4;
	ccInc = 10000;
	gfiDoubleClick = true;
	startBasemap = 'googleMap';
	sldLimit = 5000;
	username='';
	//accumulate = false;
	password='';
	direction='horizontal'
	quality='QUICKEST';
	markerZm = 8;
	loadIT = true;
	filterTol=0;
	srs = 'EPSG:900913'; 	//var srs = "EPSG:4326";
	drapeImage = 'image/png';
	linkAddr = 'http://www.numaps.com.au';
	//logoImg = 'images/numaps_120.png';  // this is the old one
	logoImg = 'images/numapsLogo.png';
	outFormat = 'BXFS';		// this is default for CubeWerx but can be overwritten via layer control file
	country='Australia';	// this is default but can be overwritted in address entry

	// pick off each supported parameter
	for (var i = 0; i<params.length ; i++)
	{
		//alert(params[i] +" = "+params[params[i]])
		if(params[i] == 'accCode')
		{	
			drapes = njsResourceDir + 'drapeLists_'+params[params[i]]+'.xml';
			account = params[params[i]];
		}
		if(params[i] == 'tileSize'){tileSize = params[params[i]];}
		if(params[i] == 'srs'){srs = params[params[i]];}
		if(params[i] == 'imgFormat'){drapeImage = params[params[i]];}
		if(params[i] == 'logoSrc'){logoImg = params[params[i]];}
		if(params[i] == 'home'){linkAddr = params[params[i]];}
		if(params[i] == 'gfiLimit'){gfiLimit = params[params[i]];}
		if(params[i] == 'drapes'){drapes = params[params[i]];}
		if(params[i] == 'layers'){layersFile = params[params[i]];}
		if(params[i] == 'opac') {vectOpac = params[params[i]];}
		if(params[i] == 'cache') {nuCache = params[params[i]];}
		if(params[i] == 'buff') {buff = parseInt(params[params[i]]);}
		if(params[i] == 'username') {username =params[params[i]];}
		if(params[i] == 'password') {password = params[params[i]];}
		if(params[i] == 'filter') {filterTol = params[params[i]];}
		if(params[i] == 'markerZm') {markerZm = params[params[i]];}
		if(params[i] == 'basemap') {startBasemap = params[params[i]];}
		if(params[i] == 'quality') {quality = params[params[i]];}
		if(params[i] == 'zoom') {startZoom = params[params[i]];}
		if(params[i] == 'account') {account = params[params[i]];}
		if(params[i] == 'menu') {direction = params[params[i]];}
		//if(params[i] == 'accumulate') {accumulate = params[params[i]];}
		if(params[i] == 'ccNo') {ccNo = params[params[i]];}
		if(params[i] == 'ccInc') {ccInc = params[params[i]];}
		if(params[i] == 'loader') 
		{
			if(params[params[i]] == 'false' || params[params[i]] == false)
			{	loadIT = false; }
			else 
			{	loadIT = true;} 
		}
		
	}
	//--------------- sniff the browser being used ----------------
	//var browserName=navigator.appName;  // important for getFeature decoding
	// browserName = Netscape or Microsoft Internet Explorer
	br=new Array(4);
	os=new Array(2);
	flash=new Array(2);
	br=getBrowser();
	browser = br[0]
	version = getMajorVersion(br[1])
	
	// apply XML browser difference here
	prefix='gml:';
	if ((browser =='firefox' && version == '2') || (browser == 'safari'))
	{	prefix='';	}	
}

function getUrlVars()
{
	var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {	
		hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function proxyRequest(uri, request, file, type)
{
	// execute the request via proxy server
	var appsUrl = applicationBase+'cf/proxycall.cfm?';					// coldfusion version
	var query  = 'url='+meshBlocksBase.split('?')[0]+"&"+request;
	ajaxRequest = fetchXml(appsUrl, query, false, type);	
	if (ajaxRequest.status != 200) {alert('error within proxyRequest function'); return ajaxRequest;}
	return ajaxRequest;
}

function proxyRequestPhp(uri, request, file, type)
{
	// execute the request via proxy server
	var appsUrl = applicationBase+njsResourceDir+'getPolygonBbox.php?';					// PHP version
	var query  = 'url='+meshBlocksBase.split('?')[0]+"&"+request;
	//alert(appsUrl + query)
	ajaxRequest = fetchXml(appsUrl, query, true, type);	
	if (ajaxRequest.status != 200) {alert('error within proxyRequest function'); return ajaxRequest;}
	return ajaxRequest;
}

//--------------- Generic function to launch a PopUp window --------------------//
function makePopup(url, wdth, hght, overflow) // overflow can be 'scroll', 'resize' or 'both'
{
	if(win) {win.close();}
	if (  (url != "")  &&  (url != null)  )
	{
		if (hght > 800) {hght = 800;}
		if (wdth > 800)  {wdth = 800;}
		if (overflow == '' || !/^(scroll|resize|both)$/.test(overflow))
		{ overflow = 'both';}
		//alert(wdth+" : "+hght)
		var params = 'width='+wdth+
			', height='+hght+
			', top=100, left=100'+
			', scrollbars='+(/^(scroll|both)$/.test(overflow) ? 'yes' : 'no')+
			', resizable=' +(/^(resize|both)$/.test(overflow) ? 'yes' : 'no')+
			', status=yes'+
			', toolbar=no'+
			', menubar=yes'+
			', location=no'+
			', alwaysRaised';
		// Now launch the window
		win = window.open (url, '', params);
		//win.setZOptions('alwaysRaised');
		return win;
	}
}

function pause(numberMillis) 
{
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) 
	{
		now = new Date();
		if (now.getTime() > exitTime)
		return;
	}
}
// ---------------- function to launch a sized window ---------------
function popUp(Url) 
{
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(Url, '" + id + "', 'toolbar=0,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width=650,height=300,left = 200,top = 200');");	
}
function killit(path, delfile)
{
	// this will remove the file called 'temp' from the disk
	var url=njsResourceDir + 'deletefile.php?';
	var query="path="+path+"&file="+delfile;
	loadXml(url, query);
	return true;
}
//---------------- delete a file on the server ---------------------//
function deleteit(delfile)
{
	
	//alert ('file for delete in deleteit = '+delfile)
	// this will remove the file called delfile passed in from the server
	var url=njsResourceDir + 'deleteit.php';
	var query="?file="+delfile;
	if(!loadXml(url, query)) {return false;}
	return true;
}

// -------------------- function to bind an event to an object ------------------------
function bindEvent(object, event, fnct, status)
{
	if (status) status=false;
	if (object.addEventListener)
	{	object.addEventListener(event, fnct, status);  }// for FF 
	else 
	{	object.attachEvent("on"+event, fnct); }// for IE
}
function unload()
{
	map.destroy;
	OpenLayers.Event.observe(window, 'unload', OpenLayers.Event.unloadCache, false);
	GUnload();
}

function roundNumber(num, dec) 
{
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
//------------ check that the file of a certain extenstion type is already on server -------------------
function checkFileExists(checkFile, collPath, collExts)
{
	//alert('file = '+checkFile)
	//alert('path = '+collPath)
	//alert('ext = '+collExts)
	
	// get a directory list of files from server in XML
	getFolderList(collPath, collExts);
	// scan through the list of files
	var fileList = ajaxRequest.responseXML.getElementsByTagName("files");
	var fileNames = fileList[0].getElementsByTagName("file");
	for (var k=0; k<fileNames.length; k++)
	{
		var serverFile = fileNames[k].firstChild.nodeValue;
		var serverFilename = serverFile.split('.')				// strip off the extension
		if (checkFile == serverFilename[0]) {return true;}
	}
	return false;
}
// ----------- general routine to make a file copy ------------
function copyFile (oldFileName, fileName, path)
{
	//alert (oldFileName+" : "+fileName)
	var url  = njsResourceDir + "copyfile.php";
	var query="?oldf="+oldFileName+"&newf="+fileName+"&path="+path;
	loadXml(url, query);
	return true;
}

// ----------- general routine to rename a file ------------
function renameFile (oldFileName, newFileName, path)
{
	//alert (newFileName+" >> "+oldFileName)
	var url  = njsResourceDir + "renameFile.php";
	var params = "?oldFile="+oldFileName+"&newFile="+newFileName+"&path="+path;
	//alert (url+query)
	loadXml(url, params);
	return true;
}
//------------------ get the file size ------------------------
function fileSize(processFile)
{
	// check that file exists 
	var filesize = '';
	var params = '?file='+processFile;
	ajaxRequest = loadXml(applicationBase+njsResourceDir+'FileSize.php', params, false);
	filesize = ajaxRequest.responseText;
	//alert('file size = '+filesize);
	return filesize;
}
// ----------- general routine to rename a file ------------
function renameFileText (oldFileName, newFileName, path)
{
	//alert (newFileName+" >> "+oldFileName)
	var url  = applicationBase+njsResourceDir+"renameFile.php";
	var params="?oldFile="+oldFileName+"&newFile="+newFileName+"&path="+path;
	//alert (url+query)
	ajaxRequest = loadXml(url, params, false);
	fileRenamed = ajaxRequest.responseText;
	if (fileRenamed == 'true') {return true;}
	else {return false;}
}
// ----------- CF routine to replace a file with another ----------
function replaceFileCF(source, destination)
{
	// note must have "/inc/" as preceding part of file
	var url  = applicationBase+"cf/replacefile.cfm";
	var params="?source="+source+"&destination="+destination;
	//alert(">> "+url+params)
	ajaxRequest = loadXml(url, params, false);
	if(ajaxRequest.status == 200)
	{
		var status = ajaxRequest.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
		//alert("replacefile.cfm return = "+status)
		if(status == 'false'){ return false;} else {return true;}
	}
	else{return false;}
}






//------------------ check if a file is present on server disk via text file ------------------------
function filePresent(processFile)
{
	// check that file exists 
	var filePres = 'false';
	var params = '?file='+processFile;
	ajaxRequest = loadXml(applicationBase+njsResourceDir+'FileExistsText.php',params, false);
	filePres = ajaxRequest.responseText;
	if (filePres == 'true') {return true;}
	else {return false;}
}

//------------------ check if a file is present on server disk via XML (not working) ------------------------
function filePresentXML(processFile)
{
	// check that file exists
	var filePresent = 'false';
	var params = '?file='+processFile;
	ajaxRequest = loadXml(applicationBase+njsResourceDir+'FileExists.php',params, false);
	var files = ajaxRequest.responseXML.getElementsByTagName('Files');
	filePresent = files[0].getElementsByTagName('File')[0].firstChild.nodeValue;
	if (filePresent == 'true') {return true;}
	else {return false;}
}
//--------------------- get a list of files from the server ----------------------
function getFolderList(collPath, collExts)
{
	// set up for folder scan
	var filesList = "data/list"+new Date().getTime()+".xml";  // temporary file to hold the list
	var relPath = collPath.split(applicationBase);
	//alert(relPath)
	var query="?path=/"+relPath[1]+"&ext="+collExts+"&file="+filesList;
	//alert(query)
	var getFilesUrl = applicationBase+njsResourceDir+"getfile_list.php"; 	
	
	//create a new filesList.xml file on server (directory Listing)
	if(!makeXml(getFilesUrl, query, false)) {alert ('Unable to make the XML file on the server'); return false;}
	
	// load the XML into the application DOM
	var query='';
	var filesLists = +njsResourceDir+filesList;
	ajaxRequest = loadXml(filesLists, query, false)
	if(!ajaxRequest.responseXML.getElementsByTagName("files")) { alert ('Unable to return the XML file from the server'); return false;}
	
	// delete the temporary XML file listing on server
	deleteit(filesList)
	return true;
}

//------------ checks that a number is even ---------------//
function evenCheck (numb)
{
	var intNo = parseInt(numb)
	var rem = intNo/2
	var diff =  Math.ceil(rem) - Math.floor(rem) 
	if (diff == 0)
	{ return true	}
	else { return false	}
}

//----------- checks if a value is numeric ---------------//
function checkNumeric(value)
	{		
		//alert(value)
		var anum=/(^\d+$)|(^\d+\.\d+$)/		
		if (anum.test(value))			return true;		return false;  
	}

//--------------Find a centroid of a polygon array ---------------------//
function findCentroid(vertices, area) 
{
	// this actual calculates the center of mass.
	var cx = 0;
	var cy = 0;
	var i, j, n = vertices.length;
	var factor = 0;
	 if (vertices[0].y == vertices[vertices.length - 1].y &&  vertices[0].x == vertices[vertices.length - 1].x) 
	{
       // do nothing.
	}
	 else 
	{
      // We must close the polygon by adding the first vertices to
      // also be the last.
      vertices[vertices.length] = vertices[0];
	}
	
	// accumulate the geometry values
	for (i=0; i<n; i++) 
	{
      j = (i + 1) % n;
      factor = (vertices[i].y * vertices[j].x - vertices[j].y * vertices[i].x);           
      cx += (vertices[i].y + vertices[j].y) * factor;
      cy += (vertices[i].x + vertices[j].x) * factor;
	}
	area *= 6;
	factor = 1 / area;
	cx *= factor;
	cy *= factor;
 
	if (cx < 0) 
	{	return new OpenLayers.LonLat(-cy, -cx);}
	else 
	{	return new OpenLayers.LonLat(cy, cx);}
}

//-------------------- Replaces all instances of the given substring --------------------
// useage: sqlExp[i] = sqlExp[i].replaceAll( what, with_what )

String.prototype.replaceAll = function(	strTarget, 	strSubString )
{
	//alert(strTarget+" >> "+strSubString)
	var strText = this.toString();
	//alert(strText)
	strTarget = strTarget.toString();
	strSubString = strSubString.toString();
	
	var intIndexOfMatch = strText.indexOf( strTarget );
	//alert(intIndexOfMatch)
	
	// Keep looping while an instance of the target string still exists in the string.
	while (intIndexOfMatch != -1)
	{
		
		// Relace out the current instance.
		strText = strText.replace( strTarget, strSubString )
	 
		// Get the location of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
		alert(intIndexOfMatch)
	}
	 
	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}

// function to check for a CR to complete a data entry field
function checkEnter(e,id)
{
	var characterCode
	if(e && e.which)
	{
		e = e;
		characterCode = e.which
	}
	else
	{
		e = e;
		characterCode = e.keyCode
	}
	// on carriage return trigger action
	if(characterCode == 13)
	{
		document.getElementById('search').value = document.getElementById(id).value;
		lastAccuracy = -1;
		showAddress(country, 'geocoder', id, 'selector', 'selForm', 'whiteSunkenBox', 'messHolder', srs); 

	}
	
}
// function to check for a CR to complete a data entry field
function checkEnterAddress(e, newAddr)
{
	var characterCode
	if(e && e.which)
	{
		e = e;
		characterCode = e.which
	}
	else
	{
		e = e;
		characterCode = e.keyCode
	}
	// on carriage return trigger action
	if(characterCode == 13)
	{
		//alert('new addr = '+newAddr)
		// geocode the new address
		geocoder.getLocations(newAddr, function (result)
		{ 
			// Only one in collection so plot it only
			var p = result.Placemark[0].Point.coordinates;
			var currentAccuracy = result.Placemark[0].AddressDetails.Accuracy;
			if(currentAccuracy >= 4)
			{// transform geogs to google if required
				if (srs == 'EPSG:900913') 
				{	
					var point = geogs2google(p);
					p = decodePoint (point);
					baseCoords[0] = p[0];
					baseCoords[1] = p[1];
				}
				else
				{	baseCoords[0] = p[0];
					baseCoords[1] = p[1];
				}
				alert(baseCoords)
				// create the vector marker for the territory Home location
				makeHomeMarker(true);
			}
			else{alert ('unable to geocode this new address - try again');}
			
		});
	}
	//showAddress(country, 'geocoder', id, 'selector', 'selForm', 'selBox', 'messHolder', srs); 
}
function checkEnterKeyword(e, keyword)
{
	//alert(keyword)
	var characterCode
	if(e && e.which)
	{	e = e
		characterCode = e.which
	}
	else
	{	e = event
		characterCode = e.keyCode
	}	 
	if(characterCode == 13)
	{
		//alert('about to find it')
		findIt(keyword,  "searchResults", "ddSearchEngine");
		//alert('done')
		return false
	}else { return true}
}
// function to check for a CR to complete a data entry field


// ------------ This will build a progress bar inside 'barId' to a percent 'complete' ---------------//
function progressBar(barId, message, complete)
{
	
	//alert(complete)
		var progressBarHolder = document.getElementById(barId);
	if(message == '')
	{	
		checkRemoveObject('indicatorText') ; 
		progressBarHolder.style.backgroundColor ='transparent';
		return;
	}
	
	// set up a text tag if first time and update as you go
	if(complete != '') {var newText = message+" "+complete+"%";}
	else {var newText = message;}
		
	// create a new Div and add new text
	//checkRemoveObject('indicText');
	checkRemoveObject('indicatorText') ;
	var progBar = document.createElement('div');
	progBar.id = 'indicatorText';
	progBar.setAttribute("id", 'indicatorText');
	var textNode = document.createTextNode(newText);	
		
	// position the text Div node inside progressBarHolder
	progBar.style.position='absolute';
	progBar.style.top='2px';
	progBar.style.left='6px';
	progBar.style.height='12px';
	progBar.style.width='90px';
	progBar.style.textAlign='center';
	progBar.style.backgroundColor='transparent';
	progBar.style.zIndex='1000';
	progBar.style.fontSize='10px';
	//progBar.style.border='1px solid red';
	progBar.appendChild(textNode);
	progressBarHolder.appendChild(progBar);
	progressBarHolder.style.textAlign='center';
	
	if(complete == ''){complete=100;}
	// update the file progress bar with complete which should be a % integer
	progressBarHolder.style.width = complete+'%';
	progressBarHolder.style.backgroundColor = '#FFFFD4';
	progressBarHolder.style.display = 'block';
	
}
// ------------------ function to check if object exists and if so remove it --------------------
function checkRemoveObject(oId)
{
	if (document.getElementById(oId))
	{	
		var obj = document.getElementById(oId);
		obj.parentNode.removeChild(obj);
		obj.value=null;
		return true;
	}
	return false;
}
	 
// ------------ This will build a vertical record pointer bar inside 'barId' to a percent 'complete' ---------------//
function recordNumber (barId, currPointer, totalNumber)
{
	
	// set up a text tag if first time and update as you go
	var progressBarHolder = document.getElementById(barId);
	var newText = 'Record Num '+currPointer;
	var complete = Math.ceil(parseInt(currPointer)/parseInt(totalNumber)*100);
	
		// create a new Div and add new text
		//checkRemoveObject('indicatorText') ;
		checkRemoveObject('indicText');
		var progressBar = document.createElement('div');
		progressBar.id = 'indicText';
		progressBar.setAttribute("id", 'indicText');
		var textNode = document.createTextNode(newText);	
			
		// position the text Div node inside progressBarHolder
		progressBar.style.position='absolute';
		progressBar.style.top='2px';
		//progressBar.style.left='6px';
		progressBar.style.height='12px';
		progressBar.style.width='90px';
		if(barId == 'progBar2'){progressBar.style.width='190px';}
		progressBar.style.backgroundColor='transparent';
		progressBar.style.zIndex='1000';
		progressBar.style.fontSize='10px';
		//progressBar.style.border='1px solid red';
		progressBar.appendChild(textNode);
		progressBarHolder.appendChild(progressBar);
		progressBarHolder.style.textAlign='center';
	
	// update the file progress bar with complete which should be a % integer
	
	progressBarHolder.style.width = complete+'%';
	progressBarHolder.style.maxWidth='93px';
	if(barId == 'progBar2'){progressBarHolder.style.maxWidth='196px';}
	//progressBarHolder.style.paddingRight='2px';
	progressBarHolder.style.backgroundColor = '#ECE9D8';
	progressBarHolder.style.borderRight = '2px solid gray';
	progressBarHolder.style.display = 'block';
}
// ------------- date stamp -----------
function getStamp()
{
	stamp = new Date().getTime();
	return stamp;
}

// ----------------- create a readout of the percentage on the slider bar ---------------------------
function showPercent(sliderPosition)
{
	var pos = document.getElementById('position');
	checkRemoveObject('posBox');
	var text = Math.round( 100 * sliderPosition ) ;
	var posBox = document.createElement('div')
	posBox.id='posBox';
	posBox.setAttribute('id','posBox');
	var postext=document.createTextNode(text)
	posBox.appendChild(postext);
	pos.appendChild(posBox)
}
// ----------------- mouse slider function --------------------
function moveFunction(sliderPosition) 
{
	// keep the slider bar iwth the mouse
	myslider.setPosition(sliderPosition);
	
	// echo the percentage position in a div - optional
	//showPercent(sliderPosition);
	if(DemoDrape)
	{
		// set the new opacity for the layer
		newOpacity = (parseFloat(sliderPosition)).toFixed(1);
		newOpacity = Math.min(maxOpacity, Math.max(minOpacity, newOpacity));
		DemoDrape.setOpacity(newOpacity);
	}
}
// ----------------- this fixes it after the mouse has stopped -------------------
function stopFunction(sliderPosition) 
{
	//do something with the position of the slider
	myslider.setPosition(sliderPosition);
		
	//all done, save last known position for purposes of disabling
	lastKnownPosition = sliderPosition;
	
	//Now apply the new opacity to the active legend
	//alert ('newOpacity= '+newOpacity)
	if (DemoDrape){legendBuilder("mapSurround", sldUrl, newOpacity, dvbdy1, dvhdr1);}
	//buildLegend (sldUrl, legendBackground, legend, legendTitle, legendTable, legendBox, legendText, tdCell, newOpacity, dvbdy1, dvhdr1);
	//window.alert( 'The final position is ' + Math.round( 100 * sliderPosition ) + '%' );
}
// ----------------- Main slider function to be included in HTML where needed -----------------
function displayDrapeSlider(top, left, horiz, sliderBack)
{
	if(!horiz || horiz == null)
	{	// vertical slider
		var trkHt = 108;
		var trkWd = 19;
		var butHt = 5;
		var butWd = 17;
	}
	else
	{	// horizontal slider
		var trkHt = 19;
		var trkWd = 108;
		var butHt = 17;
		var butWd = 5;
	}
		
	// style controls of slider
	myslider = new slider(
		trkHt,				//height of track
		trkWd,				//width of track
		'transparent',		//colour of track
		0,					//thickness of track border
		'transparent',		//colour of track border
		0,					//thickness of runner (in the middle of the track)
		'#000000',			//colour of runner
		butHt,				//height of button
		butWd,				//width of button
		'#999999',			//colour of button
		1,					//thickness of button border (shaded to give 3D effect)
		'<span id=\"position\" style=\"font-size:8px; \" ><\/span>', //text of button (if any)
		horiz,				//direction of travel (true = horizontal, false = vertical)
		'moveFunction',		//the name of the function to execute as the slider moves
		'stopFunction',		//the name of the function to execute when the slider stops
							//the functions must have already been defined (or use null for none)
		true,				 //optional, false = use default cursor over button, true = use hand cursor
		sliderBack			// the src of the background Image to be used for slider
	);
		
	// Initialise slider
	alert(opacityValue)
	lastKnownPosition=0.0;
	if (opacityValue != null){	lastKnownPosition = opacityValue;}
	myslider.setPosition(lastKnownPosition);
	//showPercent(lastKnownPosition);
	//document.write('</div>');
}
// ----------------- mouse slider function --------------------
function moveTerritoryFunction(sliderPosition2) 
{
	// keep the slider bar iwth the mouse
	terrSlider.setPosition(sliderPosition2);
	
	// echo the percentage position in a div - optional
	if(territory)
	{
		// set the new opacity for the layer
		newOpacity2 = (parseFloat(sliderPosition2)).toFixed(1);
		newOpacity2 = Math.min(maxOpacity, Math.max(minOpacity, newOpacity2));
		territory.setOpacity(newOpacity2);
	}
}
// ----------------- this fixes it after the mouse has stopped -------------------
function stopTerritoryFunction(sliderPosition2) 
{
	//do something with the position of the slider
	terrSlider.setPosition(sliderPosition2);
		
	//all done, save last known position for purposes of disabling
	lastKnownPosition2 = sliderPosition2;
	//alert(lastKnownPosition2)
}
// ----------------- Main slider function to be included in HTML where needed -----------------
function displayTerritorySlider(top, left, horiz, sliderBack)
{
	if(!horiz || horiz == null)
	{	// vertical slider
		var trkHt = 108;
		var trkWd = 19;
		var butHt = 5;
		var butWd = 17;
	}
	else
	{	// horizontal slider
		var trkHt = 19;
		var trkWd = 108;
		var butHt = 17;
		var butWd = 5;
	}
		
	// style controls of slider
	terrSlider = new slider(
		trkHt,				//height of track
		trkWd,				//width of track
		'transparent',		//colour of track
		0,					//thickness of track border
		'transparent',		//colour of track border
		0,					//thickness of runner (in the middle of the track)
		'#000000',			//colour of runner
		butHt,				//height of button
		butWd,				//width of button
		'#999999',			//colour of button
		1,					//thickness of button border (shaded to give 3D effect)
		'<span id=\"position\" style=\"font-size:8px; \" ><\/span>', //text of button (if any)
		horiz,				//direction of travel (true = horizontal, false = vertical)
		'moveTerritoryFunction',		//the name of the function to execute as the slider moves
		'stopTerritoryFunction',		//the name of the function to execute when the slider stops
							//the functions must have already been defined (or use null for none)
		true,				 //optional, false = use default cursor over button, true = use hand cursor
		sliderBack			// the src of the background Image to be used for slider
	);
		
	// Initialise slider
	//alert('opacity = '+opacityValue2)
	lastKnownPosition2 = 0.0;
	if (opacityValue2 != null){	lastKnownPosition2 = opacityValue2;}
	terrSlider.setPosition(lastKnownPosition2);
	//showPercent(lastKnownPosition);
	//document.write('</div>');
}




// function to get cookie value from cookie name
function getCookies(searchName)
{
	var cookies = document.cookie.split(";")
	for (var i=0; i < cookies.lenght; i++);
	{
		var cookieCrumbs = cookies[i].split("=");
		var cookieName = cookieCrumbs[0];
		var cookieValue = cookieCrumbs[1];
		if (cookieName == searchName)
		{
			return cookieValue;		// I assume = true/false?
		}
	}
	return false;
}

/*function camelCaps(str, firstCap) 
{
	str.toString();
	var newStr = '';

	// Make the first character of each word upper- or lowercase
	// depending on the value of firstCap
 	if (firstCap) 
	{
		str.toLowerCase();
		for (var i=0; i<str.length; i++)
		{
			if(i == 0){newStr=str[i].toUpperCase();}
			else{newStr += str[i];}
		}
		//alert('new Str = '+newStr)
    }
    else 
	{
		str.toUpperrCase();
		for (var i=0; i<str.length; i++)
		{
			if(i == 0){newStr=str[i].toLowerCase();}
			else{newStr += str[i];}
		}
		//alert('new Str = '+newStr)
    }
	return newStr;
 */

function getThisId(evt)
{
	// cross browser tool to determine objects ID from an event trigger
	var e_out;
	var ie_var = "srcElement";
	var moz_var = "target";
	var prop_id = "id";
	// "target" for Mozilla, Netscape, Firefox et al. ; "srcElement" for IE
	evt[moz_var] ? e_out = evt[moz_var][prop_id] : e_out = evt[ie_var][prop_id];
	return e_out;
}
// random colour generator
function random_color(format)
{
	// format = 'hex' or 'rgb'
	var rint = Math.round(0xffffff * Math.random());
	switch(format)
	{
		case 'hex':
		return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
		break;

		case 'rgb':
		return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
		break;

		default:
		return rint;
		break;
	}
}
function boundaryRequired()
{
	// first get the selected target polygon
	var pLayers='NONE';
	if(document.getElementById('polyLayers') )
	{
		var selectObject = document.getElementById('polyLayers');
		pLayers = selectObject.options[selectObject.selectedIndex].value;
	}
	return pLayers;
}

function textDisplay(targetId, text)
{
	if(targetId)
	{
		// generic function to stuff a text string (text) into the target Object defined by its ID (targetId)
		var drapeWindow = document.getElementById(targetId);
		checkRemoveObject('spanit');
		var span = document.createElement('span');
		span.id='spanit'; span.setAttribute('id','spanit');
		span.style.fontSize='10px';
		span.style.paddingLeft='3px';
		var textObj = document.createTextNode(text);
		span.appendChild(textObj);
		drapeWindow.appendChild(span);
		drapeWindow.value = text;
	}
}
function getListOfFiles(folder)
{
	// get list of files from the target folder
	var query="?path="+njsResourceDir+folder+"&time="+new Date().getTime(); // added the time stamp because IE caches this request
	var getFilesUrl = applicationBase+njsResourceDir+"getXmlFiles.php"; 	
	ajaxRequest = loadXml(getFilesUrl, query, false);
	if(ajaxRequest.status !== 200){return 'error';}
	else {return ajaxRequest;}
}
// function to convert an input string so that the first lette of each word is a capital and all others are lowercase
function capitaliseIt(string)
{
	var nameParts = string.split(" ");
	if(nameParts.length > 1)
	{
		for (var i = 0; i<nameParts.length; i++)
		{
			if(i==0){var newName = stCap(nameParts[i]);}
			else { newName = newName+" "+stCap(nameParts[i]);}
		}
	}
	else
	{	var newName = stCap(nameParts[0]);	}
	return newName;
}

function stCap(strObj)
{	return(strObj.charAt(0).toUpperCase()+strObj.substr(1).toLowerCase());	}

function getCentreBbox(polyBounds)
{
	if(polyBounds)
	{
		var bboxVals = polyBounds.toBBOX(); 
		var bboxVals = bboxVals.split(",");
		var centX = (parseFloat(bboxVals[0]) + parseFloat(bboxVals[2]))/2;
		var centY = (parseFloat(bboxVals[1]) + parseFloat(bboxVals[3]))/2;
		return centX+","+centY;
	}
	else
	{
		return 'error';
	}
}
function bringToTop(layerObject)
{
	if(layerObject != null)			
	{
		//alert('bringToTop zindex in = '+layerObject.getZIndex());
		layerObject.setZIndex(map.Z_INDEX_BASE['Popup']+10); 
		//alert('bringToTop zindex out = '+layerObject.getZIndex());
		layerObject.redraw();
	}
}
function getBboxOfView(zoom, srs)
{
	// if the user wants to see only for window then generate the smaller oxBox bounds
	var ozBoxGeog = [104.94141,  -44.96480,  180.0,  0.0] ;
	var pnt=[];
	if(!zoom) 
	{
		// get the bounds of the map window
		if (srs == "EPSG:900913")
		{
			// convert first point
			pnt[0] = map.getExtent().left;
			pnt[1] = map.getExtent().bottom;
			var point = google2geogs(pnt);
			loLeft = decodePoint(point);
			point1X = roundNumber(loLeft[0],8);
			point1Y = roundNumber(loLeft[1],8);

			// convert second point
			pnt[0] = map.getExtent().right;
			pnt[1] = map.getExtent().top;
			var point = google2geogs(pnt);
			hiRight = decodePoint(point);
			point2X = roundNumber(hiRight[0],8);
			point2Y = roundNumber(hiRight[1],8);

			// create a new ozBoxGeo
			ozBoxGeog = [point1X, point1Y, point2X, point2Y]
		}
		else
		{
			// create the geographicals version of the ozBoxGeo bound
			ozBoxGeog = [map.getExtent().left, map.getExtent().bottom, map.getExtent().right, map.getExtent().top]; 
		}
	}
	return ozBoxGeog;
}
// -------------- button control functions ----------------------
function buttonHandler(buttonId, functionName, titleText, imageName, sticky, visible)
{
	// this will create a button within the parent object
	// inputs:
	// buttonId = unique ID of the button being created
	// functionName = the onclick function that is to be launched
	// titleText = the title for the button shown as a tool tip
	// imageName = the image that is displaye at the top of the button 19px x 18px
	// sticky = logical flag set to true if this button sticks down & releases on a subsequent click
	// visible = this initiates the visible state of the original button
		
	// set the appropriate flags
	var onmouseup = '';
	if(!sticky){onmouseup = "onmouseUp=mouseup('"+buttonId+"');"}
	var display = 'display:none;';
	if(visible) {display = 'display:block;';}
		
	// create the button
	document.write("<div id='"+buttonId+"'  style='height:18px; width:20px; border-right:1px solid gray; border-bottom:1px solid gray; border-top:1px solid #c3c3c3;	border-left:1px solid #c3c3c3;	color:gray;	cursor:pointer;	background-color:transparent; z-index:5000; "+display+"' onclick='"+functionName+"' title='"+titleText+"' onmouseDown=mousedown('"+buttonId+"');  " +onmouseup+" >"	);
	document.write("<img  src='"+imageName+"' style='cursor:pointer; vertical-align:middle;' />");
	document.write("</div>");
}

function mouseup(buttonId)
{
	//alert('mouseup = '+buttonId)
	document.getElementById(buttonId).style.backgroundColor='#C3C3C3';
	normalDiv(buttonId);
}
function mousedown(buttonId)
{
	//alert('mousedown = '+buttonId)
	document.getElementById(buttonId).style.backgroundColor='white';
	depressedDiv(buttonId);
}
function highlightDiv(id)
{
	document.getElementById(id).style.borderLeft="1px solid gray";
	document.getElementById(id).style.borderTop="1px solid gray";
	document.getElementById(id).style.borderBottom="1px solid #c3c3c3";
	document.getElementById(id).style.borderRight="1px solid #c3c3c3";	
}
function normalDiv(id)
{
	//document.getElementById(id).style.border="1px solid #ECE9D8";
	document.getElementById(id).style.borderRight="1px solid gray";
	document.getElementById(id).style.borderBottom="1px solid gray";
	document.getElementById(id).style.borderTop="1px solid #c3c3c3";
	document.getElementById(id).style.borderLeft="1px solid #c3c3c3";	
	document.getElementById(id).style.backgroundColor="#C3C3C3";
	document.getElementById(id).style.color='black';
}

function depressedDiv(id)
{
	document.getElementById(id).style.borderLeft="1px solid gray";
	document.getElementById(id).style.borderTop="1px solid gray";
	document.getElementById(id).style.borderBottom="1px solid #c3c3c3";
	document.getElementById(id).style.borderRight="1px solid #c3c3c3";	
	document.getElementById(id).style.backgroundColor="white";
	document.getElementById(id).style.color='black';
}

function separator(left,top, length, orientation)
{		
		var width = length; var height = '0px'; var borders = "border-bottom:1px solid white; border-top:1px solid gray;"
		if(orientation == 'vertical') {width = '0px'; height = length; borders = 'border-left:1px solid gray; border-right:1px solid white;'  }
		document.write("<div style='position:absolute; 	left:"+left+"; top:"+top+";	width:"+width+"; height:"+height+";	"+borders+"' ></div>");
}

function panelButton(left, top, id, title, functionName, label)
{
	document.write("<div id='"+id+"' class='standardButton'	style='position:absolute; top:"+top+";	left:"+left+";'	title='"+title+"' onclick='if(loaded){"+functionName+"}'>"+label+"</div>");
}

function alphabetButtons(id, title, functionName, label)
{	 
	document.write("<div style='width:20px' class='lettersNormal' id="+id+" title="+title+" onclick='"+functionName+"' onmousedown='this.className=\"lettersDepressed\";' onmouseup='this.className=\"lettersNormal\";' onmouseover='this.className=\"lettersHighlight\";' onmouseout='this.className=\"lettersNormal\";'>"+label+"</div>");
}
function toggleSearch(id)
{
	searchOriginator = id;
	var searchButt = document.getElementById(id);
	if(searchButt.title == 'Launch search panel')
	{
	
		document.getElementById("searchHolder").style.display="block";
		document.getElementById("keyword").focus();
		searchButt.title = 'Close search panel';
		highlightDiv(id);
	}
	else
	{
		document.getElementById("searchHolder").style.display="none";
		searchButt.title = 'Launch search panel';
		normalDiv(id);
	}
}
//------------- this will load data into the metadata div ----------------//
function showData(name,  abstractData)
{
	MochaUI.notification(abstractData);
	new Event(evt).stop();
}
function hideData()
{
	document.getElementById('metaHolder').style.display='none';
}
function registerLoadWheel(layer,  wheelId)
{
	//alert(layer.name)
	layer.events.register("loadstart",  layer,  function() 
	{
		$('spinner').setStyle('visibility','visible');
		//if(document.getElementById(wheelId)){document.getElementById(wheelId).style.display='block';  }
		//document.getElementById('eventsLogID').style.display='block'; 
	});
	layer.events.register("loadend",  layer,  function() 
	{
		$('spinner').setStyle('visibility','hidden');
		//if(document.getElementById(wheelId)){document.getElementById(wheelId).style.display='none';  }
		//document.getElementById('eventsLogID').style.display='none';  
	});
}
function resetZlevels()
{

	if(markers)			{markers.setZIndex(map.Z_INDEX_BASE['Popup'] -1000);}
	if(vectorLayer)		{vectorLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);}
	if(vectorLayer2)	{vectorLayer2.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);}
	if(vectorLayer3)	{vectorLayer3.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);}

	if(userMarkers)		{userMarkers.setZIndex(map.Z_INDEX_BASE['Popup'] -4000); }
	//alert(terrMarkers)
	if(terrMarkers)		{terrMarkers.setZIndex(map.Z_INDEX_BASE['Popup'] -4000);}

	//if(vectorLayer4)	{vectorLayer4.setZIndex(map.Z_INDEX_BASE['Popup'] -4010);}

	if(terrLabels)		{terrLabels.setZIndex(map.Z_INDEX_BASE['Popup'] -4010);}
	if(boundary)		{boundary.setZIndex(map.Z_INDEX_BASE['Popup'] -4050);}
	if(innerBoundaries)	{innerBoundaries.setZIndex(map.Z_INDEX_BASE['Popup'] -4050);}
	if(territory)		{territory.setZIndex(map.Z_INDEX_BASE['Popup'] -4100);}
	if(CouncilsMask)	{CouncilsMask.setZIndex(map.Z_INDEX_BASE['Popup'] -4200);}
	if(allTerritoriesLayer)	{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] ) {LabelObj[i].setZIndex(map.Z_INDEX_BASE['Popup'] -zindex);}
			var zindex = 6000 + parseInt(i);
			if(LayerObj[i] ) {LayerObj[i].setZIndex(map.Z_INDEX_BASE['Popup'] -zindex);}
			
		}
	}

	if(DrapeHighlight )	{DrapeHighlight.setZIndex(map.Z_INDEX_BASE['Popup'] -8800);}
	if(DemoDrape )		{DemoDrape.setZIndex(map.Z_INDEX_BASE['Popup'] -9000);}
	if(collectLayer )		{collectLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -9000);}
}	
