function populateAreasIncluded(array)
{
	// load up list of areas into form display
	//alert(array)
	if(array.length == 0){ return;}
	checkRemoveObject('tableOfAreas');
	var tableBody = document.createElement('tbody');
	tableBody.id='tableOfAreas'; tableBody.setAttribute('id','tableOfAreas');
	for(var i=0; i<array.length ; i++)
	{
		var row = document.createElement("tr");
			row.style.height='15px';

			// add polygon count cell
			var countCell = document.createElement('td');
			countCell.style.width='10%';
			countCell.style.height='15px';
			
			countCell.className='unselectedItem'; 
			
			countCell.style.textAlign='center';
			countCell.id='count:'+i; 
			countCell.setAttribute('id','count:'+i);
			var text = document.createTextNode(i+1);
			countCell.appendChild(text);
			row.appendChild(countCell);

			// add delete me cell
			var delCell = document.createElement('td');
			delCell.style.width='10%';
			delCell.style.height='15px';
			
			delCell.className='unselectedItem'; 
			
			delCell.id='kill:'+i; 
			delCell.setAttribute('id','kill:'+i);
				
				// add the deleteme image
				var delImg = document.createElement('img');
				delImg.src='images/deleteme.gif';
				delImg.style.height='100%';
				delImg.style.width='100%';
				delImg.style.cursor='pointer';
				delImg.id='delimg:'+i; 
				delImg.setAttribute('id','delimg:'+i);
				delImg.title='click here to remove this area from Territory '+array[i];
				bindEvent(delImg, 'click', removeThisArea, 'false');
				delCell.appendChild(delImg);
			row.appendChild(delCell);

			// add the polygon name cell
			var nameCell = document.createElement('td');
			nameCell.style.width='70%';
			nameCell.style.height='15px';
			
			nameCell.className='unselectedItem'; 
			
			nameCell.id='name:'+i; 
			nameCell.setAttribute('id','name:'+i);
			var text = document.createTextNode(array[i]);
			nameCell.appendChild(text);
			row.appendChild(nameCell)
			//nameCell.style.cursor='pointer';
			//nameCell.title='click here to center over area called '+array[i];
			//bindEvent(nameCell, 'click', goToAreaByBbox, 'false')
			
			// add zoom to cell
			var zoomCell = document.createElement('td');
			zoomCell.style.width='10%';
			zoomCell.style.height='15px';
			
			zoomCell.className='unselectedItem'; 
			
			zoomCell.id='zoom:'+i; 
			zoomCell.setAttribute('id','zoom:'+i);
				
				// add the zoomto image
				var zoomImg = document.createElement('img');
				zoomImg.src='images/zoomTo.gif';
				zoomImg.style.height='100%';
				zoomImg.style.width='100%';
				zoomImg.style.cursor='pointer';
				zoomImg.id='zmimg:'+i; 
				zoomImg.setAttribute('id','zmimg:'+i);
				zoomImg.title='click here to center over area called '+array[i];
				bindEvent(zoomImg, 'click', goToAreaByBbox, 'false');
				zoomCell.appendChild(zoomImg);
			row.appendChild(zoomCell);		
		tableBody.appendChild(row);
	}
	document.getElementById('areasTable').appendChild(tableBody);
}

// this is called in initialising function 
function prepareTerritorySearch()
{
	searchTarget = [];
	infoTarget = [];
	
	// get a list of Territory files
	//alert('territoryFolder = '+territoryFolder)
	ajaxRequest = getListOfFiles(territoryFolder);
	if(ajaxRequest == 'error')
	{ 
		// switch the buttons and form to the Input screen
		changeMode('newTerr');
		//document.getElementById('listTerr').style.display='none';
		document.getElementById('openTerr').style.display='none';
		return false;
	}
	// pick off search metadata for all xml files in list
	//alert(ajaxRequest.responseText)
	var xmlFiles = ajaxRequest.responseText.split("|");
	if(xmlFiles.length > 0)
	{
		for (var j=0; j<xmlFiles.length; j++)
		{
			// get the name of the territory from xml file
			var file = applicationBase+"inc/"+territoryFolder+xmlFiles[j];
			var query="?"+new Date().getTime();
			ajaxRequest = loadXml(file, query, false)
			if (!ajaxRequest.responseXML) 
			{
				// switch the buttons and form to the Input screen
				changeMode('newTerr');
				//document.getElementById('listTerr').style.display='none';
				document.getElementById('openTerr').style.display='none';
				return false; 
			}
			// pick off the attributes needed
			var territoryObj = ajaxRequest.responseXML.getElementsByTagName("Territory");

			if(territoryObj.length > 0)
			{
				territoryName = territoryObj[0].getAttribute('territoryName');
				territoryCode = territoryObj[0].getAttribute('territoryCode');
				territoryAbstract = territoryObj[0].getAttribute('territoryAbstract');
				dataLayer = territoryObj[0].getAttribute('dataLayer');
				territoryContact = territoryObj[0].getAttribute('territoryContact');
			
				// concatinate into a searchable string
				var searchString = 	territoryName+" :: "+territoryCode+" :: "+territoryAbstract+" :: "+dataLayer+" :: "+xmlFiles[j]+" :: "+territoryContact;
				searchTarget[j] = searchString.toString(); 
				infoTarget[j] = searchTarget[j];
			}
		}
		noOfTerr = searchTarget.length
		return true;
	}
	else
	{
		// switch the buttons and form to the Input screen
		changeMode('newTerr');
		//document.getElementById('listTerr').style.display='none';
		document.getElementById('openTerr').style.display='none';
		return false;
	}
}

function setTerritoryMenu()
{
	//alert ('number of territories = '+noOfTerr)
	var terrItem = -1;
	for (var i=0; i<searchTarget.length; i++)
	{
		// first get the name of each row
		var terrName = document.getElementById('terr_name:'+i).value
		if(terrName == territoryName) {terrItem = i;}
		
		// reset to each row to unselected
		document.getElementById('terr_op:'+i).className = 'unselectedItem';
		document.getElementById('terr_kill:'+i).className = 'unselectedItem';
		document.getElementById('terr_name:'+i).className = 'unselectedItem';
	}
	// highlight the actual row
	if(terrItem >= 0)
	{
		document.getElementById('terr_op:'+terrItem).className = 'selectedItem';
		document.getElementById('terr_op:'+terrItem).style.borderLeft ='1px solid gray';
		document.getElementById('terr_kill:'+terrItem).className = 'selectedItem';
		document.getElementById('terr_name:'+terrItem).className = 'selectedItem';
	}
	// now make sure the mobe base and labels buttons are active
	if(allTerritories || territoryName != '')
	{
		//toggleHome('homeTerr');
		document.getElementById('homeTerr').style.display = 'block';
		//toggleLabels('labelTerr');
		document.getElementById('labelTerr').style.display = 'block';
	}
}



// -------------- this will plot all user uploaded data as markers ----------------
function showTerritory(xmlFile)
{
	genLoadStatus('Fetching Territory ...', true, '');

	// get the territory defined by its xmlFile
	//alert(xmlFile)
	if(!getTheTerritory(xmlFile)) {return;}	
	var terrLay = territoryDataLayer.split(':')[0];
	//alert('1')
	// search the drop down list for this layer 
	for (var i=0; i<Name.length; i++ )
	{
		var layNameShort = Name[i].split(":")[0];// strip off :ABS
		//alert(layNameShort+"  ++  "+terrLay)
		if(layNameShort == terrLay)
		{
			// set the drop down to this layer
		 	var optionNumb = i+1;
			//alert(optionNumb)
			document.getElementById('actLayOptions').options[optionNumb].selected=true;
			document.getElementById('actLayOptions').disabled=true;
			break;
		}
	}
	// make sure the selected Territory is now set on select menu
	//alert('territory Name 1 = '+territoryName)
	setTerritoryMenu();
//alert('2')

	// clear out any report
	document.getElementById('territoriesReportHolder').style.display='none';
	document.getElementById('reportTerr').title = 'Show Report';
	mouseup('reportTerr');

	// Make sure vector layer & innerboundaries layer is removed from map
	//if(vectorLayer4)	{alert('turn off'); vectorLayer4.setVisibility(false);}

	if(innerBoundaries) {innerBoundaries.setVisibility(false); }
	if(terrMarkers)		{terrMarkers.setVisibility(false);}
	if(terrLabels)		{terrLabels.setVisibility(false);}
	if(terrPopup != null)
	{	//map.removePopup(terrPopup);
		terrPopup.destroy();
		terrPopup = null;
	}
//alert('3')
	// reset the showhide sticky buttons
	document.getElementById('circlesTerr').title='Show 10Km Radial Distances';
	mouseup('circlesTerr');
	document.getElementById('innerTerr').title='Show Inner Boundaries';
	mouseup('innerTerr');

	// turn on the territories form
	document.getElementById('territoriesForm').style.display='block';

	// now set the territory manager to be in maximum state
	minmaxTerritoryManager('max');
//alert('4')
	// reset the allTerrs checkbox
	//document.getElementById('showAllTerr').checked = false;
	
	// populate the form with existing Territory data
	document.getElementById('nameOfTerritory').value = territoryName;
	document.getElementById('contactOfTerritory').value = territoryContact;
	document.getElementById('addressOfTerritory').value = territoryAddress;
	document.getElementById('dbCodeOfTerritory').value = territoryCode;
	document.getElementById('abstractOfTerritory').value = territoryAbstract;

	// populate the araes name with the list for this Territory
	populateAreasIncluded(territoryNames);
//alert('5')
	// make sure the open specific buttons are visible
	//document.getElementById('listTerr').style.display='block';
	document.getElementById('openTerr').style.display='block';

	// convert territory array into a comma separated string
	//alert('savedSqlString = '+savedSqlString)
	// now highlight the selected Territory
	sqlString = territoryFilter.toString();
	highlightTerritory(sqlString, territoryName);
	// move seleceted file name up into current Territory display window
	textDisplay('selectedTerr', territoryName);
//alert('6')	// set all the buttons to be visible
	//activateTerritoryControls();
	//firstOfGroup 
	genLoadStatus('', false, '');
}

function activateTerritoryControls()
{
	document.getElementById('newTerr').style.display='block';
	document.getElementById('openTerr').style.display='block';
	//document.getElementById('listTerr').style.display='block';	
	
	document.getElementById('removeTerr').style.display='block';
	//document.getElementById('deleteTerr').style.display='block';
	//document.getElementById('grabPoly').style.display='block';
	document.getElementById('saveTerr').style.display='block';
	document.getElementById('zoomToTerr').style.display='block';
	document.getElementById('themeTerr').style.display='block';
	//alert('here' ); territoryActive = true;
}
function deactivateTerritoryControls()
{
/*	document.getElementById('removeTerr').style.display='none';
	document.getElementById('deleteTerr').style.display='none';
	document.getElementById('grabPoly').style.display='none';
	document.getElementById('saveTerr').style.display='none';
	document.getElementById('zoomToTerr').style.display='none';
	document.getElementById('themeTerr').style.display='none';*/
	territoryActive = false;
}


function removeThisArea(evt)
{
	// get the BBox for this option
	var id = getThisId(evt);
	var ptr = id.split(':')[1];

	// this should remove the polygon from the arrays
	var saveAddRemove = addRemove;
	addRemove = true;
	addPolygonToTerritory(territoryFilter[ptr], territoryName[ptr], territoryBboxes[ptr], false)
	addRemove=saveAddRemove;

	// populater the araes name with the list for this Territory
	populateAreasIncluded(territoryNames);

	// convert array to a comma sep string
	sqlString = territoryFilter.toString();
	//alert('sql String = '+sqlString)
	// calculate a new BBox for Territory
	getNewTerrBbox(territoryBboxes);

	// now highlight the selected Territory
	highlightTerritory(sqlString, territoryName);
	genLoadStatus('', false, '');
	Event.stop(evt);
}
function goToAreaByBbox(evt)
{
	// get the BBox for this option
	var id = getThisId(evt);
	var ptr = id.split(':')[1];
	var bbox = territoryBboxes[ptr];
	var pb = bbox.split(':');

	// set the row rendering as per selection
	//alert(allTerritories)
	if(!allTerritories){	setRowToSelected(ptr);}
	//else {setRowToSelected('');}
	
	// jump to this polygon
	areaBounds = new OpenLayers.Bounds(pb[0],pb[1],pb[2],pb[3]);
	map.setCenter(areaBounds.getCenterLonLat(),map.getZoomForExtent(areaBounds));
	map.updateSize();
	Event.stop(evt);
}
function setRowToSelected(ptr)
{

	// set the row to cyan
	for (var i=0; i<territoryBboxes.length; i++)
	{
		// first just make all unselected
		document.getElementById('name:'+i).className='unselectedItem';
		document.getElementById('count:'+i).className='unselectedItem';
		document.getElementById('zoom:'+i).className='unselectedItem';
		document.getElementById('kill:'+i).className='unselectedItem';
		
		// now if this is the selected row, highlight it
		if(i == ptr && ptr >= 0)
		{
			// now set the one the user has selected 
			document.getElementById('name:'+i).className='selectedItem';
			document.getElementById('count:'+i).className='selectedItem';
			document.getElementById('zoom:'+i).className='selectedItem';
			document.getElementById('kill:'+i).className='selectedItem';
		}
	}
}
function zoomToTerritory(thisBounds)
{
	//alert(thisBounds)
	if(!thisBounds) {return;}
	// reset the polygon rows
	if(!allTerritories)	
	{
		//setRowToSelected(-1);
		//alert('territory Name 2= '+territoryName)
		setTerritoryMenu();
	}

	// jump to the territory bounds
	map.setCenter(thisBounds.getCenterLonLat(),map.getZoomForExtent(thisBounds));
	if(territoryActive)
	{	territory.setVisibility(true);
		territory.redraw();
	}

	resetZlevels();
	//alert('territory = '+territory.getZIndex());
	//if(DemoDrape){alert('ddrape = '+DemoDrape.getZIndex());}
	//territory.mergeNewParams({'sld':newSld});
	
	map.updateSize();
}


function editTerritoryTheme()
{
	if(document.getElementById('themeTerr').title == 'enter theme editor mode')
	{
		// reset the color editor from current territory data
		document.getElementById('renderPanel').style.display='block';
		document.getElementById('themeTerr').title = 'exit theme editor mode';
		
		// create the color editor tool
		if(territoryFillColor == ''){territoryFillColor = '00FF00';}
		if(territoryFillOpacity == ''){territoryFillOpacity = 0.2;}
		if(territoryStrokeColor == ''){territoryStrokeColor = 'FF0000';}
		if(territoryStrokeWidth == ''){territoryStrokeWidth = 4;}
		if(territorySolidBorder == ''){territorySolidBorder = false;}
		refreshColorTheme();
	}
	else
	{
		// hide the theme editor
		document.getElementById('renderPanel').style.display='none';
		document.getElementById('themeTerr').title = 'enter theme editor mode';
		mouseup('themeTerr');
	}
}
function refreshColorTheme()
{
	// remove existing render rules div and create a new one
	checkRemoveObject('renderingDiv');
	renderRules = document.createElement('div')
	renderRules.style.position = 'absolute';
	renderRules.style.top = '10px';
	renderRules.style.left = '10px';
	renderRules.style.width = '190px';
	renderRules.style.height = '160px';
	//renderRules.style.border = '1px solid red';
	renderRules.id='renderingDiv';
	renderRules.setAttribute('id','renderingDiv');

		// add the polygon fill section
		var label = document.createElement('label')
		label.style.position = 'absolute';
		label.style.top = '0px';
		label.style.left = '0px';
		label.style.width = '100%'
		label.style.height = '20px';
		//label.className='label';
		label.style.fontSize = '11px';
		label.style.fontWeight = 'bold';
		var text = document.createTextNode('Area Styles:');
		label.appendChild(text);
		renderRules.appendChild(label);

		// add the polygon fill table
		var fillTable = document.createElement('table');
		fillTable.style.position = 'absolute';
		fillTable.style.top = '10px';
		fillTable.style.left = '20px';
		fillTable.style.width = '150px';
		//fillTable.style.height = '40px';
		fillTable.border=0;

			// add the render rule table Body for Area Fill
			var tableBody = document.createElement('tbody');
				
				// build the color fill row
				var row = document.createElement('tr');
					
					// first cell is the label
					var tdCell = document.createElement('td')
					tdCell.style.width = '60px';
					tdCell.style.height= '18px';
					var text = document.createTextNode('Colour:');
					tdCell.appendChild(text);
					row.appendChild(tdCell);

					// second cell is the target color cell
					var tdCell = document.createElement('td')
					tdCell.style.width = '60px';
					tdCell.style.height= '18px';
					tdCell.id = 'terrFillColor';
					tdCell.setAttribute('id','terrFillColor');
					tdCell.className='whiteSunkenBox';
					if(territoryFillColor == ''){	territoryFillColor = "ff0000";} // set the default
					tdCell.style.backgroundColor = "#"+territoryFillColor;
					// set the opacity in the color fill box
					if(territoryFillOpacity == ''){	territoryFillOpacity = .1;} 
					if(browser == 'msie') 
					{	tdCell.style.filter = "alpha(opacity="+ (territoryFillOpacity * 100) + ")";		}
					else 
					{	tdCell.style.opacity = territoryFillOpacity;	}
					row.appendChild(tdCell);
					
					// third cell is the palette image control 
					var tdCell = document.createElement('td')
					tdCell.style.width = '20px';
					tdCell.style.height= '18px';
						// insert the color palette
						var symbolImg = document.createElement('img');
						symbolImg.src='images/palette.png';
						symbolImg.id='img:terrFillColor';
						symbolImg.setAttribute('id','img:terrFillColor');
						symbolImg.style.cursor='pointer';
						// onclick launch the colour palette
						bindEvent(symbolImg, 'click', colourPalette, 'false');
						tdCell.appendChild(symbolImg);
					row.appendChild(tdCell);
				
				tableBody.appendChild(row);
				
				// build the border color row
				var row = document.createElement('tr');
					var tdCell = document.createElement('td')
					tdCell.style.width = '60px';
					tdCell.style.height= '1px';
					var text = document.createTextNode('Opacity:');
					tdCell.appendChild(text);
					row.appendChild(tdCell);

					// add input cell for Fill Opacity
					var symbolCell = document.createElement('td');
					symbolCell.className='whiteSunkenBox';
					//symbolCell.className = 'symbolTitleCell';
					symbolCell.style.height='18px';
						
						// create the Select object
						var select = document.createElement('select');
						select.className='simpleSelectBox';
						select.style.width='60px';
						select.style.height='18px';
						select.id='terrFillOp';
						select.setAttribute('id','terrFillOp');
						// now create the Option rows
						var num = opacityOps.length;
						for (var i=0; i<num ; i++ )
						{
							var opt = document.createElement('option');
							opt.value=opacityOps[i];
							var optText = document.createTextNode(opacityOps[i]);
							opt.appendChild(optText);
							select.appendChild(opt)
						}
						// calculate rwo element as 10 times the opacity number
						if(territoryFillOpacity != ''){	select.selectedIndex = 10 - (territoryFillOpacity * 10);}
						else{ territoryFillOpacity = 10;}
						bindEvent(select, 'change', getSelectValue, 'false')
						symbolCell.appendChild(select);
					row.appendChild(symbolCell);

					// this is an emptry Cell
					var tdCell = document.createElement('td')
					tdCell.style.width = '20px';
					tdCell.style.height='18px';
					row.appendChild(tdCell);

				tableBody.appendChild(row);
				fillTable.appendChild(tableBody);
				
		renderRules.appendChild(fillTable);

		// add the border label
		var label = document.createElement('label')
		label.style.position = 'absolute';
		label.style.top = '65px';
		label.style.left = '0px';
		label.style.width = '100%'
		label.style.height = '20px';
		label.style.fontSize = '11px';
		label.style.fontWeight = 'bold';
		var text = document.createTextNode('Border Styles:');
		label.appendChild(text);
		renderRules.appendChild(label);
		
		// add the polygon border table
		var borderTable = document.createElement('table');
		borderTable.style.position = 'absolute';
		borderTable.style.top = '80px';
		borderTable.style.left = '20px';
		borderTable.style.width = '150px';
		//borderTable.style.height = '20px';
		borderTable.border=0;
		renderRules.appendChild(borderTable);
		// calculate rwo element as 10 times the opacity number
		if(territoryStrokeWidth == ''){	territoryStrokeWidth = 5;	} // set the default

			var tableBody = document.createElement('tbody');

				// add the render rule row for Area Fill
				var row = document.createElement('tr');
					
					// first cell is the label
					var tdCell = document.createElement('td')
					tdCell.style.width = '60px';
					tdCell.style.height='18px';
					var text = document.createTextNode('Colour:');
					tdCell.appendChild(text);
					row.appendChild(tdCell);

					// second cell is the tareget cell for the color
					var tdCell = document.createElement('td')
					tdCell.style.width = '60px';
					tdCell.style.height='18px';
					tdCell.className='whiteSunkenBox';
					if(territoryStrokeColor == ''){territoryStrokeColor = "#ff0000";}// set the default
					//tdCell.style.border= territoryStrokeWidth+'px solid  #'+territoryStrokeColor;
					//tdCell.style.backgroundColor = "#"+territoryStrokeColor;
					
						// set up a div that is the line replica
						var topAndHeight = makeLineThickness (territoryStrokeWidth);
						var parts = topAndHeight.split(':'); 
						var lineReplica = document.createElement('div');
						//lineReplica.style.position='absolute';
						lineReplica.style.height='10px';
						lineReplica.style.marginTop = '4px';
						lineReplica.style.top = parts[0]+'px';
						lineReplica.style.height = parts[1]+'px';
						lineReplica.style.width = '60px';
						lineReplica.style.borderTop = territoryStrokeWidth+'px solid  #'+territoryStrokeColor; 
						lineReplica.id = 'terrLineColor'
						lineReplica.setAttribute('id','terrLineColor');
						tdCell.appendChild(lineReplica);
					
					row.appendChild(tdCell);

					// third cell is the palette image control 
					var tdCell = document.createElement('td')
					tdCell.style.width = '20px';
					tdCell.style.height= '18px';
						// insert the color palette
						var symbolImg = document.createElement('img');
						symbolImg.src='images/palette.png';
						symbolImg.id='img:terrLineColor';
						symbolImg.setAttribute('id','img:terrLineColor');
						symbolImg.style.cursor='pointer';
						// onclick launch the colour palette
						bindEvent(symbolImg, 'click', colourPalette, 'false');
						tdCell.appendChild(symbolImg);					
					row.appendChild(tdCell);
					
				tableBody.appendChild(row);

				// create the line thickness row
				var row = document.createElement('tr');
					
					// first cell is the label
					var tdCell = document.createElement('td')
					tdCell.style.width = '80px';
					tdCell.style.height= '18px';
					var text = document.createTextNode('Thickness:');
					tdCell.appendChild(text);
					row.appendChild(tdCell);

					// second cell is the Select box
					var tdCell = document.createElement('td')
					tdCell.style.width = '60px';
					tdCell.style.height= '18px';
					tdCell.className='whiteSunkenBox';
					// create the Select object
						var select = document.createElement('select');
						select.className='simpleSelectBox';
						select.style.width='60px';
						select.style.height='18px';
						select.id='terrLineThick';
						select.setAttribute('id','terrLineThick');
						
						// now create the Option rows
						for (var i=0; i<lineWeights.length ; i++ )
						{
							var opt = document.createElement('option');
							opt.value=lineWeights[i];
							var optText = document.createTextNode(lineWeights[i]);
							opt.appendChild(optText);
							select.appendChild(opt)
						}
						// calculate rwo element as 10 times the opacity number
						select.selectedIndex = territoryStrokeWidth;	
						bindEvent(select, 'change', getSelectValue, 'false')
						tdCell.appendChild(select);
					row.appendChild(tdCell);
					
					// empty cell
					var tdCell = document.createElement('td')
					tdCell.style.width = '25px';
					row.appendChild(tdCell);
				tableBody.appendChild(row);
			borderTable.appendChild(tableBody);
		renderRules.appendChild(borderTable);

		// add the solid Territory override
		var label = document.createElement('label')
			label.style.position = 'absolute';
			label.style.top = '135px';
			label.style.left = '0px';
			label.style.width = '100%'
			label.style.height = '20px';
			label.style.fontSize = '11px';
			label.style.fontWeight = 'bold';
			var text = document.createTextNode('Solid Infill/Borders Override:');
		label.appendChild(text);
		renderRules.appendChild(label);

		// add the override checkbox
		var override = document.createElement('input');
			override.type = 'checkbox';
			override.style.position = 'absolute';
			override.style.top = '135px';
			override.style.left = '160px';
			override.style.backgroundColor='transparent';
			//alert('flag = '+territorySolidBorder);
			if(territorySolidBorder == 'false'){territorySolidBorder = false;}
			if(territorySolidBorder == 'true'){territorySolidBorder = true;}
			override.checked = territorySolidBorder; 
			override.id='solidOverride';
			override.title='check this box to override above styles with solid infil and surround border';
			override.setAttribute('id','solidOverride');
			bindEvent(override, 'change', overrideStyle, 'false')
		renderRules.appendChild(override);

	document.getElementById('renderEditor').appendChild(renderRules);
}

function overrideStyle(evt)
{
	var id = getThisId(evt);
	territorySolidBorder = document.getElementById(id).checked;
	document.getElementById(id).blur();
	if(territorySolidBorder == 'false'){territorySolidBorder = false;}
	if(territorySolidBorder == 'true'){territorySolidBorder = true;}
	document.getElementById(id).checked = territorySolidBorder;
	Event.stop(evt);
}

function showHideAllTerritories(id)
{
	// if plotting all territories
	//alert(document.getElementById(id).checked)
	if(document.getElementById(id).checked)
	{
		// reset checkbox
		document.getElementById(id).blur();
		document.getElementById(id).checked=true;

		// save the name of the current territoryfile if set
		//if(currentTerritoryFile != ''){saveCurrentTerritoryFile = currentTerritoryFile;}

		// cleanup any previous all territories SLD file
		if ( allSldTerritory )	
		{	deleteit(allSldTerritory);		
			var cacheDir = allSldTerritory.split('sld/')[1];
			purgeDrapeCache(cacheDir, '');
		}

		// turn off territory layer and remove any territory markers
		//removeTerrMarkers();
		//alert('terr markers gone')
		if(territory) 
		{ 
			//territory.destroy(); 
			territory.setVisibility(false);
		}
		zoomToSelectBox = false;

		// set up loop to display each territory in turn
		firstOfGroup = true;
		allTerritories = true;

		//alert(xmlValuesList)
		//alert(searchTarget)
		for (var i = 0; i<searchTarget.length; i++)
		{
			if(!getTheTerritoryForAll(xmlValuesList[i])) {return;}
			var percentDone = parseInt( Math.round((i+1)/searchTarget.length*100));
			genLoadStatus('Loading '+xmlTitlesList[i], false, percentDone);

			// convert territory area codes array into a comma separated string
			sqlStringAll = territoryFilterAll.toString();

			// draw out BBox od each territory  (debug)
			//drawBbox(loLeftCoords[0], loLeftCoords[1], hiRightCoords[0], hiRightCoords[1],"#FF0000", false);
			
			// update the all Territories Sld file
			appendTerritories(sqlStringAll, territoryRenderingStringAll, territoryLayerDataAll)
		}
		genLoadStatus('Displaying all Territories ...', false, '')
	
		// Assuming the Sld was created now swap it for the empty Sld to show all territories in folder
	
		var newSld = applicationBase+"inc/"+allSldTerritory;
		//alert(newSld)
		if(territoryDataLayerAll != '' )
		{
			// zoom to see all territories only if no active territory is set
			if(!territoryActive) 
			{	map.setCenter(allTerritoriesBounds.getCenterLonLat(),map.getZoomForExtent(allTerritoriesBounds));}
			
			// plot out all the territories layer
			registerLoadWheel(allTerritoriesLayer, 'loadWheelDrape');
			
			allTerritoriesLayer.mergeNewParams({'sld':newSld});
			allTerritoriesLayer.setVisibility(true);
			allTerritoriesLayer.setOpacity(0.5);
			resetZlevels();
		}
	
		//always set to New Territory Mode
		if(territoryActive && newSldTerritory)
		{
			territory.setVisibility(true);
			if(terrMarkers)
			{
				terrMarkers.setVisibility(true);
				document.getElementById('homeTerr').style.display = 'block';
				document.getElementById('homeTerr').title = 'hide home base'
				mousedown('homeTerr');
				//toggleHome('homeTerr');
			}
			if(terrLabels) 
			{	
				terrLabels.setVisibility(true);
				document.getElementById('labelTerr').style.display = 'block';
				document.getElementById('labelTerr').title = 'hide Territory labels'
				mousedown('labelTerr');
				//toggleLabels('labelTerr');
			}
		}

		// now add the home bases & home labels
		var homeButtTitle = document.getElementById('homeTerr').title;
		for (var i = 0; i<searchTarget.length; i++)
		{
			if(!getTheTerritoryForAll(xmlValuesList[i])) {return;}
			//alert('flag = '+territoryAddressAll)
			//alert('butt title = '+homeButtTitle)
			if(territoryAddressAll != '')
			{	makeHomeMarkerAll(true);		}
		}
		// set the home and labels buttons
		document.getElementById('homeTerr').title = 'show home base';
		toggleHome('homeTerr');
		document.getElementById('labelTerr').title = 'show Territory labels';
		toggleLabels('labelTerr');
		document.getElementById('homeTerr').style.display = 'block'
		document.getElementById('labelTerr').style.display = 'block';
		if(document.getElementById('newTerr').style.backgroundColor != 'white')
		{	changeMode('newTerr');	}
	}
	else
	{
		document.getElementById(id).blur();
		document.getElementById(id).checked=false;

		// turn off territory layers and remove any territory markers
		//removeTerrMarkers();
		document.getElementById('homeTerr').title = 'hide home base';
		toggleHome('homeTerr');
		document.getElementById('labelTerr').title = 'hide Territory labels';
		toggleLabels('labelTerr');
		document.getElementById('homeTerr').style.display = 'block'
		document.getElementById('labelTerr').style.display = 'block'
		
		if(territory) 
		{ 	territory.setVisibility(false);		}

		// turn off all the territories layer
		if(allTerritoriesLayer)
		{	allTerritoriesLayer.setVisibility(false);	}
		
		// cleanup any previous allterritories SLD file
		//alert('all sld on check = '+allSldTerritory)
		if ( allSldTerritory )	
		{	
			deleteit(allSldTerritory);		
			var cacheDir = allSldTerritory.split('sld/')[1];
			purgeDrapeCache(cacheDir, '');
			allSldTerritory = null;
			firstOfGroup = true;
		}
		allTerritories=false;

	}
	
/*	// if a territory is already active then redisplaplay
	//alert('is terr Active ? = '+territoryActive);
	//alert('row numb = '+checkForActiveTerritory());
	var homeButtTitle = document.getElementById('homeTerr').title;
	if(checkForActiveTerritory() != 'none')
	{
		//getTheTerritory(currentTerritoryFile);
		if(territory) {territory.setVisibility(true); }
		//if(terrMarkers){terrMarkers.setVisibility(true); }
		//if(terrLabels) {terrLabels.setVisibility(true); }

		// plot out the Homebase if required
		if(homeButtTitle = 'hide home base' && territoryAddress != '')
		{	
			makeHomeMarker(true);	
			document.getElementById('homeTerr').style.display = 'block'
			document.getElementById('labelTerr').style.display = 'block';
		}
	}
	else
	{	
		if(homeButtTitle!= 'hide home base')
		{	
			//alert('initialising territory')
			initialiseNewTerritory();
		}
	}
*/
	// clear out message and reset zlevels
	genLoadStatus('', false, '');
	resetZlevels();
}

function checkForActiveTerritory()
{
	for (var i=0; i<searchTarget.length; i++)
	{
		if(document.getElementById('terr_op:'+i).className == 'selectedItem')
		{return i;}
	}
	return 'none';
}


function getSelectValue(evt)
{
	var thisId = getThisId(evt)
	var areaObj = document.getElementById(thisId);	
	var newValue = areaObj.options[areaObj.selectedIndex].value;
	
	// reset the fill color
	if(thisId == 'terrFillOp')
	{
		var newOpacity = parseInt(parseFloat(newValue)*100);
		setOpacity(document.getElementById('terrFillColor'), newOpacity);
		territoryFillOpacity = newValue;
	}
	//reset the line thickness
	else if(thisId == 'terrLineThick')
	{
		//alert('selected option = '+newValue)
		document.getElementById('terrLineColor').style.borderTopWidth = newValue+'px';
		territoryStrokeWidth = newValue;
	}
	Event.stop(evt);
}


function makeLineThickness (thick)
{
	var topStartArray = [10,9,9,8,8,7,7,6,6,5,5];
	for (var i = 0; i<topStartArray.length ; i++)
	{
		if(i == thick)
		{	
			var top = topStartArray[i-1];
			var height = i-1;
			return top+":"+height;
		}
	}
	
}

function colourPalette(evt)
{
	var e_out = getThisId(evt);
	fillTargetId = e_out.split(":")[1];
	buildColorPalette(renderRules);
	Event.stop(evt);
}

function getTheTerritory(xmlfile)
{
	// check if file is actually there
	//alert('getTheTerritory input file = '+xmlfile)
	if(!filePresent(xmlfile))	{alert('Territory file '+xmlfile+' is not present!!'); return false;}
	
	// save current territory file when editing an existing Territory	
	if(!allTerritories){currentTerritoryFile = xmlfile;}
	else{currentTerritoryFile = '';}

	// load the territory
	var file = applicationBase+"inc/"+xmlfile;
	var query="?"+new Date().getTime();
	ajaxRequest = loadXml(file, query, false)
	if (!ajaxRequest.responseXML) 
	{	alert ("Territory File Fetch was unsuccessful");  return false; 	}
	
	// pick off all the data from the territory object 
	var territoryObj = ajaxRequest.responseXML.getElementsByTagName("Territory");
	
	// get the system specific attributes
	territoryFileName = territoryObj[0].getAttribute('fileName');
	territoryDateEntered = territoryObj[0].getAttribute('dateEntered');
	territoryDataLayer = territoryObj[0].getAttribute('dataLayer');
	territoryAttName = territoryObj[0].getAttribute('attName');
	territoryAttCode = territoryObj[0].getAttribute('attCode');
	territorySrs = territoryObj[0].getAttribute('srs');
	
	// get the territory specific attributes
	territoryPolygonName = territoryObj[0].getAttribute('territoryPolygonName'); // this is the xml tag name used to list the included polygons
	territoryBbox = territoryObj[0].getAttribute('territoryBbox'); // surrounding BBox
	territoryCode = territoryObj[0].getAttribute('territoryCode');
	territoryName = territoryObj[0].getAttribute('territoryName');
	
	//territoryArea = territoryObj[0].getAttribute('territoryArea');
	//territoryPop = territoryObj[0].getAttribute('territoryPop');
	
	territoryContact = territoryObj[0].getAttribute('territoryContact');
	territoryAddress = territoryObj[0].getAttribute('territoryAddress');
	territoryLocation = territoryObj[0].getAttribute('territoryLocation');
	territoryAbstract = territoryObj[0].getAttribute('territoryAbstract');
	
	// get the rendering parameters
	territoryFillColor = territoryObj[0].getAttribute('territoryFillColor');
	territoryFillOpacity = territoryObj[0].getAttribute('territoryFillOpacity');
	territoryStrokeColor = territoryObj[0].getAttribute('territoryStrokeColor');
	territoryStrokeWidth = territoryObj[0].getAttribute('territoryStrokeWidth');
	territorySolidBorder = territoryObj[0].getAttribute('territorySolidBorder');
	if(territorySolidBorder == 'false'){territorySolidBorder = false;}
	if(territorySolidBorder == 'true'){territorySolidBorder = true;}
	//alert('border flag = '+territorySolidBorder)

	// string the rendering riles together
	territoryRenderingString = territoryFillColor+":"+territoryFillOpacity+":"+territoryStrokeColor+":"+territoryStrokeWidth+":"+territorySolidBorder;
	
	// string the layer data together
	territoryLayerData = territoryDataLayer+":"+territoryAttName+":"+territoryAttCode
	
	// inititalise arrays of all the areas included in this Territory
	var areaObj = ajaxRequest.responseXML.getElementsByTagName(territoryPolygonName);
	territoryFilter = new Array();
	territoryNames = new Array();
	territoryBboxes = new Array();

	// save area name, code and BBox into current Territory arrays
	for (var i=0; i<areaObj.length; i++ )
	{
		territoryNames[i] = areaObj[i].getAttribute('name');
		territoryFilter[i] = areaObj[i].getAttribute('code');
		//territoryArea[i] = areaObj[i].getAttribute('area');
		//territoryPop[i] = areaObj[i].getAttribute('pop');
		if(areaObj[i].getAttribute('bbox')) {territoryBboxes[i] = areaObj[i].getAttribute('bbox');}
	}
	

	// split off the parts of the surrounding Territory BBox
	var bboxParts = territoryBbox.split(' ');
	loLeftCoords = bboxParts[0].split(',');
	hiRightCoords = bboxParts[1].split(',');
	baseCoords = territoryLocation.split(',');

	// the home base point on the territory is always long lats so switch them here if required
	if(srs == "EPSG:900913")
	{
		// now the Base location
		var p = [];
		p[0] = baseCoords[0];
		p[1] = baseCoords[1];
		var point = geogs2google(p);
		p = decodePoint (point);
		baseCoords[0] = p[0];
		baseCoords[1] = p[1];
	}

	// if this territory was from another srs than current one transform all BBox geometry
	if (territorySrs != srs)	
	{
		var p = [];
		if (srs == "EPSG:900913")
		{
			// do the low left point
			p[0] = loLeftCoords[0]; 
			p[1] = loLeftCoords[1];
			var point = geogs2google(p);
			p = decodePoint (point);
			loLeftCoords[0] = p[0];
			loLeftCoords[1] = p[1];
			
			// now the high right point
			p[0] = hiRightCoords[0];
			p[1] = hiRightCoords[1];
			var point = geogs2google(p);
			p = decodePoint (point);
			hiRightCoords[0] = p[0];
			hiRightCoords[1] = p[1];
		}
		else if (srs == 'EPSG:4326')
		{
			// do the low left point
			p[0] = loLeftCoords[0]; 
			p[1] = loLeftCoords[1];
			var point = google2geogs(p);
			p = decodePoint (point);
			loLeftCoords[0] = p[0];
			loLeftCoords[1] = p[1];
			
			// now the high right point
			p[0] = hiRightCoords[0];
			p[1] = hiRightCoords[1];
			var point = google2geogs(p);
			p = decodePoint (point);
			hiRightCoords[0] = p[0];
			hiRightCoords[1] = p[1];
		}
	}
	
	// build the BBOX parameterand Bounds for the Territory BBox
	bboxParam = loLeftCoords[0]+","+loLeftCoords[1]+" "+hiRightCoords[0]+","+hiRightCoords[1];
	territoryBounds = new OpenLayers.Bounds(loLeftCoords[0],loLeftCoords[1],hiRightCoords[0],hiRightCoords[1]);
	baseLocation = baseCoords[0]+","+baseCoords[1];	
	
	// reconstruct the filter list
	var polygon = territoryObj[0].getElementsByTagName(territoryPolygonName);
	nic = polygon.length;

	// remove the folder panel
	//document.getElementById('folderPanel').style.display='none';
	
	// draw out the BBox of the current Territory (debug)
	//drawBbox(loLeftCoords[0], loLeftCoords[1], hiRightCoords[0], hiRightCoords[1],"#FF0000", true);
	//alert(territoryNames)
	return true;
}
function getTheTerritoryForAll(xmlfile)
{
	// check if file is actually there
	//alert('getTheTerritory input file = '+xmlfile)
	//if(!filePresent(xmlfile))	{alert('Territory file '+xmlfile+' is not present!! see getTheterritoryForAll'); return false;}
	currentTerritoryFile = '';

	// load the territory
	var file = applicationBase+"inc/"+xmlfile;
	var query="?"+new Date().getTime();
	ajaxRequest = loadXml(file, query, false)
	if (!ajaxRequest.responseXML) 
	{	  return false; 	}
	
	// pick off all the data from the territory object 
	var territoryObj = ajaxRequest.responseXML.getElementsByTagName("Territory");
	
	// get the system specific attributes
	territoryFileNameAll = territoryObj[0].getAttribute('fileName');
	territoryDateEnteredAll = territoryObj[0].getAttribute('dateEntered');
	territoryDataLayerAll = territoryObj[0].getAttribute('dataLayer');
	territoryAttNameAll = territoryObj[0].getAttribute('attName');
	territoryAttCodeAll = territoryObj[0].getAttribute('attCode');
	territorySrsAll = territoryObj[0].getAttribute('srs');
	
	// get the territory specific attributes
	territoryPolygonNameAll = territoryObj[0].getAttribute('territoryPolygonName');
	territoryBboxAll = territoryObj[0].getAttribute('territoryBbox'); // surrounding BBox
	territoryCodeAll = territoryObj[0].getAttribute('territoryCode');
	territoryNameAll = territoryObj[0].getAttribute('territoryName');
	
	//territoryAreaAll = territoryObj[0].getAttribute('territoryArea');
	//territoryPopAll = territoryObj[0].getAttribute('territoryPop');
	
	territoryContactAll = territoryObj[0].getAttribute('territoryContact');
	territoryAddressAll = territoryObj[0].getAttribute('territoryAddress');
	territoryLocationAll = territoryObj[0].getAttribute('territoryLocation');
	territoryAbstractAll = territoryObj[0].getAttribute('territoryAbstract');
	
	// get the rendering parameters
	territoryFillColorAll = territoryObj[0].getAttribute('territoryFillColor');
	territoryFillOpacityAll = territoryObj[0].getAttribute('territoryFillOpacity');
	territoryStrokeColorAll = territoryObj[0].getAttribute('territoryStrokeColor');
	territoryStrokeWidthAll = territoryObj[0].getAttribute('territoryStrokeWidth');
	territorySolidBorderAll = territoryObj[0].getAttribute('territorySolidBorder');
	if(territorySolidBorderAll == 'false'){territorySolidBorderAll = false;}
	if(territorySolidBorderAll == 'true'){territorySolidBorderAll = true;}
	//alert('border flag = '+territorySolidBorder)

	// string the rendering riles together
	territoryRenderingStringAll = territoryFillColorAll+":"+territoryFillOpacityAll+":"+territoryStrokeColorAll+":"+territoryStrokeWidthAll+":"+territorySolidBorderAll;
	
	// string the layer data together
	territoryLayerDataAll = territoryDataLayerAll+":"+territoryAttNameAll+":"+territoryAttCodeAll
	
	// inititalise arrays of all the areas included in this Territory
	var areaObj = ajaxRequest.responseXML.getElementsByTagName(territoryPolygonNameAll);
	territoryFilterAll = new Array();
	territoryNamesAll = new Array();
	territoryBboxesAll = new Array();

	// save area name, code and BBox into current Territory arrays
	for (var i=0; i<areaObj.length; i++ )
	{
		territoryNamesAll[i] = areaObj[i].getAttribute('name');
		territoryFilterAll[i] = areaObj[i].getAttribute('code');
		if(areaObj[i].getAttribute('bbox')) {territoryBboxesAll[i] = areaObj[i].getAttribute('bbox');}
	}
	//alert(territoryNameAll +' = '+territoryNamesAll)

	// split off the parts of the surrounding Territory BBox
	var bboxParts = territoryBboxAll.split(' ');
	loLeftCoords = bboxParts[0].split(',');
	hiRightCoords = bboxParts[1].split(',');
	baseCoordsAll = territoryLocationAll.split(',');

	// the home base point on the territory is always long lats so switch them here if required
	if(srs == "EPSG:900913")
	{
		// now the Base location
		var p = [];
		p[0] = baseCoordsAll[0];
		p[1] = baseCoordsAll[1];
		var point = geogs2google(p);
		p = decodePoint (point);
		baseCoordsAll[0] = p[0];
		baseCoordsAll[1] = p[1];
	}

	// if this territory was from another srs than current one transform all BBox geometry
	if (territorySrsAll != srs)	
	{
		var p = [];
		if (srs == "EPSG:900913")
		{
			// do the low left point
			p[0] = loLeftCoords[0]; 
			p[1] = loLeftCoords[1];
			var point = geogs2google(p);
			p = decodePoint (point);
			loLeftCoords[0] = p[0];
			loLeftCoords[1] = p[1];
			
			// now the high right point
			p[0] = hiRightCoords[0];
			p[1] = hiRightCoords[1];
			var point = geogs2google(p);
			p = decodePoint (point);
			hiRightCoords[0] = p[0];
			hiRightCoords[1] = p[1];
		}
		else if (srs == 'EPSG:4326')
		{
			// do the low left point
			p[0] = loLeftCoords[0]; 
			p[1] = loLeftCoords[1];
			var point = google2geogs(p);
			p = decodePoint (point);
			loLeftCoords[0] = p[0];
			loLeftCoords[1] = p[1];
			
			// now the high right point
			p[0] = hiRightCoords[0];
			p[1] = hiRightCoords[1];
			var point = google2geogs(p);
			p = decodePoint (point);
			hiRightCoords[0] = p[0];
			hiRightCoords[1] = p[1];
		}
	}
	
	// build the BBOX parameterand Bounds for the Territory BBox
	bboxParamAll = loLeftCoords[0]+","+loLeftCoords[1]+" "+hiRightCoords[0]+","+hiRightCoords[1];
	territoryBoundsAll = new OpenLayers.Bounds(loLeftCoords[0],loLeftCoords[1],hiRightCoords[0],hiRightCoords[1]);
	baseLocationAll = baseCoordsAll[0]+","+baseCoordsAll[1];	
	
	// reconstruct the filter list
	var polygon = territoryObj[0].getElementsByTagName(territoryPolygonNameAll);
	nic = polygon.length;

	// remove the folder panel
	//document.getElementById('folderPanel').style.display='none';
	
	// draw out the BBox of the current Territory (debug)
	//drawBbox(loLeftCoords[0], loLeftCoords[1], hiRightCoords[0], hiRightCoords[1],"#FF0000", true);
	return true;
}

function drawBbox(LLX, LLY, TRX, TRY, bboxColor, overwrite)
{
	var loX=99999999999999.0; 
	var loY=99999999999999.0; 
	var hiX=-99999999999999.0; 
	var hiY=-99999999999999.0;
	var pointList = new Array();
	
	if(vectorLayer3 && overwrite) 
	{	//alert('removing BBoxes')
		vectorLayer3.destroy();
		//map.removeLayer(vectorLayer2); 
		//vectorLayer2 = null;
	}

	//alert('drawing the new BBox')
		
	// initialise a new vector layer
	bounding_box = OpenLayers.Util.extend({},  layer_style); 
	bounding_box.fillOpacity = 0;
	bounding_box.strokeWidth = 2.0;
	bounding_box.strokeOpacity = 0.5;
	bounding_box.strokeColor = bboxColor;
	vectorLayer3 = new OpenLayers.Layer.Vector("Bounding Box", {style: bounding_box});

	// now add the new vector layer to the map
	vectorLayer3.addOptions({'displayInLayerSwitcher': true, reproject: true, visibility:true, reaspect: false});
	map.addLayer(vectorLayer3);
	resetZlevels();


	// get the vertices of the polygon into real world arrays
	// loLeftCoords and hiRightCoords defines the BBox of territory as on file
	allX = new Array();
	allY = new Array();
	allX[0] = LLX;
	allY[0] = LLY;
	
	allX[1] = LLX;
	allY[1] = TRY;
	
	allX[2] = TRX;
	allY[2] = TRY;
	
	allX[3] = TRX;
	allY[3] = LLY;
	
	allX[4] = LLX;
	allY[4] = LLY;

	for (var i=0 ; i<allX.length ; i++)
	{
		// get all the points of the polygon from input arrays
		pointList.push(new OpenLayers.Geometry.Point(allX[i], allY[i]));
		
		// calculate BBox of search polygon
		if(allX[i] < loX){loX=allX[i];}
		if(allX[i] > hiX){hiX=allX[i];}
		if(allY[i] < loY){loY=allY[i];}
		if(allY[i] > hiY){hiY=allY[i];}
	}
	
	// make sure last point and first point are the same
	if(allX[0] != allX[allX.length-1] || allY[0] != allY[allX.length-1])
	{  allX[allX.length-1] = allX[0]; allY[allX.length-1] = allY[0];}

	// commit the search polygon to the vector layer
	var bboxVectors = new OpenLayers.Geometry.LinearRing(pointList);
	bboxFeature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Polygon([bboxVectors]));
	//polygonFeature.graphicZIndex = 300;
	vectorLayer3.addFeatures(bboxFeature);	
	resetZlevels();
	
	
}

function drawPoint(x, y, delme)
{
	pointList = [];
	if(vectorLayer3 && delme) {	vectorLayer3.destroy(); }

	// get the vertices of the polygon into real world arrays
	pointList.push(new OpenLayers.Geometry.Point(x-20, y-20));
	pointList.push(new OpenLayers.Geometry.Point(x-20, y+20));
	pointList.push(new OpenLayers.Geometry.Point(x+20, y+20));
	pointList.push(new OpenLayers.Geometry.Point(x+20, y-20));
	pointList.push(new OpenLayers.Geometry.Point(x-20, y-20));
	
	// commit the search polygon to the vector layer
	var bboxVectors = new OpenLayers.Geometry.LinearRing(pointList);
	bboxFeature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Polygon([bboxVectors]));
	vectorLayer3.addFeatures(bboxFeature);	
	
}
// ----- this is a generic routine to use SLDs to highlight a collection of polygons defined in sqlString ----//
function highlightTerritory(sqlString, territoryName)
{
	genLoadStatus('Loading "'+territoryName+'"', false);
	if ( newSldTerritory )	
	{	deleteit(newSldTerritory);		// cleanup any previous allterritories SLD file
		var cacheDir = newSldTerritory.split('sld/')[1];
		purgeDrapeCache(cacheDir, '');
	}

	// Now create a new SLD for this particular LGA boundary
	var pathParts = terrPathSld.split('/');
	newTempSldPath = pathParts[0]+'/';
	var fileParts = pathParts[1].split('.');
	newTempSldFile = 'newSld_'+fileParts[0]+'_'+new Date().getTime()+'.xml';
	newSldTerritory = 'sld/'+ newTempSldPath + newTempSldFile;

	//alert('layer = '+territoryDataLayer)
	// set parameters to build a new SLD via makeNewSldFile_new.php
	var query = "?file="+newSldTerritory;
	query+= "&layer="+territoryDataLayer;
	query+= "&title="+territoryAttName;
	query+= "&name="+territoryAttName;
	query+= "&abstract="+territoryAbstract;
	query+= "&att="+territoryAttCode;
	query+= "&filter="+sqlString;
	query+= "&patt=";
	//query+= "&patt="+areaFillBase+"blackdiagonal.png";
	//query+= "&form=image/png";
	query+= "&form=";	
	query+= "&label=";
	//query+= "&label="+territoryAttName;	
	query+= "&bcol="+territoryStrokeColor;
	query+= "&fcol="+territoryFillColor;
	query+= "&opac="+territoryFillOpacity;
	query+= "&line="+territoryStrokeWidth;
	query+= "&update=false";
	query+= "&solid="+territorySolidBorder; 
	//alert('territory Solid Border = '+territorySolidBorder)
	// create a new temporary Highlighting SLD
	var request = applicationBase + "inc/makeNewSldFile_new.php";
	var aquery = query.split('?')[1];
	
	//alert(request+query)
	makeFile(request, aquery,  'false', 'POST')
	
	// Assuming the Sld was created now swap it for the empty Sld
	var newSld = applicationBase+"inc/"+newSldTerritory;
	
	// if the territory layer has been deleted, create it again
	if(!territory)	{	createTerritoryLayer();	}

	//alert('territory layer = '+territoryDataLayer)

	// if OK then go ahead and replace the old territory filter with the new one
	if(territoryDataLayer != '' && activelayerMatchTerritorylayer() )
	{
		// set map window over territory boundary
		if(territoryBounds) {zoomToTerritory(territoryBounds);}
		//alert('new Sld = '+newSld)
		territory.mergeNewParams({'sld':newSld});

		// all is well
		if(territory)		{ 	territory.setVisibility(true);}
		territoryActive = true;

		// show the home base if button down
		var homeButt = document.getElementById('homeTerr');
		if(homeButt.title = 'hide home base' && territoryAddress != '')
		{	makeHomeMarker(true);	}	
	}

	genLoadStatus('', false, '');
	resetZlevels();
	firstOfGroup = true;

	// now set the territory manager to be in maximum state
	minmaxTerritoryManager('max');
}

// ----- this is a generic routine to use SLDs to highlight a collection of polygons defined in sqlString ----//
function appendTerritories(sqlString, terrRenderingString, terrLayerData)
{
	if (firstOfGroup)	
	{	
		// Now create a new SLD file for the Territory or
		var pathParts = terrPathSld.split('/');
		newTempSldPath = pathParts[0]+'/';
		var fileParts = pathParts[1].split('.');
		newTempSldFile = 'newSld_'+fileParts[0]+'_'+new Date().getTime()+'.xml';
		allSldTerritory = 'sld/'+ newTempSldPath + newTempSldFile;
		//alert(allSldTerritory)
	}

	// split off all the components needed for this territory
	var renderParts = terrRenderingString.split(':');
	var dataParts = terrLayerData.split(':');

	// set parameters to build a new SLD via makeNewSldFile.php
	var query = "?file="+allSldTerritory;
	query+= "&layer="+dataParts[0]+":"+dataParts[1];
	query+= "&title="+dataParts[2];
	query+= "&name="+dataParts[2];
	query+= "&att="+dataParts[3];
	query+= "&abstract=";
	query+= "&filter="+sqlString;
	//query+= "&patt="+areaFillBase+"blackdiagonal.png";
	query+= "&patt=";
	query+= "&form=";
	//query+= "&form=image/png";
	//query+= "&label="+dataParts[2];	
	
	query+= "&label=";
	query+= "&line=";
	query+= "&fcol="+renderParts[0];
	query+= "&opac="+renderParts[1];
	query+= "&bcol="+renderParts[2];
	if(firstOfGroup) {	query+="&update=false";}
	else {	query+= "&update=true";}
	query+= "&solid="+renderParts[4];

	// create a new temporary Highlighting SLD
	var request = applicationBase + "inc/makeNewSldFile_new.php";
	var aquery = query.split('?')[1];
	//alert(request+query)
	makeFile(request, aquery,  'false', 'POST')
	firstOfGroup = false;
}


function makeHomeMarker(selectable)
{
	//alert(territoryAddress)
	//alert(territoryLocation)
	if(territoryAddress == '')
	{	document.getElementById('homeTerr').title='show home base';
		mouseup('homeTerr');
		//alert('nothing here')
		return;
	}
	
	// get the Territory name from the form
	if(territoryName == '')
	{
		territoryName = document.getElementById('nameOfTerritory').value;
		//alert('terr name = '+territoryName);
		if(territoryName == '' && !allTerritories){alert('You need to name this Territory '); 	return; }
	}
	
	// remove any existing popups/markers
	//if(!accumulate && terrMarkers) { removeTerrMarkers();}
	//alert('territoryActive = '+territoryActive+ "territoryName = "+territoryName);
	// now setup popup information
	var atts = "<div class='attributes' ><h3>Territory Attributes ("+territoryName+")</h3>"+
		"<b>File Name : </b>"+territoryFileName+"<br/>"+ 
		"<b>Date Entered : </b>"+territoryDateEntered+"<br/>"+
		"<b>Data Layer : </b>"+territoryDataLayer+"<br/>"+
		"<b>Attribute Name : </b>"+territoryAttName+"<br/>"+
		"<b>Attribute Code : </b>"+territoryAttCode+"<br/>"+
		"<b>Spatial Reference System : </b>"+territorySrs+"<br/>"+
		"<b>Bounding Box : </b>"+territoryBbox+"<br/>"+
		"<b>Territory ID : </b>"+territoryCode+"<br/>"+
		"<b>Territory Name : </b>"+territoryName+"<br/>"+
		"<b>Contact Person : </b>"+territoryContact+"<br/>"+
		"<b>Home Address : </b>"+territoryAddress+"<br/>"+
		"<b>Home Location (lng/lat) : </b>"+territoryLocation+"<br/>"+ 
		"<b>Colour of Infill : </b>"+territoryFillColor+"<br/>"+
		"<b>Opacity of Infill : </b>"+territoryFillOpacity+"<br/>"+
		"<b>Colour of Borders : </b>"+territoryStrokeColor+"<br/>"+
		"<b>Thickness of Borders : </b>"+territoryStrokeWidth+"<br/>"+
		"<b>Description : </b>"+territoryAbstract+"<br/>"+
		"<b>Area Type : </b>"+territoryPolygonName +"<br/><br/>"+
		"------------------ Included Areas ("+territoryNames.length+")------------------<br/><br/>";

	// add the individual included polygon data
	var accumX = 0.0; var accumY = 0.0;
	//alert('no of territories = '+territoryNames.length)
	for(var i=0; i<territoryNames.length; i++)
	{
		atts+="<b>Name : </b>"+territoryNames[i]+"<br/>"+
		"<b>ID : </b>"+territoryFilter[i]+"<br/>"+
		"<b>BBox : </b>"+territoryBboxes[i]+"<br/><br/>";
	}
	atts+="</div>";

	// add the point to the pointFeature array of Vector objects
	var point = new OpenLayers.Geometry.Point(baseCoords[0], baseCoords[1]);
	pointFeature = new OpenLayers.Feature.Vector (point)

	// add attributes to pointFeature of Vector Objects (can be an array)
	pointFeature.attributes.description = atts;
	pointFeature.attributes.fillColor = 'white';
	pointFeature.attributes.fillOpacity = '0.6';
	pointFeature.attributes.strokeColor = 'black';
	pointFeature.attributes.strokeWidth = '2';
	pointFeature.attributes.radius = '6';
	pointFeature.attributes.symbology = "images/home.png";
	pointFeature.attributes.name = territoryName;
	pointFeature.id = territoryName;
	//alert(pointFeature.attributes.symbology)

	// create the vector layer and apply the styleMap at the same time
	if(!terrMarkers)
	{
		terrMarkers = new OpenLayers.Layer.Vector( "Territory Markers", 
		{	styleMap: terrStyleMap		});
		map.addLayer(terrMarkers);
		//resetZlevels();
	}

	// pointFeature is the array of sorted point objects to be added as vector markers
	terrMarkers.addFeatures(pointFeature);	

	// if selectable then generate the select control
	if(selectable)
	{
		//alert('activating territory select')
		terrSelectControl = new OpenLayers.Control.SelectFeature(terrMarkers, 
		{	//hover: true
			onSelect: onTerrSelect 
			,onUnselect: onTerrUnselect
		});
		map.addControl(terrSelectControl);
		terrSelectControl.activate();
		terrMarkers.setVisibility(true);
		mousedown('homeTerr');
		document.getElementById('homeTerr').title='hide home base';
	}
	else if(map.terrSelectControl && !selectable)
	{	
		//alert('removing select control');		
		//map.terrSelectControl.decativate();	
		map.removeControl(terrSelectControl);
		//terrSelectControl.destroy(); 
	}
	
	// add the point at the centre of the territoryBounds
	var centre = getCentreBbox(territoryBounds);
	if(centre != 'error')
	{
		centre = centre.split(":");

		// set label at the centre of the territories BBox
		var label = new OpenLayers.Geometry.Point(centre[0], centre[1]);
		labelFeature = new OpenLayers.Feature.Vector (label)
		
		// capitalise first letter of each word
		labelFeature.attributes.name = capitaliseIt(territoryName);
		labelFeature.id = 'label:'+territoryName;
		// create the vector layer and apply the styleMap at the same time
		if(!terrLabels)
		{
			terrLabels = new OpenLayers.Layer.Vector( "Territory Labels", 
			{	styleMap: terrLabelStyleMap		});
			map.addLayer(terrLabels);
			//resetZlevels();
		}
		// pointFeature is the array of sorted point objects to be added as vector markers
		terrLabels.addFeatures(labelFeature);
		terrLabels.setVisibility(true);
		mousedown('labelTerr');
		document.getElementById('labelTerr').title='hide Territory labels';
	}

	//resetZlevels();

}
function makeHomeMarkerAll(selectable)
{
	//alert(territoryAddressAll)
	//alert(territoryLocationAll)
	if(territoryAddressAll == '')
	{	document.getElementById('homeTerr').title='show home base';
		mouseup('homeTerr');
		return;
	}
	
	// get the Territory name from the form
	if(territoryNameAll == '')
	{
		territoryNameAll = document.getElementById('nameOfTerritory').value;
		//alert('terr name = '+territoryName);
		if(territoryNameAll == '' && !allTerritories){alert('You need to name this Territory '); 	return; }
	}
	
	// remove any existing popups/markers
	//if(!accumulate && terrMarkers) { removeTerrMarkers();}
	//alert('territoryActive = '+territoryActive+ "territoryName = "+territoryName);
	// now setup popup information
	var atts = "<div class='attributes' ><h3>Territory Attributes ("+territoryNameAll+")</h3>"+
		"<b>File Name : </b>"+territoryFileNameAll+"<br/>"+ 
		"<b>Date Entered : </b>"+territoryDateEnteredAll+"<br/>"+
		"<b>Data Layer : </b>"+territoryDataLayerAll+"<br/>"+
		"<b>Attribute Name : </b>"+territoryAttNameAll+"<br/>"+
		"<b>Attribute Code : </b>"+territoryAttCodeAll+"<br/>"+
		"<b>Spatial Reference System : </b>"+territorySrsAll+"<br/>"+
		"<b>Bounding Box : </b>"+territoryBboxAll+"<br/>"+
		"<b>Territory ID : </b>"+territoryCodeAll+"<br/>"+
		"<b>Territory Name : </b>"+territoryNameAll+"<br/>"+
		"<b>Contact Person : </b>"+territoryContactAll+"<br/>"+
		"<b>Home Address : </b>"+territoryAddressAll+"<br/>"+
		"<b>Home Location (lng/lat) : </b>"+territoryLocationAll+"<br/>"+ 
		"<b>Colour of Infill : </b>"+territoryFillColorAll+"<br/>"+
		"<b>Opacity of Infill : </b>"+territoryFillOpacityAll+"<br/>"+
		"<b>Colour of Borders : </b>"+territoryStrokeColorAll+"<br/>"+
		"<b>Thickness of Borders : </b>"+territoryStrokeWidthAll+"<br/>"+
		"<b>Description : </b>"+territoryAbstractAll+"<br/>"+
		"<b>Area Type : </b>"+territoryPolygonNameAll+"<br/><br/>"+
		"------------------ Included Areas ("+territoryNamesAll.length+")------------------<br/><br/>";

	// add the individual included polygon data
	var accumX = 0.0; var accumY = 0.0;
	//alert('no of territories = '+territoryNamesAll.length)
	for(var i=0; i<territoryNamesAll.length; i++)
	{
		atts+="<b>Name : </b>"+territoryNamesAll[i]+"<br/>"+
		"<b>ID : </b>"+territoryFilterAll[i]+"<br/>"+
		"<b>BBox : </b>"+territoryBboxesAll[i]+"<br/><br/>";
	}
	atts+="</div>";

	// add the point to the pointFeature array of Vector objects
	var point = new OpenLayers.Geometry.Point(baseCoordsAll[0], baseCoordsAll[1]);
	pointFeature = new OpenLayers.Feature.Vector (point)

	// add attributes to pointFeature of Vector Objects (can be an array)
	pointFeature.attributes.description = atts;
	pointFeature.attributes.fillColor = 'white';
	pointFeature.attributes.fillOpacity = '0.6';
	pointFeature.attributes.strokeColor = 'black';
	pointFeature.attributes.strokeWidth = '2';
	pointFeature.attributes.radius = '6';
	pointFeature.attributes.symbology = "images/home.png";
	pointFeature.attributes.name = territoryNameAll;
	pointFeature.id = territoryNameAll;
	//alert(pointFeature.attributes.symbology)

	// create the vector layer and apply the styleMap at the same time
	if(!terrMarkers)
	{
		terrMarkers = new OpenLayers.Layer.Vector( "Territory Markers", 
		{	styleMap: terrStyleMap		});
		map.addLayer(terrMarkers);
		//resetZlevels();
	}

	// pointFeature is the array of sorted point objects to be added as vector markers
	terrMarkers.addFeatures(pointFeature);	

	// if selectable then generate the select control
	if(selectable)
	{
		//alert('activating territory select')
		terrSelectControl = new OpenLayers.Control.SelectFeature(terrMarkers, 
		{	//hover: true
			onSelect: onTerrSelect 
			,onUnselect: onTerrUnselect
		});
		map.addControl(terrSelectControl);
		terrSelectControl.activate();
		terrMarkers.setVisibility(true);
		mousedown('homeTerr');
		document.getElementById('homeTerr').title='hide home base';
	}
	else if(map.terrSelectControl && !selectable)
	{	
		//alert('removing select control');		
		//map.terrSelectControl.decativate();	
		map.removeControl(terrSelectControl);
		//terrSelectControl.destroy(); 
	}
	
	// add the Label point at the centre of the territoryBounds
	var centre = getCentreBbox(territoryBoundsAll);
	if(centre != 'error')
	{
		centre = centre.split(",");

		// set label at the centre of the territories BBox
		var label = new OpenLayers.Geometry.Point(centre[0], centre[1]);
		labelFeature = new OpenLayers.Feature.Vector (label)
		
		// capitalise first letter of each word
		labelFeature.attributes.name = capitaliseIt(territoryNameAll);
		labelFeature.id = 'label:'+territoryNameAll;
		// create the vector layer and apply the styleMap at the same time
		if(!terrLabels)
		{
			terrLabels = new OpenLayers.Layer.Vector( "Territory Labels", 
			{	styleMap: terrLabelStyleMap		});
			map.addLayer(terrLabels);
			//resetZlevels();
		}
		// pointFeature is the array of sorted point objects to be added as vector markers
		terrLabels.addFeatures(labelFeature);
		terrLabels.setVisibility(true);
		mousedown('labelTerr');
		document.getElementById('labelTerr').title='hide Territory labels';
	}

	//resetZlevels();

}

function setupTerrSymbols()
{
	// set up the default styling for the vector layer
	
	if(browser != 'msie')
	{
		terrDefaultStyle = new OpenLayers.Style(
		{
			externalGraphic: "${symbology}"
			,graphicWidth: "20"
			,graphicHeight: "20"
			,graphicOpacity: "1"
		});
		// create the style map with default and select modes
		terrStyleMap = new OpenLayers.StyleMap(
		{	"default":	terrDefaultStyle
	//		,"select":	terrSelectStyle
		});
	}
	else
	{	
		terrDefaultStyle = new OpenLayers.Style(
		{
			 fillColor: '${fillColor}' 
			,fillOpacity: '${fillOpacity}'
			,strokeColor: '${strokeColor}'
			,strokeWidth: '${strokeWidth}'
			,pointRadius: "${radius}"
		});
		terrSelectStyle = new OpenLayers.Style(
		{
			 fillColor: 'yellow' 
			,fillOpacity: '${fillOpacity}'
			,strokeColor: 'green'
			,strokeWidth: '${strokeWidth}'
			,pointRadius: "${radius}"
		});
		// create the style map with default and select modes
		terrStyleMap = new OpenLayers.StyleMap(
		{	"default":	terrDefaultStyle
			,"select":	terrSelectStyle
		});
	}
				
	// label style map
	terrLabelDefaultStyle = new OpenLayers.Style(
	{
		label: "${name}"
		,fontColor: "black"
        ,fontWeight: "bolder"
		,fontSize: "15"
		,fontFamily: "verdana"
		
	})
	
	// create the style map with default and select modes
	terrLabelStyleMap = new OpenLayers.StyleMap(
	{	"default":	terrLabelDefaultStyle	});
}

function onTerrSelect(feature) 
{
	//alert('pickmode = '+pickMode);
	selectedFeature = feature;
	popupFlag=true;
	rad = feature.attributes.radius;
	var size = rad * 2;
	
	// now calculate the pixel off sets from the centre point
	var delX = parseInt(Math.sin(45.0)*rad);
	var delY = parseInt(Math.cos(45.0)*rad);
	
	// set up the anchor point
    var anchor =
	{
		'size': new OpenLayers.Size(0,0), 
		'offset': new OpenLayers.Pixel(delX, -delY)
	};
// generate the framedCloud popup
/*
	id				{String}
	lonlat			{OpenLayers.LonLat}
	size			{OpenLayers.Size}
	contentHTML		{String}
	anchor			{Object} Object to which we’ll anchor the popup.  Must expose a ‘size’ (OpenLayers.Size) and ‘offset’ (OpenLayers.Pixel) (Note that this is generally an OpenLayers.Icon).
	closeBox		{Boolean}
	closeBoxCallback{Function} Function to be called on closeBox click.

*/
	terrPopup = new OpenLayers.Popup.FramedCloud("HomeBase" 
		,feature.geometry.getBounds().getCenterLonLat()
		,null
		,"<div style='font-size:9px; height:auto; '><br/>"+feature.attributes.description+" <br/></div>"
		,anchor
		,true
		,onTerrPopupClose);

	// add popup to this map feature
	feature.popup = terrPopup;
	map.addPopup(terrPopup);
	terrPopup.panMapIfOutOfView = true;
	//activateControls('onTerrSelect');
}

function onTerrPopupClose(evt) 
{	
	terrSelectControl.unselect(selectedFeature); 
	popupFlag=false;
	//activateControls('onTerrPopupClose');
}
					
function onTerrUnselect(feature) 
{
	map.removePopup(feature.popup)
	feature.popup.destroy();
	feature.popup = null;
	//activateControls('onTerrSelect');
}

function activelayerMatchTerritorylayer()
{
	// check that the current active layer is same as this territories layer
	var testTerritoryLayer = territoryDataLayer.split(":")[0];
	//alert(activeLayerName+" == "+testTerritoryLayer)
	if(activeLayerName != testTerritoryLayer)
	{
		if(setActiveLayer(testTerritoryLayer)) {	return true; }
		else {	return false; }
	}
	return true;
}

function setActiveLayer(testTerritoryLayer)
{
	//alert('setting active layer')
	//alert('current Active Layer = '+activeLayerName)
	//alert('test territory Layer = '+testTerritoryLayer)
	
	// set active layer to be the territory layer for now
	var layNum = -1; var actNum = -1;
	for(var i=0; i<Name.length; i++)
	{
		//alert(Name[i]+' and '+territoryDataLayer);
		if(Name[i] == territoryDataLayer)	{	layNum = i;	}
		
		var nametest = Name[i].split(":")[0];
		//alert(activeLayerName+"  &&  "+nametest)
		if(activeLayerName == nametest && nametest != '')	{	actNum = i;	}
	}
	//alert('lay num for active layer = '+layNum)
	//alert('act num for active layer = '+actNum)
	
	// set active layer and modify the select menu/panel
	if(layNum > 0)
	{
		// First clear out any existing Active Layer if present
		if(actNum > 0)
		{
			// remove existing Active Layer from map 
			//map.removeLayer(LayerObj[actNum]);
			LayerObj[actNum].destroy();
			LayerObj[actNum] = null;
			// remove Active layer from picl lists
			document.getElementById('layers:'+actNum).checked = false;
			document.getElementById('label:'+actNum).checked = false;
			document.getElementById('arow:'+actNum).className = 'unselectedItem';
		}

		// make territoryLayer the activeLayer
		activeLayerName = testTerritoryLayer;
		layLineSld = applicationBase+Sld[layNum];

		// now set new active layer as the new Active Layer
		document.getElementById('arow:'+layNum).className = 'selectedItem';
		document.getElementById('layers:'+layNum).checked = 'checked';
		manipulateLayer(layNum);
		//alert('active territory layer = '+activeLayerName)
		return true;
	}
//	else
//	{	alert('sorry this layer cannot be edited. There is no compatible active layer');
//		return false;
//	}
}
function resetTerritory()
{
	//setupTerrSymbols();
	currentTerrRow = -1;
	territoryActive = false;
	allTerritories = true;
	newSldTerritory = null;
	currentTerritoryFile = '';
	initialiseTerritory();
	
	// now set the territory manager to be in maximum state
	minmaxTerritoryManager('min');
	makeTableSelectControl(territoryFolder, 'territoriesList', 'Territory', 'territoryName', 'terr');
	changeMode('newTerr');
	if(territory) {territory.setVisibility(false); }
	if(terrMarkers){terrMarkers.setVisibility(false); }
	if(terrLabels) {terrLabels.setVisibility(false); }
	//alert('resetting territory')
	if(vectorLayer)	{vectorLayer.destroy();}
	
	// remove circles layer if already there
	if(vectorLayer4){ vectorLayer4.destroy(); vectorLayer4 = null;}
	
	// remove the innerboudaries from map
	if(innerBoundaries) {innerBoundaries.setVisibility(false);}
	//removeTerrMarkers();
	polypikaMode = false;

	// reset the PolyPika button
	document.getElementById('enterDigitMode').className='buttup';
	document.getElementById('enterDigitMode').title = 'Enter Polypika Mode';
	document.getElementById('enterDigitMode').value = 'Enter Polypika Mode';
	document.getElementById('enterDigitMode').blur();
	document.getElementById('renderPanel').style.display='none';
	//toggleHome('homeTerr');
	document.getElementById('homeTerr').style.display = 'none';
	//toggleLabels('labelTerr');
	document.getElementById('labelTerr').style.display = 'none';
		
	var selectObject = document.getElementById('actLayOptions');
	selectObject.options[selectObject.selectedIndex].value=-1
	/*if(allTerritoriesLayer) 
	{	
		allTerritoriesLayer.setVisibility(false); 
		document.getElementById('showAllTerr').checked = false;
	}*/
	//alert('territory Filter = '+territoryFilter);
}
function changeMode(Id)
{
	if(Id == 'newTerr')
	{
		// manage the buttons
		mouseup('openTerr');
		mousedown('newTerr'); 
		textDisplay('selectedTerr','');
		
		// now just switch divs about
		document.getElementById('territoriesList').style.display='block';
		document.getElementById('territoriesForm').style.display='block';
		document.getElementById('inclusions').style.display='block';
		document.getElementById("folderPanel").style.display="none";
		if(browser != 'msie'){document.getElementById("nameOfTerritory").focus();}
		
		turnOffActiveLayer();
		resetPolypikaForm();
		newTerritory = true;
		initialiseNewTerritory();
	}
	else if(Id == 'openTerr')
	{ 
		// manage the buttons
		mouseup('newTerr');
		mousedown('openTerr');
				
		// create the list of territories
		if(searchTarget.length == 0)
		{	makeTableSelectControl(territoryFolder, 'territoriesList', 'Territory', 'territoryName', 'terr');	}
		
		// activate the territory Folder and deactivate the input editing form
		document.getElementById('territoriesList').style.display='block';
		document.getElementById('territoriesForm').style.display='block';
		document.getElementById('inclusions').style.display='block';
		document.getElementById("folderPanel").style.display="block";
		
		// if in polypika mode then update polypika Panel name
		if(activeLayerName != '')
		{	enablePolypika();		}
	}
	//showHideTerritoriesReport('listTerr');
}



function killTerritoryMarkers()
{
	//alert ('hello world');
}

function showHideTerritoriesReport(callingId, reportTargetId)
{
	var callingObj = document.getElementById(callingId);
	var title= callingObj.title
	if(title == 'Show Report')
	{
		callingObj.title = 'Hide Report';	
		getListOfTerritories();
		document.getElementById(reportTargetId).style.display = 'block';
		mousedown(callingId)
	}
	else if(title == 'Hide Report')
	{
		callingObj.title = 'Show Report';
		document.getElementById(reportTargetId).style.display = 'none';
		mouseup(callingId)
	}
}

function getListOfTerritories()
{
	// get the list of xml files from the folder
	ajaxRequest = getListOfFiles(territoryFolder);
	if(ajaxRequest == 'error') {alert('oops'); return;}

	// get the names of each file and store in list array
	var xmlFiles = ajaxRequest.responseText.split("|");
	//alert(xmlFiles)

	// Create the report table
	var territoryInfo = document.getElementById('territoriesInfo2');
	checkRemoveObject('territoriesGfiData2');

	var tableHolder = document.createElement('table');
	tableHolder.style.border='1px solid gray';
	tableHolder.style.minWidth = '100%';
	tableHolder.style.width = 'auto';
	tableHolder.style.height = 'auto';
	tableHolder.style.textAlign = 'center';
	tableHolder.style.backgroubdColor = '#FFFFFF';
	tableHolder.id = 'territoriesGfiData2';
	tableHolder.setAttribute('id', 'territoriesGfiData2');

	var table = document.createElement('tbody');	
	table.style.zIndex = '5600';
	table.style.backgroundColor='#ffffff';


	tableHolder.appendChild(table);
	territoryInfo.appendChild(tableHolder);
	
	// setup report header row
	headNameArray = ['Name','Contact','Address','Location','Bounding Box','Code','Layer','Polygon','Att Name','Att Code','SRS','File','Date Entered','Abstract/Description','Fill Colour','Fill Opacity','Border Colour','Border Thickness'];
	
	// Now go and build the report header
	if(browser == 'msie') {addRow1(table, 'head', headNameArray, '')	;} 
	else{	addRow2(table, 'head', headNameArray, '')	;}

	for (var j=0; j<xmlFiles.length; j++)
	{
		// get the a file's attribute information
		getTheTerritory(territoryFolder+xmlFiles[j])
		propVal=
		[
			territoryName,
			territoryContact,
			territoryAddress,
			territoryLocation,
			territoryBbox,
			territoryCode,
			territoryDataLayer,
			territoryPolygonName,
			territoryAttName,
			territoryAttCode,
			territorySrs,
			territoryFileName,
			territoryDateEntered,
			territoryAbstract,
			territoryFillColor,
			territoryFillOpacity,
			territoryStrokeColor,
			territoryStrokeWidth,
			territoryListOfAreas
		]

		// setup the link for this row
		link='terr:0:showTerritory:'+territoryFolder+territoryFileName; 

		// send each row to the report
		if(browser == 'msie') {addRow1(table, 'data', propVal, link)	;} 
		else{	addRow2(table, 'data', propVal, link)	;}

	}
} 

function setPolypikaLayer(collLayerName)
{
	// set the header name
	var selectMethodName = document.getElementById('polypikaSelectMethod');
	var text = document.createTextNode(collLayerName+' Select Method:');
	selectMethodName.appendChild(text);
	selectMethodName.style.textTransform = 'capitalize';
	var includeMethodName = document.getElementById('polypikaInclusion');
	var text = document.createTextNode(collLayerName+' Inclusion Options:');
	includeMethodName.appendChild(text);
	includeMethodName.style.textTransform = 'capitalize';
}

function exitPolypika()
{
	deletePolypikaSelection();				
	removeAllControls();
	
	if(userdata)
	{
		showUserPoints(geocodedFile);
		initializeForms();
	}
	initialiseTerritory()
	resetZlevels();
	//alert('reactivating upload control'); activateControls();

}

function deletePolypikaSelection()
{
	document.getElementById("polypikaHolder").style.display="none";
	document.getElementById("enterDigitMode").title = 'Enter Polypika Mode';
	document.getElementById("enterDigitMode").value = 'Enter Polypika Mode';
	document.getElementById("enterDigitMode").className = 'buttup';
	document.getElementById('enterDigitMode').blur();
	
	if(filePresent(newSldFile) )	{	deleteit(newSldFile); }	
	if(click != null){click.destroy(); }

	// set mode back to non polypikaMode
	removeTerritory();

	// reset back to all territories if set
	//showHideAllTerritories('showAllTerr');
}

function deleteTerritory()
{
	// check that the user wants to delete this permnanantly
	if(confirm ('Do you wish to PERMANENTLTY DELETE the Territory from Disk - this cannot be undone?'))
	{
		// delete the file from the folder directory
		//alert ('deleting '+territoryFolder+territoryFileName)
		deleteit(territoryFolder+territoryFileName);

		// rebuild the territories selection panel
		makeTableSelectControl(territoryFolder, 'territoriesList', 'Territory', 'territoryName', 'terr');
		//makeSelectTerritoriesControl(territoryFolder, 'territoriesList', 'Territory', 'territoryName');
		//document.getElementById('listTerr').title = 'Hide Report';
		
		// remove this deleted territory
		removeTerritory();

		
	}
}
function removeTerritory()
{
	if(territory) {territory.setVisibility(false); }
	if(terrMarkers){terrMarkers.setVisibility(false); }
	if(terrLabels) {terrLabels.setVisibility(false); }
	initialiseTerritory();
	
}


function initialiseTerritory()
{
	makeTableSelectControl(territoryFolder, 'territoriesList', 'Territory', 'territoryName', '', 'terr');
	
	// first set to all territories as default
	allTerritories = true;
	showHideAllTerritories("showAllTerr");
	
	// delete any previous sld file and any similar cache 
	if ( newSldTerritory )	
	{	
		deleteit(newSldTerritory);		
		var cacheDir = newSldTerritory.split('sld/')[1];
		purgeDrapeCache(cacheDir, '')
	}

	// deactivate the territory controls
	deactivateTerritoryControls();

	// set all form values to empty
	document.getElementById('nameOfTerritory').value = '';
	document.getElementById('contactOfTerritory').value = '';
	document.getElementById('addressOfTerritory').value = '';
	document.getElementById('dbCodeOfTerritory').value = '';
	document.getElementById('abstractOfTerritory').value = '';
	//document.getElementById('areasOfTerritory').value = '';
	//document.getElementById('showAllTerr').checked = false;

	// reset the activelayer control
	document.getElementById('actLayOptions').options[0].selected=true;
	var selectObject = document.getElementById('actLayOptions');
	activeLayerName = selectObject.options[selectObject.selectedIndex].value;
	//alert('active layer name in initialise Territory = '+activeLayerName)

	// reset all layers in the list of territories panel
	for (var i=0; i<LayerObj.length ; i++)
	{
		document.getElementById('layers:'+i).checked = false;
		document.getElementById('label:'+i).checked = false;
		document.getElementById('arow:'+i).className = 'unselectedItem';
	}

	// clear out the current territory window and reset all function buttons
	textDisplay('selectedTerr', '');
	//territoryNames = [];
	changeMode('newTerr');

	//mouseup('newTerr');
	mousedown('newTerr');
	//mouseup('grabPolygons');
	mouseup('removeTerr');
	mouseup('listTerr');
	mouseup('saveTerr');
	mouseup('zoomToTerr');
	mouseup('themeTerr');
	mouseup('homeTerr');
	mouseup('labelTerr');
	polypikaMode = false;

	//resetPolypikaForm();
	territoryBounds = null;
	activeLayerName = null;


	//initialiseNewTerritory();

	if(vectorLayer)	{vectorLayer.destroy();}
	//removeTerrMarkers();
	newSldTerritory = null;
	currentTerrRow = -1;
	
	currentTerritoryFile = '';
	//if(polyDragControls)	{	map.removeControl(polyDragControls);}

	// make sure Territoruies folder is reset
	//resetZlevels();
	// setup the search engine again
	//alert('rebuiding search engine 2')
	prepareTerritorySearch();

	
}
function initialiseNewTerritory()
{
	// make sure the data entry variables are reset
	territoryName = '';
	territoryContact = '';
	territoryAddress = '';
	territoryLocation = '';
	territoryBbox = '';
	territoryCode = '';
	territoryDataLayer = '';
	territoryPolygonName = '';
	territoryAttName = '';
	territoryAttCode = '';
	territorySrs = '';
	territoryFileName = '';
	territoryDateEntered = '';
	territoryAbstract = '';
	territoryFillColor = '';
	territoryFillOpacity = '';
	territoryStrokeColor = '';
	territoryStrokeWidth = '';
	territoryListOfAreas = '';
	sqlString = '';
	territoryNames =[];
	territoryFilter = [];
	territoryBboxes = [];
	currentTerrRow = -1;

	// reset the form
	document.getElementById('nameOfTerritory').value = '';
	document.getElementById('contactOfTerritory').value = '';
	document.getElementById('addressOfTerritory').value = '';
	document.getElementById('dbCodeOfTerritory').value = '';
	document.getElementById('abstractOfTerritory').value = '';
	
	// reset anything from OpenTerritory
	document.getElementById('actLayOptions').options[0].selected=true;
	document.getElementById('actLayOptions').disabled=false;
	textDisplay('selectedTerr', '');
	checkRemoveObject('tableOfAreas');

	// make sure that the activeLayer is set to nothing in layers panel
	turnOffActiveLayer();
	deactivateTerritoryControls();
	//setRowToSelected(-1);
	//alert('territory Name 3 = '+territoryName)
	//setTerritoryMenu();
	
	// make sure the homebase and label buttons are off
	if(allTerritories)
	{
		//toggleHome('homeTerr');
		document.getElementById('homeTerr').style.display = 'block';
		//toggleLabels('labelTerr');
		document.getElementById('labelTerr').style.display = 'block';
	}
	else
	{
		//toggleHome('homeTerr');
		document.getElementById('homeTerr').style.display = 'none';
		//toggleLabels('labelTerr');
		document.getElementById('labelTerr').style.display = 'none';
	}
	if(terrMarkers){terrMarkers.setVisibility(false); }
	if(terrLabels) {terrLabels.setVisibility(false); }
	if(vectorLayer)	{vectorLayer.destroy(); vectorLayer = null;}
	
/*************	// now reset the selected territory to off
	for (var i=0; i<noOfFiles ; i++)
	{	var Id = 'terr_rowNo:'+i;
		document.getElementById(Id).className='unselectedItem';
		//document.getElementById(Id).style.border='1px solid red';
	}
*/	
	
	// if any popups there kill them off
	if(terrPopup)
	{	map.removePopup(terrPopup);
		terrPopup = null;
	}

	// turn off any current territory
	if(territory) {territory.setVisibility(false); }
	
	// remove circles layer if already there
	if(vectorLayer4){  vectorLayer4.destroy(); vectorLayer = null;}
	
	// remove the innerboudaries from map
	if(innerBoundaries) {innerBoundaries.setVisibility(false);}

	// now set the territory manager to be in maximum state
	minmaxTerritoryManager('min');

	// check to see if there are any files in directory
	//alert(territoryFolder)
	ajaxRequest = getListOfFiles(territoryFolder);
	//var xmlFiles = ajaxRequest.responseText.split("|");
	//alert(ajaxRequest.responseText)
	if(ajaxRequest.responseText == 'error')
	{ 
		// switch the buttons and form to the Input screen
		//document.getElementById('listTerr').style.display='none';
		document.getElementById('openTerr').style.display='none';
	}
	//alert('init done')
}

function removeTerrMarkers()
{
	if(terrLabels)
	{	
		map.removeLayer(terrLabels);
		terrLabels = null;
		if(terrLabels){terrLabels.destroy();}		
		mouseup('labelTerr');
		document.getElementById('labelTerr').title='show Territory labels';
	}

	if(terrPopup)
	{	map.removePopup(terrPopup);
		terrPopup.destroy();
		terrPopup = null;
	}

	if(terrMarkers)
	{	map.removeLayer(terrMarkers); 
		terrMarkers.destroy(); 
		terrMarkers = null;
		mouseup('homeTerr');
		document.getElementById('homeTerr').title='show home base';
	}

}
function resetPolypikaButton()
{
	document.getElementById("polypikaHolder").style.display="none"; 
	document.getElementById("enterDigitMode").title="Re-enter Polypika Mode"; 
	document.getElementById("enterDigitMode").className="buttdown"; 
	document.getElementById("enterDigitMode").value="Re-enter Polypika Mode";
	document.getElementById('enterDigitMode').blur();
}

function resetPolypikaForm()
{
	if(document.getElementById("polypikaRectWidth"))
		{document.getElementById("polypikaRectWidth").disabled='disabled'; }
	if(document.getElementById("polypikaRectWidth"))
		{document.getElementById("polypikaRectWidth").style.backgroundColor='#c3c3c3'; }

	if(document.getElementById("polypikaRectHeight"))
		{document.getElementById("polypikaRectHeight").style.backgroundColor='#c3c3c3'; }
	if(document.getElementById("polypikaRectHeight"))
		{document.getElementById("polypikaRectHeight").disabled='disabled'; }
	
	if(document.getElementById("polypikaCircleRad"))
		{document.getElementById("polypikaCircleRad").disabled='disabled'; }
	if(document.getElementById("polypikaCircleRad"))
		{document.getElementById("polypikaCircleRad").style.backgroundColor='#c3c3c3'; }

	if(document.getElementById("polypikaGeomkey"))
		{document.getElementById("polypikaGeomkey").checked='checked'; }
	if(document.getElementById("polypikaGeomkey"))
		{document.getElementById("polypikaGeomkey").disabled='disabled'; }
	if(document.getElementById("polypikaKeygeom"))
		{document.getElementById("polypikaKeygeom").disabled='disabled'; }
	if(document.getElementById("polypikaKeygeom"))
		{document.getElementById("polypikaKeygeom").checked=false; }

	/*
	if(document.getElementById("sendButt4"))	
		{document.getElementById("sendButt4").disabled='disabled'; }
	if(document.getElementById('sendButt4'))
		{document.getElementById('sendButt4').title='Local Government Area select mode'; }
	*/	
	if(document.getElementById("polypikaIncludeType"))
		{document.getElementById("polypikaIncludeType").disabled=false; }

	if(document.getElementById("lgaList:4"))
		{document.getElementById("lgaList:4").disabled='disabled';}

	// remove any searching vectors
	if(vectorLayer){vectorLayer.setVisibility(false);}
}
function drawCircle(centX, centY, radius)
{
	//alert(radius)
	centX = parseFloat(centX);
	centY = parseFloat(centY);
	allX = new Array();
	allY = new Array();
	var pointList = new Array();
	var k=0;
	
	// now calculate the points around the circle perimeter
	for(var i=0 ; i<360 ; i=i+6)
	{
		
		allX[k] = centX + parseInt(Math.sin(i*Math.PI/180)*radius);
		allY[k] = centY + parseInt(Math.cos(i*Math.PI/180)*radius);
		//alert(allX[k]+", "+allY[k])
		k++
	}
	
	// make sure last point and first point are the same
	if(allX[0] != allX[allX.length-1] || allY[0] != allY[allX.length-1])
	{  allX[allX.length-1] = allX[0]; allY[allX.length-1] = allY[0];}

	// stuff all points into an array
	for (var i=0 ; i<allX.length ; i++)
	{	pointList.push(new OpenLayers.Geometry.Point(allX[i], allY[i]));	}
	
	//now commit the geometry to the layer
	var parcel01= new OpenLayers.Geometry.LinearRing(pointList);
	var feature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Polygon([parcel01]));
	vectorLayer4.addFeatures(feature);	
	
}

function showConcentricCircles(number, increments)
{
	var title = document.getElementById('circlesTerr').title;
	if(title == 'Show 10Km Radial Distances')
	{			
		// Make sure vector layer is removed from map
		if(vectorLayer4){ vectorLayer4.destroy(); vectorLayer4 = null;}

		// initialise a new vector layer
		vectorLayer4 = new OpenLayers.Layer.Vector("Circles", {style: circles});
		vectorLayer4.addOptions({reproject: true, visibility:true, reaspect: false, transparent: true});

		// draw the concentric circles around the baseCoords point
		increments = parseFloat(increments);
		for(var i=0; i<number; i++)
		{
			var radius = (i * increments) + increments;
			drawCircle(baseCoords[0], baseCoords[1], radius)
		}
		// now add the new vector layer to the map
		map.addLayer(vectorLayer4);	
		resetZlevels();
		if(vectorLayer4) {vectorLayer4.setZIndex(map.Z_INDEX_BASE['Popup'] -4010);}
	
		// reset the button
		document.getElementById('circlesTerr').title = "Hide 10Km Radial Distances";
		
	}
	else if(title == 'Hide 10Km Radial Distances')
	{	
		// set visibility of the concentric circles vector layer to off
		vectorLayer4.setVisibility(false);
		
		// reset the button
		document.getElementById('circlesTerr').title = "Show 10Km Radial Distances";
		mouseup('circlesTerr');
	}
}

function showInnerTerritory()
{
	var title = document.getElementById('innerTerr').title;
	if(title == 'Show Inner Boundaries')
	{	
		// build and apply the new SLD against the innerBoundaries layer
		if(innerBoundaries == null) {createInnerBoundaries();}
		highlightInner(sqlString, territoryName);
		
		// reset the button
		document.getElementById('innerTerr').title = "Hide Inner Boundaries";
		//mousedown('innerTerr');
	}
	else if(title == 'Hide Inner Boundaries')
	{	// set visibility of the innerBoundaries to off
		innerBoundaries.setVisibility(false);
		
		// reset the button
		document.getElementById('innerTerr').title = "Show Inner Boundaries";
		mouseup('innerTerr');
	}
}

// ----- this is a generic routine to use SLDs to highlight a collection of polygons defined in sqlString ----//
function highlightInner(sqlString, territoryName)
{
	genLoadStatus('Loading "'+territoryName+'"', false, '');
	if ( innerSldTerritory != null )	
	{	deleteit(innerSldTerritory);		// cleanup any previous SLD file
		var cacheDir = innerSldTerritory.split('sld/')[1];
		purgeDrapeCache(cacheDir, '');
	}
	
	// Now create a new SLD for this particular LGA boundary
	var pathParts = terrPathSld.split('/');
	newTempSldPath = pathParts[0]+'/';
	var fileParts = pathParts[1].split('.');
	newTempSldFile = 'newSld_'+fileParts[0]+'_'+new Date().getTime()+'.xml';
	innerSldTerritory = 'sld/'+ newTempSldPath + newTempSldFile;
	
	//alert('layer = '+territoryDataLayer)
	// set parameters to build a new SLD via makeNewSldFile.php
	var query = "?file="+innerSldTerritory;
	query+= "&layer="+territoryDataLayer;
	query+= "&title="+territoryAttName;
	query+= "&name="+territoryAttName;
	query+= "&abstract="+territoryAbstract;
	query+= "&att="+territoryAttCode;
	query+= "&filter="+sqlString;
	//query+= "&patt="+areaFillBase+"blackdiagonal.png";
	//query+= "&form=image/png";
	query+= "&form=";	
	query+= "&label=";	
	query+= "&bcol=FFFFFF";
	query+= "&fcol=transparent";
	query+= "&opac=0.0";
	query+= "&line=1";
	query+= "&update=false";
	query+= "&solid=false";
	// create a new temporary Highlighting SLD
	var request = applicationBase + "inc/makeNewSldFile_new.php";
	var aquery = query.split('?')[1];
	//alert(request+query)
	makeFile(request, aquery,  'false', 'POST')
	
	// Assuming the Sld was created now swap it for the empty Sld
	var newSld = applicationBase+"inc/"+innerSldTerritory;
	
	// if OK then go ahead and replace the old territory filter with the new one
	if(territoryDataLayer != '' && activelayerMatchTerritorylayer() )
	{
		// set map window over parcel boundary
		//registerLoadWheel(territory, 'loadWheelDrape');

		//alert(newSld)
		innerBoundaries.mergeNewParams({'sld':newSld});
		resetZlevels();
		innerBoundaries.setVisibility(true);
	}
	genLoadStatus('', false, '');
}

function showHidePolypikaPanel(id)
{
	// destroy the vector layer if there - it will be created again
	if(vectorLayer) 
	{	
		vectorLayer.setVisibility(false); 	
		//vectorLayer.destroy();
		//map.removeLayer(vectorLayer); 	
	}
	
	// determine which state we are switching to from title
	var status = document.getElementById(id).title;
	if(status == 'Enter Polypika Mode' || status == 'Re-enter Polypika Mode' )
	{
		// check for an active layer set in form
		//alert('new Territory = '+newTerritory)
		if(!newTerritory)
		{	
			activeLayerName = document.getElementById('selectedTerr').value;
			//alert('active layer = '+activeLayerName)
			if (activeLayerName == '' )
			{
				alert("No Active Layer set - please chose from the 'Current Active Layer' list");
				exitPolypika();
				//disablePolypika(id);
				return;
			}
			else
			{
				// now check that activelayer and this loaded territory's layer match
				var testTerritoryLayer = territoryDataLayer.split(":")[0];
				var test = activelayerMatchTerritorylayer();
				if(test)
				{
					// all is well make sure activelayer is installed in polypika
					//territoryActive = true;
					enablePolypika();
					
					// set up polygon picking functions
					document.getElementById("polypikaHolder").style.display="block";
					document.getElementById(id).title="Exit Polypika Mode";
					document.getElementById(id).value="Exit Polypika Mode";
					document.getElementById(id).className='buttdown';
					document.getElementById(id).blur();
					//depressedDiv(id);
					polypikaMode = true;
					return;
				}
				else
				{
					territoryActive = false;
					exitPolypika();
					//disablePolypika(id);
					return;
				}
			}
		}
		else 
		{
			// when the open button has been selected get the active layer if present
			//alert('territory act = '+territoryActive)

			if(territoryActive)
			{
				var selectObject = document.getElementById('actLayOptions');
				activeLayerName = selectObject.options[selectObject.selectedIndex].value;
				//alert('active Layer Name = '+activeLayerName);
			}
			
			// validate and get Form data
			if(!checkMandatoryItems()){ return;}

			// if the territory location has not been created then create it here
			if(territoryLocation == '')
			{
				// geocode the new address
				geocoder.getLocations(territoryAddress, function (result)
				{ 
					// Only one in collection so plot it only
					if(result.Placemark)
					{
						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];
							}
	
							// create the vector marker for the territory Home location
							makeHomeMarker(true);

							// zoom into the new base address
							map.setCenter(new OpenLayers.LonLat(baseCoords[0], baseCoords[1]), 10);
						}
						else{alert ('unable to geocode this new address ('+territoryAddress+') - try more detail in the address');}
					}
					else
					{ alert('Unable to geocode this new address ('+territoryAddress+') - try more detail in the address');}
				});
			}

			// get the territory name before collecting polygons
			//newTerrName = terrHandle;
			//newTerrName = document.getElementById('nameOfTerritory').value;
			/*if(newTerrName == '')
			{
				alert('Please enter the Territory Name');
				document.getElementById('nameOfTerritory').focus();
				return;
			}*/
			// get the Contact Name
			// move seleceted file name up into current Territory display window
			textDisplay('selectedTerr', terrHandle);
			
			// all is well make sure activelayer is installed in polypika
			//territoryActive = true;
			enablePolypika();
			
			// set up polygon picking functions
			document.getElementById("polypikaHolder").style.display="block";
			document.getElementById(id).title="Exit Polypika Mode";
			document.getElementById(id).value="Exit Polypika Mode"
			document.getElementById(id).className='buttdown';
			document.getElementById(id).blur();
			//depressedDiv(id);
			return;
		}
	}
	else
	{	
		if(confirm ('Do you wish to exit Polypika mode without saving your changes?'))
		{	
			exitPolypika();
		}
	}
}

function enablePolypika()
{
	// first make sure the Home Base select control is deactivated
	removeMarkerSelectControls();

	// make all the buttons selectable
	if(document.getElementById('ppsp'))
	{
		document.getElementById('ppsp').disabled = false;
		document.getElementById('ppsd').disabled = false;
		document.getElementById('pppt').disabled = false;
		document.getElementById('ppci').disabled = false;
		document.getElementById('ppfp').disabled = false;
		document.getElementById('ppdb').disabled = false;
		polypikaMode = true;
	}
}
function disablePolypika(id)
{
	//if(terrSelectControl){alert('activating terrSelectControl'); map.terrSelectControl.activate();}
	//alert('id = '+id)
	//alert(document.getElementById(id).title);

	if(document.getElementById('ppsp'))
	{
		document.getElementById('ppsp').disabled = 'disabled';
		document.getElementById('ppsd').disabled = 'disabled';
		document.getElementById('pppt').disabled = 'disabled';
		document.getElementById('ppci').disabled = 'disabled';
		document.getElementById('ppfp').disabled = 'disabled';
		document.getElementById('ppdb').disabled = 'disabled';
		document.getElementById(id).title="Enter Polypika Mode";
		//alert(document.getElementById(id).title);
		document.getElementById("polypikaHolder").style.display="none";
		polypikaMode = false;
		normalDiv(id);
		
		// refresh the home location with select controls active
		//alert(document.getElementById('homeTerr').title);
		if(document.getElementById('homeTerr').title == 'show home base'){	makeHomeMarker(true);}
		
		// remove the vector layer used for search box and remove polypika selection controls
		if(vectorLayer)	{	vectorLayer.setVisibility(false); 	}
		removeAllControls();
		reinstateMarkerSelectControls();
		activateGfiClickControl();
		//resetZlevels();
	}
}
function minmaxTerritoryManager(ind)
{
	if (ind == 'min')
	{
		if(!territoryActive)
		{
			document.getElementById('sidebar:6').style.height='370px';
			document.getElementById('content:6').style.height='350px';
			document.getElementById('territories').style.height='330px';
			document.getElementById('currentTerritoryData').style.display = 'none';
		}
	}
	else if(ind == 'max')
	{
		document.getElementById('sidebar:6').style.height='610px';
		document.getElementById('content:6').style.height='590px';
		document.getElementById('territories').style.height='570px';
		document.getElementById('currentTerritoryData').style.display = 'block';
	}
}
//----------- main function to control polygon picking -----------------//
function enterPolyPikaPanel()
{
	document.getElementById("polypikaHolder").style.display="none"; 
	document.getElementById("enterDigitMode").title="Re-enter Polypika Mode";			
	document.getElementById("enterDigitMode").value="Re-enter Polypika Mode";  
	document.getElementById("enterDigitMode").className = "buttdown";  
	getPolypikaObjects();
}

function getPolypikaObjects()
{
	// check active layer is set
	var actLay = document.getElementById('actLayOptions');
	//alert(actLay.options[actLay.selectedIndex].value)
	if(actLay.options[actLay.selectedIndex].value == 'No Active Layer' )
	{	alert('Active Layer must be selected');
		document.getElementById('actLayOptions').focus();
		return;
	}
	
	// remove all previously active polygon selection controls
	if(circClick) {circClick.destroy();}
	if(rectClick) {rectClick.destroy();}
	if(drawControls) {drawControls.destroy();}
	removeMarkerSelectControls();
	removeAllControls();
	//if(vectorLayer) {	map.removeLayer(vectorLayer); 	}
	//if(vectorLayer) {	vectorLayer.destroy(); 	}
	if(vectorLayer)	{	vectorLayer.setVisibility(false); 	}
	zoomToSelectBox = false;


	genLoadStatus('Fetching Polygons ...', true, '');
	var selectObject = document.getElementById('polypikaIncludeType');
	searchType = selectObject.options[selectObject.selectedIndex].value;

	//alert('searchType = '+searchType)
	polypikaMode=true; PickMode=false;

	// deactivate the upload points controls
	if(userMarkers)
	{
		//alert('removing upload DRAG control')
		var conts=['Drag'];
		deactivateControls(conts, 'territoryUtils:getPolypikaObjects');
		toggleDragging('dragMarker');
	}
	//drapeAtts = Datts;  
	currentSldFile = layLineSld;
	//alert('current Sld File = '+currentSldFile)
	layerName = activeLayerName+":ABS";
	//alert('layer name = '+layerName)
	
	// now execute the appropriate selected method for selecting data
	currentFile = currentSldFile;
	report = false;
	list = false;
	addRemove = false;
	radius = '';
	width = '';
	height = '';
	dragable = false;
	
	// need to get the attributes of the active layer
	getPolypikaAttributes();
	
	// if the territory home base button is depressed - popit and remove home from map
	if(terrMarkers) 
	{	
		terrMarkers.setVisibility(false);
		var homeButt = document.getElementById('homeTerr');
		homeButt.title = 'show home base';
		mouseup('homeTerr');
		//resetZlevels();
	}
	//terrMarkers.removeLayer();
	//terrMarkers.destrory();
	resetZlevels();
	
	// set up different switches as required
	if(document.getElementById('ppsp').checked)
	{
		// single point select - default
		width = 1;
		height = 1;
		searchType = 'Contains';
		addRemove = true;
		//alert('about to enter getfeatureByPolygon')
		//getfeatureByPolygon(drapeAtts,  currentSldFile, report,  list, width, height, radius, false, false, searchType, dragable);
		getfeatureByPolygon(drapeAtts,  currentSldFile, report,  list, width, height, radius,  searchType, false, false, dragable);
	}
	else if(document.getElementById('ppsd').checked)
	{
		// shift-drag feature
		dragable=true;
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, false,  dragable);
	}
	else if(document.getElementById('pppt').checked )
	{
		// rectangle box
		width  = document.getElementById('polypikaRectWidth').value;
		height = document.getElementById('polypikaRectHeight').value;
		dragable=true;
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, false,  dragable);
	}
	else if(document.getElementById('ppci').checked )
	{
		// circle
		radius = document.getElementById('polypikaCircleRad').value;
		dragable=true;
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, false, dragable);
	}
	else if(document.getElementById('ppfp').checked )
	{
		 // freehand
		dragable=true;
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, true, false, dragable);
	}
	else if(document.getElementById('ppdb').checked )
	{
		// database polygon feature
		if(document.getElementById('polypikaKeygeom').checked)
		{	searchType='polypikaLgaKey';	}
		getfeatureByPolygon(drapeAtts,  currentSldFile, report, list, width, height, radius, searchType, false, true, dragable); 
	}
	opacityValue2=1.0;
	opacityValue=1.0;
}

function getPolypikaAttributes()
{
	//allAtts = false;
	// initialise Target Arrays
	attNames = new Array();
	//targetFilter = new Array();

	// first get the XML that defines all the attributes for the layer
	//alert('layer name = '+layerName)
	ajaxRequest = getAttributeSchema(meshBlocksBase, layerName);
	if(ajaxRequest.status !== 200)	{return;}

	// determine the attribute name for the unique key of target layer
	getPolygonCodeUsedInTerritory(ajaxRequest);
	//alert('attNames = '+attNames);

}

// function to pick off all attributes in DescribeFeature XML file and populate arrays	
function getPolygonCodeUsedInTerritory(ajaxRequest)
{
	genLoadStatus('Getting Layer Schema ...', true, '');
	// apply XML browser difference here
	var prefix='xs:';
	if ((browser =='firefox' && version == '2') || (browser == 'safari'))
	{	prefix='';	}
	
	// check to see if this request is not in error
	if(!checkForError(ajaxRequest)){ return false;}
	
	// pick off the named layer
	var elementTop = ajaxRequest.responseXML.getElementsByTagName(prefix+"element");
	//alert(elementTop[0].getAttribute('name'))
	territoryDataLayer = elementTop[0].getAttribute('name');
	if(territoryDataLayer.split(':').length <= 1){territoryDataLayer = territoryDataLayer+":"+dataStore;}

	//alert('territory data layer = '+territoryDataLayer);
	//alert('dataStore = '+dataStore)

	// now get the attributes and their data types into arrays
	var complexType = ajaxRequest.responseXML.getElementsByTagName(prefix+"complexType");
	var elements = complexType[0].getElementsByTagName(prefix+"element");		
	var k=0; 
	nameItemNumber = 0;
	codeItemNumber = 0;
	codeFound = false;
	nameFound = false;

	// loop through all Element tags
	for (var j=0 ; j<elements.length ; j++ )
	{
		// look for 'type' Attribute in elements
		var typeElement = elements[j].getAttribute('type');
		
		//alert ("typeElement = "+typeElement)
		if (typeElement == null || typeElement == 'undefined' )
		{
			// process standard formats
			var attNam = elements[j].getAttribute('name');
			var attNameParts = attNam.split('.');
			if(attNameParts[1] != 'GEOMETRY')  // should be a redundant check
			{
				attNames[k] = attNameParts[1];
				if(territoryAttName != '' && territoryAttCode !='')
				{	
					if(attNames[k] == territoryAttName) {nameItemNumber = k;}
					if(attNames[k] == territoryAttCode) {codeItemNumber = k;}
				}
				else
				{
					// look for the first CODE and NAME arttributes
					if(!codeFound)
					{
						var parts = attNames[k].split('_CODE');
						if(parts.length > 1) {codeItemNumber = k; codeFound = true;}
					}
					if(!nameFound)
					{
						var parts = attNames[k].split('_NAME');
						if(parts.length > 1) {nameItemNumber = k; nameFound = true;}
					}
					
				}
				k++
			}
		}
	}
	// check that CODE and NAME are similar if not make NAME same as CODE
	var typeCode = attNames[codeItemNumber].split("_")[0];
	var typeName = attNames[nameItemNumber].split("_")[0];
	if(typeCode != typeName){nameItemNumber = codeItemNumber;}
	
	//alert('name = '+nameItemNumber)
	//alert('code = '+attNames[codeItemNumber])
	territoryAttCode = attNames[codeItemNumber];
	territoryAttName = attNames[nameItemNumber];
	
	// check that the Name and code logically match
	var dataElementTypeCode = territoryAttCode.split('_')[0];
	var dataElementTypeName = territoryAttName.split('_')[0];
	genLoadStatus('', false, '');
	if(dataElementTypeName == dataElementTypeCode){ return;}
	else 
	{	territoryAttName = territoryAttCode;	return;}
}

//------------------------ generic listing function ------------------------
function addToTerritory(ajaxRequest, features, serviceBase, dataStore, typeName)
{
	//alert('mode = '+newTerritory)
	//alert(territoryNames);
	if (features.length == 0) {alert("No Features in XML"); return false;}
	
	// if this is a temporary edited SLD file strip back to real file in control file
	var SLD = currentSldFile
	var fileParts = currentSldFile.split('_new');
	if(fileParts.length > 1)
	{	SLD = fileParts[0]+'.xml';	}

	//alert(features.length)
	data = features[0].getElementsByTagName('gml:posList');
	geom = data[0].firstChild.nodeValue;
	//alert('debug: '+geom)
	var ordinates = geom.split(' ');
	//alert('ords = '+ordinates.length);
	//makePopup(ajaxRequest,'500', '500', 'both')

	// get the attribute contents for each attribute requested in the roport
	// First parse the resultant xml delivered DOM object
	if (!ajaxRequest.responseXML.getElementsByTagName("FeatureCollection"))
	{	alert("no featureCollection returned in XML"); return false;}
	var featureCollection = ajaxRequest.responseXML.getElementsByTagName("FeatureCollection");

	//alert('collection length = '+featureCollection.length)
	if (featureCollection.length == 0) {alert("Zero features found"); return false;}
	var featureSet = featureCollection[0].getElementsByTagName("FeatureSet");

	//alert ('number in featureSet = '+featureSet.length)
	if (featureSet.length == 0) {alert("No Features in XML"); return false;}
	var typename = featureSet[0].getAttribute('name');
	var definition = featureSet[0].getElementsByTagName("Properties");
	var properties = definition[0].getElementsByTagName("Property");
	//var features = featureSet[0].getElementsByTagName("Feature");
	// Now run through all the Features picking off attributes	
	
	// process each feature caught in GetFeature request return
	//alert('there are '+features.length+' featured here');
	if(territoryAttCode == '') {getPolypikaAttributes();}
	
	var searchName= '';
	genLoadStatus('', false, '');
	tempcontent = [];
	sqlString = '';	

	// loop through all the polygons returned and add to the arrays
	for (var b = 0; b < features.length; b++)
	{		
		// report on the progress of the process
		var percentDone = parseInt( Math.round((b+1)/features.length*100));
		genLoadStatus(percentDone+'% Complete ...', false, percentDone);
		
		// get the Value tags
		var tempcontent = new Array();
		var propertyVals = features[b].getElementsByTagName('Value');
		if (propertyVals.length == 0 ){return false;}

		// now save all the PropertyDefs and PropertyVals into the collection/reporting arrays	
		var gotone=false;

		for (var xx=0; xx<properties.length; xx++)
		{
			if(properties[xx].getAttribute('name') == 'GEOMETRY')
			{
				defs[xx] = properties[xx].getAttribute('name');
				tempcontent[xx] = '';
			}
			else
			{
				defs[xx] = properties[xx].getAttribute('name');
				tempcontent[xx] = propertyVals[xx].firstChild.nodeValue;
				tempcontent[xx] = tempcontent[xx].replace(/,/g, "");	
				if(defs[xx] == territoryAttCode) { searchName = tempcontent[xx]; }
			}	
		}
		
		// now determine BBox of this polygon 
		polyBbox = getPolygonBbox2(dataStore, typeName, account, '', '', territoryAttCode, searchName)
		polyBbox = polyBbox.toString();
		
		// add this polygon to the collection
		polyBbox = polyBbox.replace(/ /g,":");
		addPolygonToTerritory(tempcontent[codeItemNumber+1],tempcontent[nameItemNumber+1], polyBbox, false);
	}

	// populater the area name with the list for this Territory
	populateAreasIncluded(territoryNames);

	// convert array to a comma sep string
	sqlString = territoryFilter.toString();
	//alert('sqlString = '+sqlString)

	// calculate a new BBox for Territory
	getNewTerrBbox(territoryBboxes);
	//alert('sql String = '+sqlString)

	// make sure the selected Territory is now set on select menu
	//alert('territory Name 4= '+territoryName)
	setTerritoryMenu();

	// now highlight the selected Territory
	//alert('territoryName = '+territoryName)
	highlightTerritory(sqlString, territoryName);
	genLoadStatus('', false, '');
	return; 
}


function getNewTerrBbox(territoryBboxes)
{
	// get a new BBox of the updated Territory
	var loX = 99999999999999.0; 
	var loY = 99999999999999.0; 
	var hiX = -99999999999999.0; 
	var hiY = -9999999999999999999.0;
	//alert('polygons in Terr = '+territoryBboxes.length)
	for(var i=0; i<territoryBboxes.length ; i++)
	{
		//alert('additional polygon BBox = '+territoryBboxes[i])
		var parts = territoryBboxes[i].split(':');
		//alert(parts)
		
		// draw each polygon's BBox (debug)
		//drawBbox(parts[0],parts[1],parts[2],parts[3],"cyan", false);
		
		// calculate new BBox of this Territory
		if(parseFloat(parts[0]) < loX){loX = parts[0]; }
		if(parseFloat(parts[1]) < loY){loY = parts[1]; }
		if(parseFloat(parts[2]) > hiX){hiX = parts[2]; }
		if(parseFloat(parts[3]) > hiY){hiY = parts[3]; }
	}
	// now overwrite the Territory Bounds with the new bounds
	territoryBounds = null;
	territoryBounds = new OpenLayers.Bounds(loX,loY,hiX,hiY);
	//drawBbox(loX,loY,hiX,hiY,'magenta', true)
}

// ------ This will take the captured polygon and add to current collection -----
function addPolygonToTerritory(newPolygonCode, newPolygonName, polyBbox, duplicatesAccepted)
{	
	// check to see if this polygon is already in filter list
	var found = false;
	var removedPolygon = false;

	if(territoryFilter.length > 0)
	{	
		// search for this polygon code in existing array of polygons
		for (var i=0; i<territoryFilter.length ; i++ )
		{
			// if we have a match and allow duplicates then add this polygon to territory
			if (territoryFilter[i] == newPolygonCode)
			{
				found = true;
				// check if this is a singlePoint select then we can remove it from array
				if(addRemove)
				{	// remove this from the array
					territoryFilter.splice(i,1);
					territoryNames.splice(i,1);
					territoryBboxes.splice(i,1);
					//removedPolygon = true;
				}
				// if duplicates allowed then add to array
				if(duplicatesAccepted)
				{	// add the duplicate
					territoryFilter.push(newPolygonCode);
					territoryNames.push(newPolygonName);
					territoryBboxes.push(polyBbox);
					//removedPolygon = false;
				}
			}
		}
	}
	// if not found then add it here
	if(!found) 
	{	
		territoryFilter.push(newPolygonCode);
		territoryNames.push(newPolygonName);
		territoryBboxes.push(polyBbox);
		//removedPolygon = false;
	}
}

function getPolygonBbox2(dataStore, layer, accCode, realX, realY, parcelNameAtt, parcelName)
{
	// either by a coordinate point in polygon search (realX and realY != ''
	// or by a unique identifier in parcelNameAtt & parcelName
	var tempFile = "data/tempFile_"+new Date().getTime()+".xml";
	
	//params = "url=http://brad.www.numaps.com.au/nuserv.cfm";
	params = "request=getFeature";
	params += "&service=WFS";
	params += "&srs="+srs;				// e.g. EPSG:900913
	//params += "&output=BXFS";
	params += "&OUTPUTFORMAT="+outFormat;
	params += "&datastore="+dataStore;	// e.g. ABS
	params += "&typename="+layer;		// e.g. SUBURB
	//params += "&account="+account;		// e.g. NUMAPS
	//params += "&file="+tempFile;

	if(realX != '' && realY != '')
	{
		params += "&filter=<Filter xmlns:gml='http://www.opengis.net/gml'><Contains><PropertyName>GEOMETRY</PropertyName><Point><coordinates decimal='.' cs=':' ts=' '>"+realX+":"+realY+"</coordinates></Point></Contains></Filter>";
	}
	else if (parcelName != '' && parcelNameAtt != '')
	{
		params += "&filter=<Filter><PropertyIsEqualTo><PropertyName>"+parcelNameAtt+"</PropertyName><Literal>"+parcelName+"</Literal></PropertyIsEqualTo></Filter>";
	}

	// now shoot off and get the BBox
	//alert(serviceBase+params)
	ajaxRequest = proxyRequestPhp(serviceBase, params, '', 'POST');
	var bbox = ajaxRequest.responseText;
	//alert('new BBox = '+bbox);
	//deleteit(tempFile);

	ajaxRequest = proxyRequest(params, '', 'POST');
	
	// now get the bbox from the gml
	if(ajaxRequest.status != 200)
	{	
		alert('Could not execute GetFeature request'); 
		genLoadStatus('', false, '');
		return false;
	}
	//alert('ajax status = '+ajaxRequest.status)
	
	// check to see if there are more than limit specified in 'gfiLimit' for selection area
	var featureCollection = ajaxRequest.responseXML.getElementsByTagName("FeatureCollection");
	if (featureCollection.length == 0) {return  null;}
	var featureSet = featureCollection[0].getElementsByTagName("FeatureSet");
	if (featureSet.length == 0) {return null;}
	var properties = featureSet[0].getElementsByTagName("Properties");
	var property = properties[0].getElementsByTagName("Property");	
	var features = featureSet[0].getElementsByTagName("Feature");
	
	// get BBOX location in schema
	var found=false;
	for (var i=0;i<property.length ;i++ )
	{	if(property[i].getAttribute("name") == 'BBOX'){var element = i; found = true; break;}	}
	if(found)
	{
		// now get the BBox attribute if available	
		if(features.length == 1)
		{
			// ok we now have lat/lon BBox of polygon
			var value = features[0].getElementsByTagName("Value");
			var bbox = value[element].firstChild.nodeValue;	
			
			// convert to BBox attribute value to spherical mercator if required
			if(srs == "EPSG:900913")
			{
				// get the coords from string
				var parts = bbox.split(" ");

				// convert first point
				var p = [];
				p[0] = parts[0];
				p[1] = parts[1];
				var point = geogs2google(p);
				p = decodePoint (point);
				var newBbox =  p[0]+" "+p[1];
				
				// convert second point
				var p = [];
				p[0] = parts[2];
				p[1] = parts[3];
				var point = geogs2google(p);
				p = decodePoint (point);
				bbox =  newBbox+" "+p[0]+" "+p[1];
			}
		}
		else
		{return null;	}
	}
	else
	{
		// get the BBox from the geometry
		bbox = getBbox(features);
	}
	
	return bbox;
}

//--------------- gets the bounding box of all DOM features by scanning through the geometry-----------------------
function getBbox(features)
{
	// Now scan through all features adding every Coordinate to bounds
	var prefix='gml:';
	if ((browser =='firefox' && version == '2') || (browser == 'safari'))
		{	prefix='';	}
	var pt = []; var bound =null;
	var loY=999999999; var hiY=-999999999; var loX=99999999; var hiX=-99999999;
	var points = '';
	//alert('prefix = '+prefix)
	
	var len1 = features.length;
	for (var b = 0; b < len1; b++)
	{
		// get the exterior elements only
		var element0 = prefix+'exterior';
		var exterior = features[b].getElementsByTagName(element0);
		//alert("Number of exterior elements = "+exterior.length);
		var len2 = exterior.length ;
		for (var b1=0; b1 < len2 ; b1++)
		{
			// get geometry within exterior elements only
			var element1 = prefix+'LinearRing'
			var linearRing = exterior[b1].getElementsByTagName(element1);
			//alert("feature No = "+b+" exterior No = "+b1)
			//alert("Number of geometry objects in exterior element = "+linearRing.length)
			for (c = 0; c < linearRing.length; c++)
			{
				// get each linearRing from gml object
				var element2 = prefix+'posList'; 
				//alert('element2 = '+element2);
				var posList = features[b].getElementsByTagName(element2);
				//alert("number of PosList = "+posList.length)
				var len3 = posList.length;
				for (var dd = 0; dd < len3; dd++)
				{
					if (browser =='firefox') { var points = posList[dd].textContent;} // handles 4096 limit in FF for variables
					else {	 var points = posList[dd].firstChild.nodeValue;}
					//alert('points string = '+points)
					pt = points.split(" ");
					//alert('No of ordinates = '+pt.length)
					var len4 = pt.length ;
					for (var ec = 0; ec < len4 ; ec=ec+2)
					{
						var Xcoord = pt[ec];
						var Ycoord = pt[ec+1]; 
						
						//alert(lat+", "+lng);
							// calculate bounding box of coords	
							if (Xcoord < loX) {loX=Xcoord;}
							if (Xcoord > hiX) {hiX=Xcoord;}
							if (Ycoord < loY) {loY=Ycoord;}
							if (Ycoord > hiY) {hiY=Ycoord;}

							//alert(" e = "+e+" coords = "+lat+", "+lon)
							//adjustBoundsExtent(lat, lng, ec);
							//bounds = new OpenLayers.Bounds(loLng,loLat,hiLng,hiLat);
					}
				}
				
			}
		}
	}
	var bbox = loX+" "+loY+" "+hiX+" "+hiY;
	// centre the map over the collection of parcels
	//bounds = new OpenLayers.Bounds(loLng,loLat,hiLng,hiLat);
	//alert(bounds.getCenterLonLat());
	//alert(map.getZoomForExtent(bounds))
	//map.setCenter(bounds.getCenterLonLat(),map.getZoomForExtent(bounds)-1);
	//map.updateSize();
	return bbox;

}
function checkMandatoryItems()
{
	// first get all the data from the form
	terrHandle = document.getElementById('nameOfTerritory').value;
	terrCont = document.getElementById('contactOfTerritory').value;
	terrAddr = document.getElementById('addressOfTerritory').value;
	territoryAddress = terrAddr;
	terrDbCode = document.getElementById('dbCodeOfTerritory').value;
	terrAbs = document.getElementById('abstractOfTerritory').value;
	terrActLay = document.getElementById('actLayOptions');

	// check that mandatory items are present
	//alert(actLay.options[actLay.selectedIndex].value)
	if(terrActLay.options[terrActLay.selectedIndex].value == 'No Active Layer' )
	{	alert('Active Layer must be selected');
		document.getElementById('actLayOptions').focus();
		return false;
	}
	if(terrHandle == '' ) 
	{	alert('Territory Name is required'); 
		document.getElementById('nameOfTerritory').focus();
		document.getElementById('nameOfTerritory').value = '';
		return false;
	}
	if(terrCont == '')
	{	alert('Territory Contact Name is required'); 
		document.getElementById('contactOfTerritory').focus();
		document.getElementById('contactOfTerritory').value = '';
		return false;
	}
	if(terrAddr == '')
	{	alert('Territory Address is required'); 
		document.getElementById('addressOfTerritory').focus();
		document.getElementById('addressOfTerritory').value = '';
		return false;
	}
	return true;

}
function saveTerritory(saveType)
{
	if(saveType == 'save')
	{
		if(!confirm ('Do you wish to PERMANENTLTY UPDATE the Territory on Disk - this cannot be undone?')){return;}
	}
	genLoadStatus('Getting Territory Data ...', true, '');
	
	// validate and get all form data
	if(!checkMandatoryItems()){ return;}
	//alert('ok')
	// make sure all other attributes are populated for New mode
	if(territorySrs == '')	{	territorySrs = srs;}
	if(territoryPolygonName == '')	
	{	
		var name = territoryDataLayer.split(':')[0];
		territoryPolygonName = capitaliseIt(name)
	}

	// make sure the address is set
	if(terrAddr != territoryAddress )
	{ 	
		territoryAddress = terrAddr; 
		territoryLocation = '';
	}
	// make sure the TerritoryName is set
	territoryName = terrHandle;

	// Turn collection name into an xml filename
	var filename = terrHandle.replace(/ /g,"_") + '.xml';
	//alert(filename)
	//if(saveType == 'save')
	//{
	//	if(!filePresent(territoryFolder+filename))
	//	{	alert('Existing File is not present.\nA new file will be created for this Terriotory.');}
	//}

	// build the parameters for makeTerritoryFile process
	var params = "?path="+territoryFolder;
	params+= "&file="+filename;
	params+= "&name="+terrHandle;
	params+= "&abs="+terrAbs;
	params+= "&cont="+terrCont;
	params+= "&code="+terrDbCode;
	
	params+= "&loc="+territoryLocation;
	params+= "&addr="+territoryAddress;
	params+= "&bbox="+territoryBounds.toBBOX();
	
	params+= "&layer="+territoryDataLayer;
	params+= "&attCode="+territoryAttCode;
	params+= "&attName="+territoryAttName;
	params+= "&srs="+territorySrs;		
	params+= "&tags="+territoryPolygonName;
	
	params+= "&fColor="+territoryFillColor;		//alert(territoryFillColor);
	params+= "&fOpac="+territoryFillOpacity;	//alert(territoryFillOpacity);
	params+= "&sColor="+territoryStrokeColor;	//alert(territoryStrokeColor);
	params+= "&sWidth="+territoryStrokeWidth;	//alert(territoryStrokeWidth);
	params+= "&pSolid="+territorySolidBorder;
	
	params+= "&polyCodes="+territoryFilter.toString();
	params+= "&polyNames="+territoryNames.toString();
	params+= "&polyBboxes="+territoryBboxes.toString();

	// set up the php calling program
	var url = applicationBase+"inc/makeTerritoryFile.php";
	var aquery = params.split('?')[1];
	//alert(url+params)
	ajaxRequest = makeFile(url, aquery,  'false', 'POST')

	// set up the results message
	if(ajaxRequest.status != 200)
	{	var mess = 'Not successfully Updated ...';	}
	else 
	{
		var mess = 'Successfully Updated ...';
		if(vectorLayer)	{	vectorLayer.setVisibility(false);}
		
		// Update the allTerritoriesBounds with this BBox
		if (allTerritoriesBounds == null)
		{	allTerritoriesBounds.extend(territoryBounds);	}
		else 
		{	allTerritoriesBounds = territoryBounds;			}
	}

	// if allTerritories is set then re do the all territories
	//alert('allTerritories = '+allTerritories)
	if(allTerritories)	{	showHideAllTerritories("showAllTerr");	}

	// reload the territory from disk
	//alert('territoryActive = '+territoryActive)
	if(territoryActive) {	showTerritory(territoryFolder+filename);	}
	
	// rebuild the search engine and the foilder list
	//alert('rebuiding search engine 1')
	prepareTerritorySearch();

	//alert('current Row = '+currentTerrRow);
	makeTableSelectControl(territoryFolder, 'territoriesList', 'Territory', 'territoryName', 'terr');
	if(currentTerrRow >0 ){ resetMenuSelection(filePrefix+'_rowNo:'+currentTerrRow);	}

	genLoadStatus(mess, false, '');
	window.setTimeout(function(){genLoadStatus('', false, '');}, 5000) // delay loop for message change

	// all is well so now take it out of polypika mode
	//if(polypikaMode){	 exitPolypika();	}
}

function toggleHome(id)
{
	var homeButt = document.getElementById(id);
	if(homeButt.title == 'show home base')
	{
		if(terrMarkers) 
		{	terrMarkers.setVisibility(true);	
			homeButt.title='hide home base';
		}
		else 
		{
			makeHomeMarker(true);	
			//document.getElementById('homeTerr').style.display = 'block'
			//document.getElementById('labelTerr').style.display = 'block';
			mouseup(id);
		}
	}
	else if(homeButt.title == 'hide home base')
	{
		if(terrMarkers) {	terrMarkers.setVisibility(false);	}
		homeButt.title = 'show home base';
		mouseup(id);
		if(terrPopup != null)
		{	//map.removePopup(terrPopup);
			terrPopup.destroy();
			terrPopup = null;
		}
	}
	resetZlevels();
}

function toggleLabels(id)
{
	var labelButt = document.getElementById(id);
	if(labelButt.title == 'show Territory labels')
	{
		if(terrLabels)// create the vector marker for the territory label
		{	terrLabels.setVisibility(true);			
			labelButt.title='hide Territory labels';
		}
		else {mouseup(id);}
	}
	else if(labelButt.title == 'hide Territory labels')
	{
		if(terrLabels)	{	terrLabels.setVisibility(false);	}
		labelButt.title = 'show Territory labels';
		mouseup(id);
	}
	resetZlevels();
}

function createTerritoryLayer()
{
// make the territory layer here
	territory = new OpenLayers.Layer.WMS
	( 
		'territory', 
		meshBlocksBase, 
		{
			sld:territorySld, 
			format: drapeImage,  
			quality: 'BEST', 
			reaspect: false, 
			transparent:'true'
		},
		{ tileSize: new OpenLayers.Size(512,512) }
	);
	territory.addOptions({isBaseLayer: false, visibility: false, buffer: 0, reproject: true }); 
	map.addLayer(territory);
	resetZlevels();
}
function createInnerBoundaries()
{
// make the territory layer here
	innerBoundaries = new OpenLayers.Layer.WMS
	( 
		'innerBoundaries', 
		meshBlocksBase, 
		{
			sld:territorySld, 
			format: drapeImage,  
			quality: 'BEST', 
			reaspect: false, 
			transparent:'true'
		},
		{ tileSize: new OpenLayers.Size(512,512) }
	);
	innerBoundaries.addOptions({isBaseLayer: false, visibility: false, buffer: 0, reproject: true }); 
	map.addLayer(innerBoundaries);
	resetZlevels();
}

function createAllTerritoriesLayer()
{
// make the territory layer here
	allTerritoriesLayer = new OpenLayers.Layer.WMS
	( 
		'allTerritoriesLayer', 
		meshBlocksBase, 
		{
			sld:allTerritoriesSld, 
			format: drapeImage,  
			quality: 'BEST', 
			reaspect: false, 
			transparent:'true'
		},
		{ tileSize: new OpenLayers.Size(512,512) }
	);
	allTerritoriesLayer.addOptions({isBaseLayer: false, visibility: false, buffer: 0, reproject: true }); 
	map.addLayer(allTerritoriesLayer);
	resetZlevels();
}

function buildCompositeReport(objId)
{	
	//alert('feature currently not available'); 
	//document.getElementById(objId).checked = false;
	//return;
	if(document.getElementById(objId).checked)
	{
		//genLoadStatus('Compiling All Territories Report ...', true, '');
		document.getElementById(objId).checked = true;
		
		// get the list of xml files from the folder
		ajaxRequest = getListOfFiles(territoryFolder);
		if(ajaxRequest == 'error') {alert('oops'); return;}

		// get the names of each file and store in list array
		var xmlFiles = ajaxRequest.responseText.split("|");
		//alert(xmlFiles)

		
		// Create the report table
		var territoryInfo = document.getElementById('territoriesInfo2');
		checkRemoveObject('territoriesGfiData2');

		var tableHolder = document.createElement('table');
		tableHolder.style.border='1px solid gray';
		tableHolder.style.minWidth = '100%';
		tableHolder.style.width = 'auto';
		tableHolder.style.height = 'auto';
		tableHolder.style.textAlign = 'center';
		tableHolder.style.backgroubdColor = '#FFFFFF';
		tableHolder.id = 'territoriesGfiData2';
		tableHolder.setAttribute('id', 'territoriesGfiData2');

		var table = document.createElement('tbody');	
		table.style.zIndex = '5600';
		table.style.backgroundColor='#ffffff';


		tableHolder.appendChild(table);
		territoryInfo.appendChild(tableHolder);
		
		// setup report header row
		headNameArray = ['Name','polygonName','Contact','Address','Location','Bounding Box','Code','Layer','Polygon','Att Name','Att Code','SRS','File','Date Entered','Abstract/Description','Fill Colour','Fill Opacity','Border Colour','Border Thickness'];

		// send this request off to the server to create a new header section in a new csv file
		// now build the header row of the csv file
		if(newAllCsvFile != ''){	deleteit(newAllCsvFile);	}
		newAllCsvFile = 'data/tempCsvAll_'+new Date().getTime()+'.csv';
		var url = applicationBase+"cf/createcsvfile.cfm?";
		var queryHead = "file=/inc/"+newAllCsvFile;
		queryHead+= "&valArray="+headNameArray;
		//alert('queryhead = '+url+ queryHead)
		makeFile(url, queryHead, false, 'POST');
	
		
		// Now go and build the report header
		if(browser == 'msie') {addRow1(table, 'head', headNameArray, '')	;} 
		else{	addRow2(table, 'head', headNameArray, '')	;}
	
		// step through each territory
		//genLoadStatus('building CSV File ...', true, '');
		//document.getElementById('completeBarHolder').style.display='block';
		for (var i=0; i<xmlFiles.length; i++)
		{
			// report on the progress of the process
			var percentDone = Math.round((i+1)/xmlFiles.length*100);
			genLoadStatus('CSV File - '+ percentDone + '% Complete ...', false, percentDone);
			//document.getElementById('completeBar').style.width=percentDone+'%';

			
			// get the a file's attribute information
			getTheTerritory(territoryFolder+xmlFiles[i])
			
			// now get all the polygon names
			//alert(territoryName);
			propVal=[];
			for(var j=0; j<territoryNames.length; j++)
			{
				// load up the values array
				propVal=
				[
					territoryName,
					territoryNames[j],
					territoryContact,
					territoryAddress,
					territoryLocation,
					territoryBbox,
					territoryCode,
					territoryDataLayer,
					territoryPolygonName,
					territoryAttName,
					territoryAttCode,
					territorySrs,
					territoryFileName,
					territoryDateEntered,
					territoryAbstract,
					territoryFillColor,
					territoryFillOpacity,
					territoryStrokeColor,
					territoryStrokeWidth,
					territoryListOfAreas
				]			

				// setup the link for this row
				link='terr:0:showTerritory:'+territoryFolder+territoryFileName; 

				// send each row to the report
				if(browser == 'msie') {addRow1(table, 'data', propVal, link)	;} 
				else{	addRow2(table, 'data', propVal, link)	;}

				//now add this row to the csv file
				var queryRecord = "file=/inc/"+newAllCsvFile;
				queryRecord+= "&valArray="+propVal;
				//alert('queryrecord = '+url+ queryRecord)
				makeFile(url, queryRecord, false, 'POST');
			}
		}
		//alert('creating link')
		document.getElementById('downloadLink3').style.display='block';
		buildDownloadLinks('downloadLink3', newAllCsvFile, false, true)
	}
	else
	{
		document.getElementById(objId).checked = false;
		// now go and build the summary roport
		document.getElementById('listTerr').title = 'Show Report';
		showHideTerritoriesReport("listTerr","territoriesReportHolder2");
		document.getElementById('downloadLink3').style.display='none';
	}
	//document.getElementById('completeBarHolder').style.display='none';
	genLoadStatus('', false, '');
}

function aggregateTerritoryStats(buttId)
{
	if(document.getElementById(buttId).title == 'Hide Report')
	{
		document.getElementById(buttId).title = 'Show Report';
		document.getElementById('territoriesReportHolder').style.display = 'none';
		mouseup(buttId);
		return;
	}
	
	// build the onscreen report territoriesTableId 
	if(buildListOfTerritory())
	{
		generateReportGrid(ajaxRequest, 'territoriesInfo', 'territoriesGfiData');
		buildDownloadLinks('downloadLink2', newCsvFile, true, true);

		// make the report visible
		document.getElementById('territoriesReportHolder').style.display='block';
		mousedown(buttId);
		document.getElementById(buttId).title='Hide Report';
	}
	genLoadStatus('', false, '');
}

function buildListOfTerritory()
{
	// get all the attributes for the active layer
	layerName = activeLayerName+":ABS";
	loadAllAttributes();

	// list of polygons in Terrirory
	//alert(territoryFilter)
	sqlString = territoryFilter.toString(); 
	//alert(sqlString)
	//alert(targetNames);
	//alert(targetFormats);
	//alert(targetTooltips);

	// find the '_CODE' attribute name
	var objCode = '';
	for (var i=0; i<targetNames.length ; i++)
	{
		var parts = targetNames[i].split("_CODE");
		if(parts.length > 1) {objCode = targetNames[i]; break;}
	}
	if(objCode =='' ){alert('A unique key named *_CODE was not found'); return false;}
	//alert('key = '+objCode)
	
	 // set up the getFeature request
	 
	// set up the parameters for accessing ActiveLayer
	var uri = meshBlocksBase;
	var dataStore ="ABS";
	var typeName = activeLayerName;
	var attName =  objCode;
	
	//var searchType ='PropertyIsLike';
	// set up the polygon name search filter 
	//terrFilter = "<Filter><"+searchType+"><PropertyName>"+attName+"</PropertyName><Literal>"+sqlString+"</Literal></"+searchType+"></Filter>";

	terrFilter = makeFilterWithOr(attName, territoryFilter);
	
	// call function to get the ploygon's GetFeature GML into the DOM
	ajaxRequest = getFeatureRequest (uri, 'GetFeature','WFS', srs, dataStore, typeName, terrFilter, 'BXFS');
	if(ajaxRequest.status != 200){alert('Could not execute GetFeature request'); return false;}
	
	// check to see if there are more than limit specified in 'gfiLimit' for selection area
	var feature = fetchObjects(ajaxRequest);
	if(feature == null){alert('Could not get any Features'); return false;}
	
	// Generic reporting function for the features located
	//alert('number of features = '+feature.length)
	if (feature.length > 0)
	{
		// step through the traget Attrib arrays and load into attributeInfo array
		attributeInfo = new Array();
		var found=false;

		for (var k=0; k<targetNames.length ; k++ )
		{
			
			var percentDone = parseInt( Math.round((k+1)/targetNames.length*100));
			genLoadStatus(percentDone+'% Complete ...', false, percentDone);
			
			attributeInfo[k] = new Array(6);
			attributeInfo[k][0] = '';
			attributeInfo[k][1] = targetNames[k]; // typically used as a desctiption/Title
			attributeInfo[k][2] = targetSummit[k]; 
			attributeInfo[k][3] = targetNames[k];  // actual attribute name
			attributeInfo[k][4] = targetFilter[k]; // true or false
		
			// now see if there are any attribute values/ranges available for this attribute
			attributeInfo[k][6] = ''
		}
		genLoadStatus('', false, '')
		
	}
	else{return false;}
	return true;
}
	

function makeFilterWithOr(attribName, codesArray)
{
	var filter = ''
	//var codesArray = sqlListString.toSource();
	if(codesArray.length < 1)  {return filter;}
	
	// now build up the filter tag
	filter = "<Filter>";
	var orTag01 = '<Or>'; var orTag02 = '</Or>';
	if(codesArray.length == 1){var orTag01 = ''; orTag02 = '';}
	
	filter = filter+orTag01;
	for(var i=0; i<codesArray.length; i++)
	{	filter = filter+"<PropertyIsEqualTo><PropertyName>"+attribName+"</PropertyName><Literal>"+codesArray[i]+"</Literal></PropertyIsEqualTo>";		}
		
	filter = filter+orTag02+"</Filter>";
	return filter;
}
