
//----------------- load all attributes into the reporting arrays -------------------------
function loadAllAttributes()
{
	allAtts = false;
	// initialise Target Arrays
	targetNames = new Array();
	targetFormats = new Array();
	targetTooltips = new Array();
	targetSummit = new Array();
	targetFilter = new Array();

	// first get the XML that defines all the attributes for the layer
	//alert('layerName = '+layerName)

	ajaxRequest = getAttributeSchema(meshBlocksBase, layerName);
	//alert(ajaxRequest.status)	

	// get all attributes from XML file into arrays
	if(!buildAttributeArrays(ajaxRequest)){return;}
		
	// Copy all database attributes into target arrays
	targetNames = attNames;
	targetFormats = format;
	targetTooltips = tooltip;
	
	// assume first attribute is unique key and set the sum flag for each numeric attribute
	for (var i=0; i<targetNames.length ; i++)
	{
		targetFilter[i] = 'false';
		if(i == 0){targetFilter[i] = 'true';}
		
		var summ = targetFormats[i].split(' (');
		var parts = targetNames[i].split('_CODE');
		if((summ[0] == 'Floating' || summ[0] == 'Double' || summ[0] == 'Integer') && parts.length <= 1 )
		{  	targetSummit[i] = 'true'	} else {	targetSummit[i] = 'false';	}
	}
	 allAtts = true;
	 numberAtts = targetNames.length;
	//alert('filters = '+targetFilter)
	//alert('names = '+targetNames)
}

function populateAttribList()
{
	// initialise Target Arrays
	targetNames = new Array();
	targetFormats = new Array();
	targetTooltips = new Array();
	targetFilter = new Array();
	targetSummit = new Array();
	
	// get the list of attributes for the currently active datalayer
	getAttributeSchema(meshBlocksBase, layerName);
		
	// get all attributes from XML file into arrays
	if(!buildAttributeArrays(ajaxRequest)){return;}

	// now build the picklist with the arrays
	var targetObj = document.getElementById('fromList');
	createSourceAttribTable(targetObj);

	// now just expose the picklist panel
	document.getElementById("attribHolder").style.display="block";
	allAtts = false;
}

function validated()
{
	//alert(polypikaMode)
	if(!polypikaMode)
	{
		// scan through the target Reporting arrays to make sure there is at least one attribute selected and is a unique key
		for (var i = 0 ; i<targetFilter.length; i++)
		{
			if(targetFilter[i] == 'true'){return true;}	
		}
		alert('There are no attributes in the report that can be used for highlighting polygon selection.') ;
		
		document.getElementById('attribHolder').style.display='block';
		return false;
	}
	else
	{
		if(activeLayerName != '') {return true;}
		else
		{	
			alert('No Active Layer set. Open Layer Control Panel and make a layer active by clicking on the layer name. The layer row will be highlighted and the layer will display. This layer is assumed the layer for polygon picking.');
			return false;
		}
	}

}

function getAttributeSchema(serviceBase, layerName)
{
	//alert('layer name = '+layerName)
	// do a DescribeFeatureType request to get attribute schema
	// initialise the request
	ajaxRequest = null;
	var gfiParams = '';
	gfiParams = startReq(serviceBase, gfiParams);

	// buld up the GetFeature request here
	var srcParts = layerName.split(':');
	var datastore = srcParts[srcParts.length-1]	;

	for (var i=0; i<srcParts.length-1; i++)
	{	if(i == 0 ) {var typename = srcParts[i];}else{typename = typename+":"+srcParts[i];}	}
	
	//alert(typename+ " >>> "+datastore )
	gfiParams = "REQUEST=DescribeFeatureType";
	gfiParams += "&SERVICE=WFS";
    gfiParams += "&DATASTORE="+datastore;
	gfiParams += "&TYPENAME="+typename;
	gfiParams += "&VERSION=1.0.0";
	if(account!=''){gfiParams += "&accCode="+account;}

	//alert(serviceBase + gfiParams)
	//makePopup(serviceBase+gfiParams, '500', '500', 'both'); 
	ajaxRequest = proxyRequest(serviceBase, gfiParams, '', 'POST') ;
	return ajaxRequest;
}
function checkForError(ajaxRequest)
{
	// Check to see if there were any errors from Ajax request
	var exceptions = ajaxRequest.responseXML.getElementsByTagName("ows:Exception");	
	if (exceptions.length > 0) 
	{
		for(var i=0; i<exceptions.length; i++)
		{	
			var errors = exceptions[i].getElementsByTagName("ows:ExceptionText");
			var error = errors[i].firstChild.nodeValue;
			alert('returned error = **** '+error+' ****'); 
			
		}
		return false;
	}
	return true;
}

// function to pick off all attributes in DescribeFeature XML file and pupulate arrays
function buildAttributeArrays(ajaxRequest)	
{
	// apply XML browser difference here
	var prefix='xs:';
	//alert(browser+" : "+version)
	if ((browser =='firefox' && version == '2') || (browser == 'safari'))
	{	prefix='';	}
	//alert('prefix = '+prefix)
	// check to see if this request is not in error
	if(!checkForError(ajaxRequest)){alert('Error in DescribeFeatureType WFS request'); return false;}
	
	// now get the attributes and their data types into arrays
	var complexType = ajaxRequest.responseXML.getElementsByTagName(prefix+"complexType");
	var elements = complexType[0].getElementsByTagName(prefix+"element");		
	
	//alert('number in list = '+elements.length)
	attNames = []; format = []; var k=0; tooltip = [];

	// 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('.');
			
			//alert('attribute name = '+attNameParts[1])
			if(attNameParts[1] != 'GEOMETRY')  // should be a redundant check
			{
				attNames[k] = attNameParts[1];

				// now get each attributes format
				var simpleType = elements[j].getElementsByTagName(prefix+"simpleType");
				var typeObj = simpleType[0].getElementsByTagName(prefix+"restriction");
				var type = typeObj[0].getAttribute("base");
				var string = 'xs:string'; var integer = 'xs:integer'; var decimal = 'xs:decimal';
				//alert('restriction Base = '+type)
				if (type !== null)
				{	
					if (type == string ) 
					{	
						// check for any attribute metadata we have
						var optionsList=[];
						if(attributeInfo.length > 0)
						{
							for (var m=0; m<attributeInfo.length ;m++ )
							{
								//alert(attributeInfo[m][3]+' = '+attributeInfo[m][6]);
								if(attributeInfo[m][3] == attNames[k])
								{
									optionsList = attributeInfo[m][6].split(',');
									break;
								}
							}
						}
						format[k] = 'Text '; 
						var value = typeObj[0].getElementsByTagName(prefix+"maxLength")[0].getAttribute("value");
						format[k] += "("+value+")";
						//alert ("att name = "+attNames[k]+"\nformat = "+format[k]+"\nList = "+optionsList);
						tooltip[k] = 
							"Format : "+format[k]+","+
							"Options : ";
						for (var h=0; h < optionsList.length ; h++)
						{
							if(h == 0) { tooltip[k] = optionsList[h];}
							else{ tooltip[k] += ", "+optionsList[h]; }
						}
						k++;
					}
					else if (type == integer)
					{
						// check for any attribute metadata we have
						var optionsList=[];
						if(attributeInfo.length > 0)
						{
							for (var m=0; m<attributeInfo.length ;m++ )
							{
								//alert(attributeInfo[m][3]+' = '+attributeInfo[m][6]);
								if(attributeInfo[m][3] == attNames[k])
								{
									optionsList = attributeInfo[m][6].split(',');
									break;
								}
							}
						}
						format[k] = 'Integer ';
						var value = typeObj[0].getElementsByTagName(prefix+"totalDigits")[0].getAttribute("value");
						format[k] += "("+value+")";
						//alert ("att name = "+attNames[k]+"\nformat = "+format[k]+"\nLow Value = "+optionsList[0]+"\nHigh Value = "+optionsList[1]);
						tooltip[k] = 
							"Format : "+format[k]+", "+
							"Low Value : "+optionsList[0]+", "+
							"High Value : "+optionsList[1];
						k++;
					}
					else if (type == decimal)
					{
						var optionsList=[];
						if(attributeInfo.length > 0)
						{
							for (var m=0; m<attributeInfo.length ;m++ )
							{
								//alert(attributeInfo[m][3]+' = '+attributeInfo[m][6]);
								if(attributeInfo[m][3] == attNames[k])
								{
									optionsList = attributeInfo[m][6].split(',');
									break;
								}
							}
						}
						format[k] = 'Floating ';
						var value = typeObj[0].getElementsByTagName(prefix+"totalDigits")[0].getAttribute("value");
						var value2 = typeObj[0].getElementsByTagName(prefix+"fractionDigits")[0].getAttribute("value");
						format[k] += "("+value+"."+value2+")";
						//alert ("att name = "+attNames[k]+"\nFormat = "+format[k]+"\nLow Value = "+optionsList[0]+"\nHigh Value = "+optionsList[1]);
						tooltip[k] = 
							"Format : "+format[k]+", "+
							"Low Value : "+optionsList[0]+", "+
							"High Value : "+optionsList[1];
						k++;
					}
				}
			}
		}
		else
		{
			// process date formats and others
			if (typeElement == prefix+'dateTime')
			{
				format[k] = "D";
				//alert ("att name = "+attNames[k]+" and format = "+format[k]);
				k++;
			}
		}
	}
	//alert('att Names = '+attNames)
	return true;
}

function createSourceAttribTable(holderDivObj)
{
	// first kill off any existing table
	checkRemoveObject('sourceAttribTable');

	// create the Table element
	var attribTable = document.createElement('table');
	attribTable.style.top='0px';
	attribTable.style.left='0px';
	attribTable.style.height='auto';
	attribTable.style.width='100%';
	attribTable.style.overflowX='auto'; 
	attribTable.style.overflowY='auto'; 
	attribTable.style.borderCollapse='collapse';
	attribTable.id='sourceAttribTable'; attribTable.setAttribute('id','sourceAttribTable');
		var attribTableBody = document.createElement('tbody');
		var found=false;
		// add each row to the body
		for (var i=0; i < attNames.length ; i++)
		{
			// Create the Row
			var innerRow = document.createElement('tr');
			
				// now the TD cell
				var innerCell = document.createElement('td');
				innerCell.style.height='15px';
				innerCell.style.fontSize='10px';
				innerCell.id='source:'+i; innerCell.setAttribute('id','source:'+i);
				var textElement = document.createTextNode(attNames[i]);
				innerCell.appendChild(textElement);
				innerCell.title = tooltip[i];
				var backColor = '#FFFFFF';
				if(evenCheck (i)) {backColor = '#FFFFD4';}
				innerCell.style.backgroundColor = backColor;

				// add the onclick event
				bindEvent(innerCell, 'click', adjustReportList, 'false');
				
				// highlight the unique key attribute
				if(i == 0) {innerCell.style.fontWeight='bold'; found=true;}
				else {innerCell.style.fontWeight='normal'; }

			// append to Table
			innerRow.appendChild(innerCell)	;
			attribTableBody.appendChild(innerRow);
		}
	attribTable.appendChild(attribTableBody);
	holderDivObj.appendChild(attribTable);
	
	// now force the key into the selected arrays - first attribute in list
	document.getElementById('source:0').style.backgroundColor = 'cyan';
	targetNames.push(attNames[0]);
	targetFormats.push(format[0]);
	targetTooltips.push(tooltip[0]);
	targetSummit.push('false');
	targetFilter.push('true');
	
	// initialise the Destination table
	var targetObj = document.getElementById('toList');
	createDestAttribTable(targetObj);
}

function adjustReportList(evt)
{
	var thisObjId	= getThisId(evt) ;
	var parts = thisObjId.split(':');
	//alert(thisObjId)

	// check to see if this is an add or a subtract
	if(document.getElementById(thisObjId).style.backgroundColor !='cyan')
	{
		// ADD the selected element Name to the destination array
		document.getElementById(thisObjId).style.backgroundColor = 'cyan';
		targetNames.push(attNames[parts[1]]);
		targetFormats.push(format[parts[1]]);
		targetTooltips.push(tooltip[parts[1]]);
		targetSummit.push('false');
		
		// set the filter flag
		if(parts[1] == 0){	targetFilter.push('true');}
		else			 {	targetFilter.push('false');}
	}
	else
	{
		// REMOVE the element from destination list 
		for(var j=0; j < targetNames.length; j++)
		{
			if(targetNames[j] == attNames[parts[1]])
			{
				// set the cell colour to normal
				var backColor = '#FFFFFF';
				if(evenCheck (parts[1])) {backColor = '#FFFFD4';}
				document.getElementById(thisObjId).style.backgroundColor = backColor;
				
				// remove the element from the arrays
				targetNames.splice(j,1);
				targetFormats.splice(j,1);
				targetTooltips.splice(j,1);
				targetFilter.splice(j,1);
				targetSummit.splice(j,1);
				break;
			}
		}
	}

	// initialise the Destination table
	var targetObj = document.getElementById('toList');
	createDestAttribTable(targetObj);

	Event.stop(evt);
}

function createDestAttribTable(holderDivObj)
{
	// first kill off any existing table
	checkRemoveObject('destAttribTable');

	// create the surrounding Form element <form  action='' id='reptRadioButts'>
	var attribForm = document.createElement('form');
	attribForm.id='destAttribTable'; attribForm.setAttribute('id','destAttribTable');
	attribForm.action=''; attribForm.setAttribute('action','');
	//attribForm.setAttribute('name','attForm'); attribForm.name='attForm';	
	
	// create the Table element
	var attribTable = document.createElement('table');
	attribTable.style.top='0px';
	attribTable.style.left='0px';
	attribTable.style.height='auto';
	attribTable.style.width='100%';
	attribTable.style.overflowY='auto'; 
	attribTable.style.borderCollapse='collapse';
		var attribTableBody = document.createElement('tbody');
		
		// add each row to the body
		var found=false;
		for (var i=0; i < targetNames.length ; i++)
		{
			// Create the Row
			var innerRow = document.createElement('tr');
				
				// now the TD cell for Summit Checkbox
				var innerCell = document.createElement('td');
				innerCell.style.height='15px';
				innerCell.style.width='40px';
				innerCell.style.fontSize='10px'; 
				var backColor = '#FFFFFF';
				if(evenCheck (i)) {backColor = '#FFFFD4';}
				innerCell.style.backgroundColor = backColor;

					// create the Input checkbox for Attribute Summation
					var box = document.createElement('input');
					box.setAttribute('type','checkbox');
					box.setAttribute('id','summit:'+i);
					box.id='summit:'+i;
					box.style.backgroundColor='transparent';
					box.title='Check this box if this attribute requires a total at the bottom of the report';
					
					// disable box if summing is not relevant
					var parts = targetFormats[i].split(' (');
					if(parts[0] == 'Floating' || parts[0] == 'Double' || parts[0] == 'Integer') 
					{		box.disabled = false;} 
					else {	box.disabled=true;}
					//var code = targetNames[i].split('_CODE');
					//if(parts[0] == 'Integer' && code.length > 1) {	box.disabled = true }
					if(parts[0] == 'Integer' && i == 0) {	box.disabled = true }
					
					// attach the interactive event handler
					bindEvent(box, 'click', saveSummit, 'false');
					//if(browser == 'msie'){bindEvent(box, 'click', blurIt, 'false');}

					//if(browser == 'firefox'){bindEvent(box, 'change', saveSummit, 'false')}
					//else {bindEvent(box, 'click', blurIt, 'false');}

					innerCell.appendChild(box);
			innerRow.appendChild(innerCell)	;

				// now the TD cell for the attribute name
				var innerCell = document.createElement('td');
				innerCell.style.height='15px';
				//innerCell.style.width='80%';
				innerCell.style.fontSize='10px';
				innerCell.style.overflowX='auto'; 
				innerCell.style.float='left'; 
				innerCell.id='dest:'+i; innerCell.setAttribute('id','dest:'+i);
				var textElement = document.createTextNode(targetNames[i]);
				innerCell.appendChild(textElement);

				// if this is a CODE attribute then highlight the Name
				//if(code.length > 1 && !found) {innerCell.style.fontWeight='bold'; found=true;}
				if(i == 0) {innerCell.style.fontWeight='bold'; found=true;}
				else {innerCell.style.fontWeight='normal'; }

				// set the background color for odd/even
				var backColor = '#FFFFFF';
				if(evenCheck (i)) {backColor = '#FFFFD4';}
				innerCell.style.backgroundColor = backColor;
			innerRow.appendChild(innerCell)	;
			attribTableBody.appendChild(innerRow);
		}
	attribTable.appendChild(attribTableBody);
    attribForm.appendChild(attribTable);
	holderDivObj.appendChild(attribForm);

}
function launchReptControl(buttObj)
{
	buttObj.src="images/gfi_on.jpg";  
	buttObj.title='Currently set to pick mode';
	document.getElementById("reptContHolder").style.display="block";
}
function saveSummit(evt)
{
	var thisEvent = getThisId(evt);
	var type = thisEvent.split(':');	
	if(document.getElementById(thisEvent).checked)	{	targetSummit[type[1]] = 'true'	}
	else {targetSummit[type[1]] = 'false'}
	//Event.stop(evt);

}
function blurIt(evt)	// for firefox to handle onchange of a checkbox
{
	//alert('click registered')
	var thisEvent = getThisId(evt);
	var type = thisEvent.split(':');
	//alert('this event =' +thisEvent)
	document.getElementById(thisEvent).blur();
	if (type[0] == 'markers')	{	toggleMarkers(evt); }
	else if(type[0] == 'summit'){	saveSummit(evt); }
	Event.stop(evt);
}

// this function will add the pick list of attributes to the target object (holding Div)
function createAttribPicker(holderDivObj)
{	
	// create the attribute picklist
	var logicCell1 = document.createElement('td');
	logicCell1.style.width='200px';
	logicCell1.style.height='20px';
	//logicCell1.style.border="1px solid red";
	logicCell1.id='attsTd';
	logicCell1.setAttribute('id','attsTd');
	var num = attNames.length;
	
	// create the Select object
		var select = document.createElement('select');
		select.className='selectBox';
		select.style.verticalAlign='middle';
		select.style.width='250px';
		select.setAttribute('size','1');
		select.setAttribute('width','70');
		select.id='attribs';
		select.setAttribute('id','attribs');

			// put a -- Select -- row in first option
			var opt = document.createElement('option');
			opt.style.zIndex='5400';
			opt.value='select';
			var optText = document.createTextNode("--- select from list ---");
			opt.appendChild(optText);
			opt.style.width="100%";
			opt.title = ('select from the available list of attributes below');
			select.appendChild(opt)				

			// now create the Option rows
			for (var i=0; i<num ; i++ )
			{		
				var opt = document.createElement('option');
				opt.value=attNames[i];
				var optText = document.createTextNode(attNames[i]);
				opt.appendChild(optText);
				opt.style.width="100%";
				opt.title= tooltip[i];
				opt.setAttribute("title", tooltip[i]);
				//var boxover = "header=[Attribute Information] cssbody=[dvbdy12] cssheader=[dvhdr12] body=["+tooltip[i]+"]"
				//opt.title= boxover;
				//opt.setAttribute("title", boxover);
				select.appendChild(opt)
			}
		bindEvent(select, 'change', addCond, 'false');
		//form.appendChild(select);
	logicCell1.appendChild(select);
	holderDivObj.appendChild(logicCell1)
}

function removeAllControls()
{

	if(dragBoxControl !=null)
	{	//map.removeControl(dragBoxControl);
		dragBoxControl.destroy(); dragBoxControl = null;
	}

	if(drawControls !=null)
	{	//map.removeControl(drawControls);
		drawControls.destroy(); drawControls=null;
	}
	//if(click)
	//{	//map.removeControl(click);
		//click.destroy(); 
	//}

	if(rectClick != null)
	{
		//map.removeControl(rectClick);
		rectClick.destroy(); rectClick = null;
	}

	if(circClick != null)
	{
		//map.removeControl(circClick);
		circClick.destroy(); circClick = null; 
	}
//	if(noticeControl != null)
//	{
//		noticeControl.destroy(); noticeControl = null;
//	}
	//alert('all controls destroyed')
}
function removeMarkerSelectControls()
{
	//alert('destroying select controls')
	if(terrSelectControl != null)
	{	//terrSelectControl.deactivate(); 
		terrSelectControl.destroy();
		terrSelectControl = null;
	}

	if (selectControl != null)
	{	//map.removeControl(selectControl);
		selectControl.destroy();
		selectControl = null;
	}

	if(click != null)
	{	//map.removeControl(click);
		click.destroy();
		click=null;
	}
	//alert('all click controls deactivated')
}
function reinstateMarkerSelectControls()
{
	//alert('reinstating controls')
	if(terrSelectControl)
	{	terrSelectControl.activate(); 	}
	
	if (selectControl)
	{	selectControl.activate(); }
	
	if(click)
	{	click.activate();}
}

//------------------------- getfeatureinfo control for various methods of capture ------------------------------------
function getfeatureByPolygon(drapeAtts, currentFile, report, list, width, height, radius, freehand, dbGeometry, searchType, dragable)
{	
	// remove any existing vectors/markers/controls used in upload vectors
	removeAllControls()
	//alert('drape Atts = '+drapeAtts)
	//resetZlevels();
	
	// if this is a click and make polygon rectangle request or a signle polygon pick
	if (width != '' && height!='')	
	{	
		
		buildRectBoxControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable); 
	}
	// if this is a click and make polygon circle request
	else if(radius != '')
	{	
		buildCircleControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable);
	}
	// enter freehand polygon digitizing mode
	else if(freehand)
	{ 
		buildFreehandControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable); 
	}
	// database selection mode
	else if(dbGeometry)
	{ 
		//alert('number of points = '+allX.length)
		//if(allX.length >10000) {alert ('more than 10000 points'); return;}
		removeCreateVectors(dragable); // this will kill off any existing enclosing box
		draw = true;
		centX=''; centY='';
		getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, draw, dragable); 
	}

	// if this is a shift-drag-box request
	else 
	{ 
		//alert('entering ShapeControl')
		//buildDragBoxControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable);
		buildVariableShapeControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable);
	}
}	

function buildVariableShapeControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable)
{
	// this will delete existing and create a new vectorLayer for search polygon
	removeCreateVectors(dragable);
	
	// get the user selected type of standard shape
	var selectObject = document.getElementById('shapesOptionsList');
	var polyType = selectObject.options[selectObject.selectedIndex].value;
	//alert(PolygonLayer.getZIndex());
	//alert(DemoDrape.getZIndex());
	
	if(noticeControl == null)
	{
		//alert('creating the control')
		//PolygonLayer.setZIndex(map.Z_INDEX_BASE['Popup'] - 1000);
		
		OpenLayers.Control.NoticeControl = OpenLayers.Class(OpenLayers.Control.DrawFeature,
		{
			initialize: function(layer, handler, options) {
				OpenLayers.Control.DrawFeature.prototype.initialize.apply(this, [layer, handler, options]);
			},
			setMap: function(map) {
				this.handler.setMap(map);
				OpenLayers.Control.prototype.setMap.apply(this, arguments);
			},
			featureAdded: function(feature) {
				// get polygon geometry
				var polyString =  feature.geometry.toString() ;

				//alert('Z index PolygonLayer = '+PolygonLayer.getZIndex());
				//alert('Z index DemoDrape = '+DemoDrape.getZIndex());
				this.deleteFeature(feature);
				if(DrapeHighlight) {DrapeHighlight.setVisibility(false);}
				//if(PolygonLayer != null){PolygonLayer.destroy(); PolygonLayer=null;}
				//alert('vectors gone');


				// update status and remove unnecessary controls
				genLoadStatus('Fetching Data From Server ...', true);
				document.getElementById("eventsLogID").style.display='block'
				removeMarkerSelectControls();
				removeCreateVectors(dragable);			
				
				// decode coordinate string
				var tempString = polyString.split('((');
				var coords = tempString[1].split('))');
				var pointArray = coords[0].split(',');

				// get the vertices of the polygon into real world arrays
				allX = new Array();	allY = new Array();
				for (var i=0; i<pointArray.length; i++)
				{	var parts = pointArray[i].split(' ');
					allX[i] = parts[0];	allY[i] = parts[1];
				}
				
				// create a search vector object of the dragged feature
				centX = ''; centY = '';			
				getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, true, dragable);
				//resetZlevels();
				document.getElementById("eventsLogID").style.display='none';
			},
			deleteFeature: function(feature) {
				feature.state = OpenLayers.State.DELETE;		
				this.layer.events.triggerEvent("afterfeaturemodified",
												   {feature: feature});
				this.layer.drawFeature(feature);
			},
			CLASS_NAME: "OpenLayers.Control.NoticeControl"
		});
		var options = {sides: 4};
		//var options = {sides: polyType, radius: null, angle: 0, irregular: false, persist: false }
		noticeControl = new OpenLayers.Control.NoticeControl(PolygonLayer, OpenLayers.Handler.RegularPolygon,{handlerOptions: options});
		map.addControl(noticeControl);
		//noticeControl.activate();
		//alert('noticeControl added')
	}
	
	// get the user selected type of standard shape
	//var selectObject = document.getElementById('polypikaIncludeShape');
	//var polyType = selectObject.options[selectObject.selectedIndex].value;
	if(DrapeHighlight) {DrapeHighlight.setVisibility(false);}
	setSize(parseFloat(""));
	setOptions({sides: parseInt(polyType)});
	noticeControl.activate();
		
	// create a new control updating sides as per user request
/*var options = {sides: polyType, radius: null, angle: 0, irregular: false, persist: false }
	alert('1')
	shapeControl = new OpenLayers.Control.NoticeControl(PolygonLayer, OpenLayers.Handler.RegularPolygon,{handlerOptions: options});
	alert('2')
	map.addControl(shapeControl);
	alert('3')
*/
	
	vectorLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);
	//alert('noticeControl setup');
}

function setOptions(options) 
{
    // alert('options int = '+options)
	  noticeControl.handler.setOptions(options);
}
        
function setSize(fraction) 
{
      var radius = fraction;
	//  alert('radius real = '+radius)
      noticeControl.handler.setOptions({radius: radius, angle: 0});
}



// ---------- set up the getfeature info alert on shift mouse box select --------------
function buildFreehandControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable)
{	
	// clean up any previous vectors/controls if present
	removeCreateVectors(dragable) // this will also create a new vectorlayer
	drawControls = new OpenLayers.Control.DrawFeature(PolygonLayer, OpenLayers.Handler.Polygon) ;

	// extend the drawcontrol with its behavior
	OpenLayers.Util.extend(drawControls, 
	{	draw: function (){	this.polygon = new OpenLayers.Handler.Polygon(drawControls,	{	"done": this.notice		});	this.polygon.activate();},
		notice: function (polygon)
		{
			//alert('hello world 2')
			genLoadStatus('Fetching Data From Server ...', true);
			document.getElementById("eventsLogID").style.display='block'
			removeMarkerSelectControls();
			removeCreateVectors(dragable);
			
			// get vertices of polygon into and array of coordinate pairs
			var polyString =  polygon.toString() ;
			var tempString = polyString.split('((');
			var coords = tempString[1].split('))');
			var pointArray = coords[0].split(',');

			// get the vertices of the polygon into real world arrays
			allX = new Array();	allY = new Array();
			for (var i=0; i<pointArray.length; i++)
			{	var parts = pointArray[i].split(' ');
				allX[i] = parts[0];	allY[i] = parts[1];
			}
			centX = ''; centY = '';			
			
			getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, true, dragable);
			this.polygon.deactivate();
			resetZlevels();
			document.getElementById("eventsLogID").style.display='none';
		}
   });
	   
   map.addControl(drawControls);

	
}



// ---------- set up the getfeature info alert on shift mouse box select --------------
function  buildDragBoxControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable)
{

	if(dragBoxControl != null){dragBoxControl.destroy(); dragBoxControl = null;}
	dragBoxControl = new OpenLayers.Control();
	OpenLayers.Util.extend(dragBoxControl, 
	{	
		draw: function () 
		{
			// this Handler.Box will intercept the shift-mousedown before Control.MouseDefault gets to see it
			this.box = new OpenLayers.Handler.Box( dragBoxControl, {"done": this.notice},{keyMask: OpenLayers.Handler.MOD_SHIFT});
			this.box.activate();
		},	
		notice: function (bounds) 
		{
			genLoadStatus('Fetching Data From Server ...', true);
			removeMarkerSelectControls();
			removeCreateVectors(dragable) // this will kill off any existing enclosing box

			// use the shift mouse control to drag a box and now get the coords of box			
			ll = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom)); 
			ur = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top));
			loXX = ll.lon.toFixed(12);
			loYY = ll.lat.toFixed(12);
			hiXX = ur.lon.toFixed(12);
			hiYY = ur.lat.toFixed(12);
			
			// calculate centre of box
			centX = (parseFloat(loXX) + parseFloat(hiXX)) / 2.0;
			centY = (parseFloat(loYY) + parseFloat(hiYY)) / 2.0;
			
			// get the vertices of polygon into real world arrays
			allX = new Array();
			allY = new Array();
			allX[0] = loXX;	allY[0] = loYY;
			allX[1] = loXX;	allY[1] = hiYY;
			allX[2] = hiXX;	allY[2] = hiYY;
			allX[3] = hiXX;	allY[3] = loYY;
			allX[4] = loXX;	allY[4] = loYY;
			getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, true, dragable);
			//getFeaturesByRectangle(loXX, loYY, hiXX, hiYY, drapeAtts, currentFile, report, list, width, height, radius);

		}
	});

	map.addControl(dragBoxControl);
	dragBoxControl.activate();

	//removeCreateVectors();
}
// ---------- set up the getfeature info alert on shift mouse box select --------------
function buildRectBoxControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable)
{
	
	
	if(rectClick != null ){rectClick.destroy(); rectClick = null;}
	rectClick = new OpenLayers.Control();
	// setup a single mouse click control for getfeatureinfo reports
	OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, 
	{                
	    defaultHandlerOptions: 
		{
		    'single': true
            ,'double': false
            ,'pixelTolerance': 10
            ,'stopSingle': false
          //  ,'stopDouble': false
        },

        initialize: function(options) 
		{
            this.handlerOptions = OpenLayers.Util.extend
			(
				{}, this.defaultHandlerOptions
            );
            OpenLayers.Control.prototype.initialize.apply
			(
                this, arguments
            ); 
                this.handler = new OpenLayers.Handler.Click
				(
					this, {
                            'click': this.trigger
                          }, this.handlerOptions
                );
        }, 
        // do this on the mouse click
        trigger: function(e) 
		{
			alert("wt = "+width+' ht = '+height)
			removeMarkerSelectControls();
			genLoadStatus('Fetching Data From Server ...', true);
			removeCreateVectors(dragable) // this will kill off any existing enclosing box

			// now convert pixels to lat longs
			var pixel = new OpenLayers.Pixel(e.xy.x, e.xy.y);
			var lonlat = map.getLonLatFromPixel(pixel); 
			loXX = lonlat.lon - parseFloat(width/2);
			loYY = lonlat.lat - parseFloat(height/2);
			hiXX = lonlat.lon + parseFloat(width/2);
			hiYY = lonlat.lat + parseFloat(height/2);

			allX = new Array();
			allY = new Array();
			allX[0] = loXX;	allY[0] = loYY;
			allX[1] = loXX;	allY[1] = hiYY;
			allX[2] = hiXX;	allY[2] = hiYY;
			allX[3] = hiXX;	allY[3] = loYY;
			allX[4] = loXX;	allY[4] = loYY;

			centX = lonlat.lon
			centY = lonlat.lat
									
			// now go and get all the polygons 
			getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, true, dragable);
		}			
	});
	rectClick = new OpenLayers.Control.Click();          
	map.addControl(rectClick);
	rectClick.activate();
}
// ---------- set up the getfeature info alert on shift mouse box select --------------
function buildCircleControl(drapeAtts, currentFile, report, list, width, height, radius, searchType, dragable)
{
	//alert('circle drag = '+dragable)
	if(circClick != null){circClick.destroy(); circClick = null;}
	circClick = new OpenLayers.Control();
	
	// setup a single mouse click control for getfeatureinfo reports
	OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, 
	{                
	    defaultHandlerOptions: 
		{
		    'single': true
            ,'double': false
            ,'pixelTolerance': 10
            ,'stopSingle': false
          //  ,'stopDouble': false
        },

        initialize: function(options) 
		{
            this.handlerOptions = OpenLayers.Util.extend
			(
				{}, this.defaultHandlerOptions
            );
            OpenLayers.Control.prototype.initialize.apply
			(
                this, arguments
            ); 
                this.handler = new OpenLayers.Handler.Click
				(
					this, {
                            'click': this.trigger
                          }, this.handlerOptions
                );
        }, 
        // do this on the mouse click
        trigger: function(e) 
		{
			removeMarkerSelectControls();
			genLoadStatus('Fetching Data From Server ...', true);
			removeCreateVectors(dragable) // this will kill off any existing enclosing box
			
			// now convert pixels to lat longs
			var pixel = new OpenLayers.Pixel(e.xy.x, e.xy.y);
			var lonlat = map.getLonLatFromPixel(pixel); 
			allX = new Array();
			allY = new Array();
			var pointList = new Array();
			var k=0;
			var z=0;
			centX = lonlat.lon
			centY = lonlat.lat
						
			// now calculate the points around the circle perimeter
			for(var i=0 ; i<360 ; i=i+6)
			{
				allX[k] = lonlat.lon + parseInt(Math.sin(i*Math.PI/180)*radius);
				allY[k] = lonlat.lat + parseInt(Math.cos(i*Math.PI/180)*radius);
				pointList.push(new OpenLayers.Geometry.Point(allX[k],allY[k]));
				k++
			}
			// now go and get all the polygons 
			//alert('getaFeaturesByPolygon');
			getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, true, dragable);
		}});
		
	circClick = new OpenLayers.Control.Click();          
	map.addControl(circClick);
	circClick.activate();

}


function getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, draw, dragable)
{		
	//alert('starting polygon selection event')
	singlePolygonPick = false;
	if(width == 1 && height== 1){singlePolygonPick = true;}
	genLoadStatus('Aggregating Features ...', true);
	
	//alert('in getfeaturesByPolygon function now')
	// Make reporting buttons visible on a Select if collection already populated
	if(collection) 
	{	if(collectionList.length > 1)
		{	alert('You can only add/remove polygons for a single collection.'); return;	}
		else
		{	resetButtons('on');		}
	}

	// zoom into the area and draw the search polygon as a vector
	if((report && draw) || (draw && polypikaMode))	{drawSelectPolygon(allX, allY, vectorLayer, searchType, dragable);	 }
	
	// convert to geographicals if in Google Maps projection so we can get data from a Geographicals database
	var p=[]; 
	var lineString = '';

	if (srs == "EPSG:900913")
	{
		for (var i=0; i < allX.length ; i++ )
		{
			p[0] = allX[i]; p[1] = allY[i];
			var point = google2geogs(p);
			p = decodePoint	(point);
			if(i==0){lineString = p[0]+","+p[1];}
			else{lineString = lineString+"%20"+p[0]+","+p[1];}
		}
	}
	else
	{
		for (var i=0; i < allX.length ; i++ )
		{
			if(i==0){lineString = allX[i]+","+allY[i];}
			else{lineString = lineString+" "+allX[i]+","+allY[i];}
		}
	}

	//other options = Equals, Touches, Within, Overlaps, Crosses, Intersects, Contains
//alert('search type = '+searchType)
	if(searchType != 'lgaKey' && searchType != 'polypikaLgaKey')
	{	
		var gfiFilter = "<Filter><"+searchType+"><PropertyName>GEOMETRY</PropertyName><Polygon xmlns:gml='http://www.opengis.net/gml'><outerBoundaryIs><LinearRing><coordinates decimal='.' cs=',' ts=' '>" +lineString+ "</coordinates></LinearRing></outerBoundaryIs></Polygon></" +searchType+ "></Filter>";
	}
	else
	{
		// use the LGA filter key that was set in LGA picker area
		//alert(LGAfilter)
		var gfiFilter = LGAfilter;
	}
	//alert('gfiFilter = '+gfiFilter)
	//alert(drapeAtts[0])
	//alert('array length = '+drapeAtts.length)
//alert('activeLayerName = '+activeLayerName)

	if(drapeAtts != null && (activeLayerName == null || activeLayerName == ''))
	{
		var components = drapeAtts[0].split('|');
		//alert(components[6] +' = '+currentFile);
		wmslayer = components[0]; 
		theme = components[1];
		themeTitle = components[2];
		themeDir = components[3];	
		themeLayer = components[4];
		layName = components[5];
		layFile = components[6];
		layStyle = components[7];
		layType = components[8];
		// strip out ABS from layer name
		var wmsTypeName = wmslayer.split(':')[0];
		//alert('wmsTypeName = '+wmsTypeName)
	}
	else if(activeLayerName != null || activeLayerName != '')
	{		var wmsTypeName = activeLayerName;	}

	if(DrapeHighlight) {DrapeHighlight.setVisibility(false);}
	
	// go and fetch the objects with a getFeature request
	genLoadStatus('Fetching Objects ...', true);
//alert('about to get objects')
	//alert('wmsTypeName = '+wmsTypeName)
	getObjects(gfiFilter, meshBlocksBase, "ABS", wmsTypeName, report, list, searchType)

	// show collection if list
	if(list)
	{
		// Update the polygons on screen as you go
		updateScreenCollection();
	}
	document.getElementById('eventsLogID').style.display='none';
//alert('resetting previous controls')
	// reinstate any deactivated select controls
	reinstateMarkerSelectControls();
//alert('done')
	
}

//-------------  this will remove the vectors created vai shift mouse control ------------
function removeCreateVectors(dragable)
{
	//alert('dragable = '+dragable)
	// Make sure vector layer and any controls are removed from map
	if(vectorLayer) 
	{	map.removeLayer(vectorLayer); 	}
	
	// initialise a new vector layer
	vectorLayer = new OpenLayers.Layer.Vector("Select Box", {style: select_box});

/*
	// if this layer is dragable add the drag control
	if(dragable)
	{	
		polyDragControls = {drag: new OpenLayers.Control.DragFeature(vectorLayer, 
		{
			'onComplete': moveStop
			,'onStart': onStartDragging
		})};
		map.addControl(polyDragControls['drag']);
		polyDragControls['drag'].activate();
	}
*/	
	// now add the new vector layer to the map
	vectorLayer.addOptions({reproject: true, visibility:true, reaspect: false});
	map.addLayer(vectorLayer);
	//registerEvents(vectorLayer);
	
	vectorLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);
	//vectorLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -500);
	//map.setLayerZIndex(vectorLayer, 25000);
	//resetZlevels();
	// delete the current SLD file for existing report
	//alert ('killing Sld = '+applicationBase+'data/'+newSldFile);
	if (!deleteit('data/'+newSldFile))
	{alert("error deleting temp file on server"); return false;}
}

function onStartDragging()
{
	if(DrapeHighlight) {DrapeHighlight.setOpacity(0.3); }
}

function moveStop(feature)
{
	if(feature)
	{
		genLoadStatus('Fetching Data From Server ...', true);
		// get vertices of polygon into and array of coordinate pairs
		var polyString = feature.geometry.toString() ;
		var tempString = polyString.split('((');
		var coords = tempString[1].split('))');
		var pointArray = coords[0].split(',');
		
		// update the arrays with the new geometry coordinates
		for(var i=0; i<pointArray.length ; i++)
		{	
			var ordinates =  pointArray[i].split(' ');
			allX[i]=ordinates[0];
			allY[i]=ordinates[1];
		}
		//if(zoomToSelectBox) {zoomToPolygon(allX, allY);}
		//alert(allX); alert(allY)
		getFeaturesByPolygon(allX, allY, drapeAtts, currentFile, report, list, width, height, radius, searchType, false, dragable);
		
	}
	else
	{ alert('OOPS no feature!'); }
}
//----------------- draw out the selection polygon -----------------------
function drawSelectPolygon(allX, allY, vectors, searchType, dragable)
{
	//alert(allX)
	//alert(allY)
	var loX = 99999999999999; loY=99999999999999; hiX=-99999999999999; hiY=-9999999999999999999;
	var pointList = new Array();
	//var polygonFeature = [];
	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 parcel01= new OpenLayers.Geometry.LinearRing(pointList);
	polygonFeature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Polygon([parcel01]));
	//polygonFeature.graphicZIndex = 300;
	vectors.addFeatures(polygonFeature);	
	vectors.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);
	
	if(zoomToSelectBox) {zoomToPolygon(allX, allY);}

	// create a drag control if required
	if(dragable)
	{	
		if(polyDragControls) { map.removeControl(polyDragControls); }
		polyDragControls = {drag: new OpenLayers.Control.DragFeature(vectors, 
		{
			'onComplete': moveStop
			,'onStart': onStartDragging
		})};
		map.addControl(polyDragControls['drag']);
		polyDragControls['drag'].activate();
		//alert("dragable select box activated");
	}
}

function zoomToPolygon(allX, allY)
{
	var loX = 99999999999999; loY=99999999999999; hiX=-99999999999999; hiY=-9999999999999999999;
	for (var i=0 ; i<allX.length ; i++)
	{
		//alert(allX[i]+', '+allY[i] );
		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];}
	}
	bounds = new OpenLayers.Bounds(loX,loY,hiX,hiY);
	zmLevel = map.getZoomForExtent(bounds)-1;
	map.setCenter(bounds.getCenterLonLat(),zmLevel);
	map.updateSize();

}

//------------------- function to get list of Polygons from server via GetFeature request  -------------------//

function getObjects(gfiFilter, serviceBase, dataStore, typeName, report, list, searchType)
{	
	// do a get feature request
	ajaxRequest = getFeatureRequest(serviceBase, 'getFeature', 'WFS', srs, dataStore, typeName, gfiFilter, 'BXFS')
	if(ajaxRequest.status != 200){alert('Could not execute GetFeature request'); return false;}
	//alert(ajaxRequest.status)
	
	// 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;}
	//alert('no of features = '+feature.length)
	
	// process the collection caught
	var showHighlights = true;
	
	if (feature.length > 0)
	{
		//alert('polypikamode = '+polypikaMode);
		//alert('report = '+report)
		//alert('list = '+list)
		
		// check to see if we have too many polygons
		if (feature.length > gfiLimit) 
		{
			alert('You have selected more than '+gfiLimit+' polygons for interactive extraction. \nPlease reduce your extraction area. \nFor larger areas NuMaps can provide an offline extraction service.\nPlease contact NuMaps about this optional service.'); 
			showHighlights = false; 
			genLoadStatus('', false);
			return false;
		}

		// Ok we have not busted the limoit so now process collection
		if(polypikaMode)
		{
			addToTerritory(ajaxRequest, feature, serviceBase, dataStore, typeName);
			if(fln !=''){deleteit('data/'+fln);}
			return true;
		}
		else if (report)
		{
			//genLoadStatus('Compiling GFI report ...', true);
			// Generic reporting function for the features located
			//alert('length of features = '+feature.length)
			reportIt(ajaxRequest, feature, serviceBase, dataStore, typeName, showHighlights, searchType)
			if(fln !=''){deleteit('data/'+fln);}
			return true;
		}
		else if(list)
		{
			// function to add all the polygons into the collection array
			listIt(ajaxRequest, feature, serviceBase, dataStore, typeName);
			if(fln !=''){deleteit('data/'+fln);}
			return true;
		}
		
	}
	else
	{
		alert('No Matching Features. This could be a for a number of reasons; please check your request process.');
		deleteSelection();
		genLoadStatus('', false);
		return false;
	}
	
}

//----------------------------------- fetch object function --------------------------------------------
function fetchObjects(ajaxRequest)
{
	genLoadStatus('GetFeature Request ...', true);
	// Find out how many features in XML
	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");
	
	// return the features object
	//alert('done')
	genLoadStatus('GetFeature Request Done ...', false);
	return features;
}

function getAttribsForLayer(drapeFile)
{
	//alert('drapeFile in getAttribsForLayer (gfiUtls) = '+drapeFile)
	// just in case strip out the actual drape filename
	var compareFilename = drapeFile;
	var parts = drapeFile.split(applicationBase+'inc/sld/')
	if(parts.length > 1) {compareFilename = parts[1];}

	// 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++ )
	{
		attributeInfo[k] = new Array(6);
		attributeInfo[k][0] = compareFilename;
		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] = '';			// this is the default
		//alert(attributeInfo[k])
	}
	return targetNames.length;
}

function getAttribsForDrape(drapeFile)
{
	//alert('drapeFile in getAttribsForDrape (gfiUtils)= '+drapeFile)
	// just in case strip out the actual drape filename
	var compareFilename = drapeFile;
	var parts = drapeFile.split(applicationBase+'inc/sld/')
	if(parts.length > 1) {compareFilename = parts[1];}
	
	// Get the XML file from server that contains the list of report attributes - inc/drapelists.xml
	attributeInfo = new Array();
	//alert(controlFile)
	
	// load the drapelist xml file into DOM from user specified file
	var Url = applicationBase+controlFile;			// this is set in main html program
	var query="?"+new Date().getTime();				// this is to avoid file cache issues
	ajaxRequest = loadXml(Url, query);
	if(ajaxRequest.status != 200){alert ('Error getting control XML file'); return;}

	// Find out how many Themes
	var drapes = ajaxRequest.responseXML.getElementsByTagName("Drapes");
	//alert('drapes= '+drapes.length)
	var themes = drapes[0].getElementsByTagName("Theme");
	//alert('themes = '+themes.length)
	if (themes.length == 0) {return 0;}

	// now loop through all the themes in XML
	var len1 = themes.length;
	//alert('themes length = '+len1)
	for (var ii=0; ii< len1; ii++)
	{
		// find out how many Drapes within this Directory
		var drape = themes[ii].getElementsByTagName("Drape");
		
		// parse the XML to get the report attributes for this drape definition
		if (drape.length > 0)
		{
			var len2 = drape.length;
			for (var l=0; l< len2; l++)
			{
				var filename = drape[l].getAttribute('file');
				//alert('drapeFile going in '+compareFilename)
				//alert('file to compare = '+filename)
				if(filename == compareFilename)
				{
					// now get the Attributes and store into arrays for later
					if(!drape[l].getElementsByTagName("Attribute")){	break;	}
					{	
						var attributes = drape[l].getElementsByTagName("Attribute");
						//var attributeDetails = attributes[k].getElementsByTagName("AttributeDetails")
						//alert ("there are "+attributes.length+" attributes in this Drape definition")
						if (attributes.length > 0)
						{
							var len3 = attributes.length;
							for (var k=0; k < len3; k++)
							{
								var aName = attributes[k].getAttribute('name');
								var aSumit = attributes[k].getAttribute('sumit');
								var aFilter = attributes[k].getAttribute('filter');
								var aAttrib = attributes[k].getAttribute('attrib');
								//alert(filename+" - "+aName+" - "+aSumit+" - "+aAttrib+" - "+aFilter);
								attributeInfo[k] = new Array(6);
								attributeInfo[k][0] = filename;
								attributeInfo[k][1] = aName;
								attributeInfo[k][2] = aSumit;
								attributeInfo[k][3] = aAttrib;  // this is the attribute code name used for key matching 
								attributeInfo[k][4] = aFilter;

								// now see if there are any attribute values/ranges available for this attribute
								attributeInfo[k][6] = '';			// this is the default

								if (attributes[k].getElementsByTagName("AttributeDetails"))
								{
									var attributeDetails = attributes[k].getElementsByTagName("AttributeDetails");
									//alert('number of details tags = '+attributeDetails.length)
									for (var x=0; x < attributeDetails.length ; x++ )
									{
										var type = attributeDetails[x].getAttribute('type');
										//alert('Attrib Details Type = '+type)
										if (type=='list')
										{
											var attOptions = attributeDetails[x].getElementsByTagName('Option')
											//alert('number options = '+attOptions.length)
											if(attOptions.length > 0)
											{
												var allOption = '';
												for (var y=0; y<attOptions.length ; y++)
												{
													var thisOption = attOptions[y].firstChild.nodeValue;
													if(y == 0) {allOptions = thisOption;}
													else {allOptions = allOptions+','+thisOption;}
												}
												attributeInfo[k][6] = allOptions;
											}
										}
										else if (type == 'positiveRange')
										{
											var lowValue = attributeDetails[x].getAttribute('lowValue');
											var highValue = attributeDetails[x].getAttribute('highValue');
											if (parseInt(lowValue) < parseInt(highValue))
											{
												attributeInfo[k][6] = lowValue+','+highValue;
											}
										}

									}
									
								//alert('all options for this Attribute = '+attributeInfo[k][6]);
										
								}

							}
							//alert('att length = '+attributes.length)
							return attributes.length;
						}
						else
						{	return 0;};
					}
				}
			}
		}
	}
	return ;
}



// ----- this is a generic routine to use SLDs to highlight a collection of polygons defined in sqlString ----//
function highlightCollection( serviceBase, dataStore, typeName, sqlString, sldTitleData, nameData, attName, attLabel)
{
	genLoadStatus('Highlighting Results ...', true);
	
	// set parameters to build a new SLD_BODY
	layer = typeName+":"+dataStore;
	filter= sqlString;
	fillPatt = areaFillBase+"blackdiagonal.png";
	fillPattForm = "image/png";
	labelName = attLabel;	
	fillColor = "#FFFFFF";
	lineColor = "#FF0000";
	fillOpac = 0.2;
	lineThickness = 4;
	solidBorder = false;
	
	// highlight the collecion
	highlightSelectedPolygons(layerName, filter, nameData, sldTitleData, attName, labelName, solidBorder, lineColor, lineThickness, fillColor, fillOpac, fillPatt, fillPattForm, sldAbstract)

	genLoadStatus('', false);
	return true;
}



// this will reset all highlight layers and remove the reports from the screen
// this is activated on the report itself.
function deleteSelection()
{
	genLoadStatus('', false);
	
	if(document.getElementById("reportHolder"))	{	document.getElementById("reportHolder").style.display="none"; }
	if(document.getElementById("reportopen"))	{	document.getElementById("reportopen").style.display="none";}
	if(document.getElementById("gfiDD"))		{	document.getElementById("gfiDD").title = 'Click to set to pick mode';}
	if(document.getElementById("reptButton"))
	{
		document.getElementById("reptButton").src='images/rept_off.jpg';
		document.getElementById("reptButton").title='Show Report';
	}
	if(document.getElementById('attribHolder')) 
	{ 
		document.getElementById('attribHolder').style.display='none';
		//document.getElementById('all').checked=true;
	}
	
	if (DrapeHighlight){DrapeHighlight.setVisibility(false);}
	if (collectLayer){collectLayer.setVisibility(true);}
	if (vectorLayer){vectorLayer.setVisibility(false);	}

	//alert('deleting New SLD file :'+applicationBase+'data/  '+newSldFile);
	
	if(newSldFile)
	{	if (filePresent(newSldFile) )	{	deleteit(newSldFile); }}
	//alert(applicationBase+newCsvFile)
	if(newCsvFile) 
	{	if (filePresent(newCsvFile) )	{	deleteit(newCsvFile);	}}
	//alert(applicationBase+gfiXmlFile)
	if(gfiXmlFile)
	{	if (filePresent(gfiXmlFile) )	{	deleteit(gfiXmlFile);	}}

	// remove the click control
	//alert ('cleaning up controls')
	if (click != null){click.destroy(); click = null;}

	//make sure there are no lingering Drag controls
	if(map.controls.length > 0)
	{	for (var i = 0; i< map.controls.length; i++) 
		{
			//alert('control : '+map.controls[i].displayClass);
			if(map.controls[i].displayClass == "olControlDragFeature")
			{	map.controls[i].deactivate();	}
		} 
	}

	// set mode back to non pickMode
	pickMode=false;
	//resetZlevels();
	//alert('done')
}
function closeReport()
{
	if(document.getElementById("reportHolder"))	{document.getElementById("reportHolder").style.display="none";}
	if(document.getElementById('reportopen'))	{document.getElementById('reportopen').style.display='block';}
	//indigenousLOC_collection.mergeNewParams({'dummy': Math.random()}); // force a refresh
}
function showReport()
{
	if(document.getElementById('reportHolder'))	{document.getElementById('reportHolder').style.display='block';}
	if(document.getElementById('reportopen'))	{document.getElementById('reportopen').style.display='none';}
	report=true;
}

//--------------------- GML Parser ------------------//
function gmlParser(ajaxRequest, defs, content)
{
	var featureCollection = ajaxRequest.responseXML.getElementsByTagName("FeatureCollection");
	//alert('feature collection = '+featureCollection.length)
	
	// Loop thru all Features caught in the GFI and build the report
	if(featureCollection.length == 0) {alert("Can't find a Feature Collection near this point"); return false;}
	var k = 0;
	var attnum = 0;
	for (var j=0; j<featureCollection.length; j++)
	{
		// Find Out how many FeatureSets in collection
		var featureSet = featureCollection[j].getElementsByTagName("FeatureSet");

		//alert('featureSet = '+featureSet.length)
		if (featureSet.length == 0) {alert("Can't find a Feature Set near this point"); return false;}
		for (var jj=0; jj<featureSet.length ; jj++)
		{
			// Get metadata for each Feature Set
			var definition = featureSet[jj].getElementsByTagName("Definition");
			var propertyDef = definition[0].getElementsByTagName("PropertyDef");
			var feature = featureSet[jj].getElementsByTagName("Feature");
			if(feature.length > 0)
			{
				// step thru each feature accumulating the data into a flat arrays (defs & content)
				for (var xml=0 ; xml<feature.length ; xml++ )
				{
					var propertyVal = feature[xml].getElementsByTagName("PropertyVal");
					//alert('number of values = '+propertyVal.length)

					if(propertyVal.length>0)
					{
						attnum = propertyVal.length;
						
						// now process each Feature's property Value
						for (var jjj=0; jjj<propertyVal.length; jjj++)
						{
							// now get the PropertyDefs and the PropertyVal matched up	
							defs[k] = propertyDef[jjj].getAttribute('name');
							content[k] = ''
							if(propertyVal[jjj].firstChild) {content[k] = propertyVal[jjj].firstChild.nodeValue;}
							k=k+1;					
						}
					}
				}
			}
		}
		
	}
	//alert('total elements = '+defs.length+ ' in groups of '+propertyVal.length);
	return attnum;
}

function dblClickGetFeatureInfo()
{
	//----------- set up the doubleclick event for a getfeatureinfo request on a DDrapes layer -------//
	map.events.remove('dblclick');
	map.events.register('dblclick', map, function (e) 
	{
		// this will delete any report collection and its vectors
		deleteSelection()
		// set up the getfeatuerinfo request to pick off the polygon ID
		filter='';
		uri = meshBlocksBase;
		var bbox = map.getExtent().toBBOX(); 
		var x=e.xy.x; var y=e.xy.y; 
		var width = map.size.w; var height=map.size.h;
		rad = 0; 
		count = 1;
		
		lineSld = layFile;
		wmslayer = drapeWmslayer;
		//alert('lineSld in dblclick = '+lineSld)
		//alert('wmslayer in dblclick = '+wmslayer)
		
		var infoForm = 'text/xml; subtype="bxfs/0.0.2"';
			
		// this does all the work in getting the data and making the report on a doubleclick for a DDrape layer
		getAttributeReport(e, uri, bbox, x, y, width, height, lineSld, wmslayer, infoForm, '2');
		Event.stop(e);
	});	
}

function clickGetFeatureInfo()
{
	if(click != null){click.destroy(); click = null;}
	
	// setup a single mouse click control for getfeatureinfo reports
	click = new OpenLayers.Control();
	OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, 
	{                
	    defaultHandlerOptions: 
		{
		    'single': true,
            'double': false,
            'pixelTolerance': 10,
            'stopSingle': false
           // ,'stopDouble': false
        },

        initialize: function(options) 
		{
            this.handlerOptions = OpenLayers.Util.extend
			(
				{}, this.defaultHandlerOptions
            );
            OpenLayers.Control.prototype.initialize.apply
			(
                this, arguments
            ); 
                this.handler = new OpenLayers.Handler.Click
				(
					this, {
                            'click': this.trigger
                          }, this.handlerOptions
                );
        }, 
	
        // do this on the mouse click
        trigger: function(e) 
		{
			if(polypikaMode) {return}
			// remove other click controls that could conflict
			if (terrSelectControl)	{	terrSelectControl.deactivate(); }
			if (selectControl)		{	selectControl.deactivate();		};
			
			// abort if a layer is not active
			if(!infoForm || !layLineSld) {return;}
			pickMode = true;
						
			// set up the getfeatuerinfo request to pick off the polygon ID
			uri = meshBlocksBase;
			var bbox = map.getExtent().toBBOX(); 
			var x=e.xy.x; var y=e.xy.y; 
			var width = map.size.w; var height=map.size.h;
					
			// set up target layer parameters
			//lineSld = layLineSld;
			//wmslayer = layWmslayer;
			rad=5;
			count=20; 
		
			// do the getFeatureRequest
			getAttributeReport(e, uri, bbox, x, y, width, height, layLineSld, layWmslayer, infoForm, '1');
        }			
	});
}

function getAttributeReport(e, uri, bbox, x, y, width, height, lineSld, wmslayer, infoForm, clicks)
{
		//alert('wmslayer = '+wmslayer)
		//alert(uri)
		//alert(lineSld)

		if(lineSld)
		{
			// carry out the getfeatureinfo request
			ajaxRequest = getFeatureInfoRequest(uri, 'GetFeatureInfo', lineSld, '1.3.2', 'WMS', srs, bbox, x, y, wmslayer, width, height, rad, count, infoForm);
			
			if(ajaxRequest.status != 200){return;}
			
			// Check to see if there were any errors from Ajax request
			var exceptions = ajaxRequest.responseXML.getElementsByTagName("ServiceExceptionReport");	
			if (exceptions.length > 0) 
			{
				var errors = exceptions[0].getElementsByTagName("ServiceException");
				var error = errors[0].firstChild.nodeValue;
				//alert('returned error = '+error); 
				return false;
			}
						
			// use the GML parser to load data into reporting arrays	
			var atts = ajaxRequest.responseXML.getElementsByTagName("PropertyDef")
			currentAttsOnClick = atts.length;
			if(atts.length == 0) {return;}
			else
			{
				defs = []; 	content = []; nic = 0;
				if(filter)
				{
					var counts = filter.split(",");
					if(counts[0]== ''){nic=0}
					else if(counts.length > 0){nic=counts.length;}
				}

				// use the GML parser to load data into reporting arrays
				var attribs = gmlParser(ajaxRequest, defs, content);
				
				//alert('clicks = '+clicks)
				if(clicks == '2')
				{
					//currentAtts = currentAttsOnClick;
					// this will delete any report collection and its vectors
					//deleteSelection();
					
					// look for an attribute with CODE/NAME as its name otherwise use first attribute following GEOMETRY
					attName=defs[1];  filter = content[1]; 
					//alert(attName+" : "+filter)
					for (var i=0; i<defs.length; i++)
					{
						var code = defs[i].split('CODE');
						if(code.length > 1){attName = defs[i]; filter = content[i]; break;}
						var code = defs[i].split('NAME');
						if(code.length > 1){attName = defs[i]; filter = content[i]; break;}
					}
					//alert(attName+" : "+filter)
					labelName=attName;
				
					// set up the new temp sld filename
					if(newSld != '') { deleteit(newSld); }
					getNewSldName(lineSld) ;							// outputs newTempSldPath and newTempSldFile
					newSld = "sld/"+newTempSldPath + newTempSldFile;
					
					// set up the new collection sld file
					//alert('deleting Sld = '+applicationBase+newSld)
					
					//newCollSld = 'newColl'+new Date().getTime()+'.xml';
					//newSld = "data/"+newCollSld;
					var fillColor = '#FFFFFF';
					var lineColor = '#FF0000';
					var lineThickness = '4';
					var fillOpac = '0.2';
					var fillPatt = areaFillBase+'blackdiagonal.gif';
					var fillPattForm = 'image/gif';
					//var fillPatt = '';	var fillPattForm = '';
					var solidBorder = false;

					//alert ("SLD Data = "+layerName+" : "+sldTitleData+" : "+nameData+" : "+opValue+"\n"+sldAbstract);

					highlightSelectedPolygons(layerName, filter, nameData, sldTitleData, attName, labelName, solidBorder, lineColor, lineThickness, fillColor, fillOpac, fillPatt, fillPattForm, sldAbstract)

				}
				// now report attributes into a popup table
				simpleReport('mapSurround', defs, content, attribs);
		}
	}
}
function startReq(uri, gfiParams)
{
	// check for trailing ? on URI - cater for config=xxx on end
	var lastChar = uri[uri.length-1];
	if(lastChar != '?')
	{	
		var parts = uri.split('?');
		if(parts.length == 1 ) { gfiParams='?';} else{ gfiParams='&';}
	}
	return gfiParams;
}

function getFeatureInfoRequest(uri, request, lineSld, version, type, srs, bbox, x, y, layer, width, height, rad, count, infoForm)
{
	//alert('hello world')
	// check that lineSld a full url
	var parts = lineSld.split('://');
	if(parts.length < 2){lineSld = applicationBase+'inc/sld/'+lineSld;}
	
	// initialise the request
	//alert('lineSLD = '+lineSLD)
	getSldInfo(lineSld);
	//alert ("SLD Data = "+layerName+" : "+sldTitleData+" : "+nameData+" : "+opValue+"\n"+sldAbstract);
	//getSldResource(lineSld);
	//if(layer == null || layer ==''){getSldInfo(lineSld); layer = layerName;}
	layer = layerName;
	if(infoForm == null || infoForm == ''){infoForm = 'text/xml; subtype="bxfs/0.0.2"';}
	if(rad == 0 || rad == null){rad = 5;}
	if(count == 0 || count == null){count = 1;}
	
	ajaxRequest = null;	
	var gfiParams = '';
	gfiParams = startReq(uri, gfiParams);
	

	// build up the request
	gfiParams = "REQUEST="+request;
	//if(sldUrl !=''){gfiParams += "&SLD="+sldUrl;}						
	gfiParams += "&VERSION="+version;
	gfiParams += "&SERVICE="+type;
	gfiParams += "&SRS="+srs;
	gfiParams += "&BBOX="+bbox;
    gfiParams += "&X="+x;
    gfiParams += "&Y="+y;
    gfiParams += "&QUERY_LAYERS="+layer;
	gfiParams += "&WIDTH="+width;
	gfiParams += "&HEIGHT="+height;
	gfiParams += "&RADIUS="+rad;
	gfiParams += "&FEATURE_COUNT="+count;
	gfiParams += '&INFO_FORMAT='+infoForm;
	
	//alert('gfiParams = '+gfiParams)
	
	// If report is a simple text/html report send to a new window	
	if(infoForm == 'application/x-cubestor-any' || infoForm == 'text/html')
	{			
		makePopup(uri+gfiParams, '500', '300', 'both')
		return null;
	}
	else // get the report details 
	{
		if(account!=''){gfiParams += "&accCode="+account;}
		// execute the getFeatureInfo request on server via proxy
		//alert(uri+gfiParams)
		ajaxRequest = proxyRequest(uri, gfiParams, '','POST')
		return ajaxRequest;
	}
}

function getFeatureRequest(uri, request, type, srs, dataStore, typeName, gfiFilter, outFormat)
{	
/*	alert('uri = '+uri)
	alert('request = '+request)
	alert('type = '+type)
	alert('srs = '+srs)
	alert('datastore = '+dataStore) // eg ABS
	alert('typename = '+typeName)	// eg SUBURBS
	alert('gfiFilter = '+gfiFilter)
	alert('outFormat = '+outFormat)
*/
	//alert('typename = '+typeName)	// eg SUBURBS
	
	// initialise the request
	ajaxRequest = null;
	gfiParams = '';
	//gfiParams = startReq(uri, gfiParams);

	// build up the request
	gfiParams += "REQUEST="+request;
	gfiParams += "&SERVICE="+type;
	gfiParams += "&SRS="+srs;
    gfiParams += "&DATASTORE="+dataStore;
	gfiParams += "&TYPENAME="+typeName;
	gfiParams += "&OUTPUTFORMAT="+outFormat;
	gfiParams += "&FILTER="+gfiFilter;
	if(account!=''){gfiParams += "&accCode="+account;}

	// execute the getFeature request on server via proxy
	// makePopup(uri+gfiParams, '600', '600', 'both')
	//alert(uri+gfiParams)
	ajaxRequest = proxyRequest(uri, gfiParams, '', 'POST');
	return ajaxRequest;

}
function exitPolygonAggregation()
{
	deleteSelection();				
	document.getElementById("reptContHolder").style.display="none";	
	document.getElementById("reportopen").title="Show Report";			
	normalDiv("reportopen"); 
	normalDiv("gfiDD"); 
	document.getElementById("gfiDD").title="enter polygon pick mode";
	removeAllControls();
	//alert('userdata = '+userdata+" file = "+geocodedFile)
	if(userdata)
	{
		showUserPoints(geocodedFile);
		initializeForms();
	}
	//alert('reactivating upload control'); activateControls();
	
}

function showHideInfoPanel(id)
{
	
	var status = document.getElementById(id).title;
//alert(status)
	if(status == 'enter polygon pick mode' || status == 'Re-enter Polypika Mode')
	{
		document.getElementById("reptContHolder").style.display="block";
		document.getElementById(id).title="exit polygon pick mode";
		depressedDiv(id);
		pickMode=true;

		// force opacity of DDrape to be 50% 
		DemoDrape.setOpacity(0.5);
		myslider.setPosition(0.5);
/*
		if(activeLayerName != '' || activeLayerName != null)
		{
			resetTerritory();
			activeLayerName = null;
		}
*/
	}
	else 
	{
		document.getElementById(id).title="enter polygon pick mode";
		document.getElementById("reptContHolder").style.display="none";
		normalDiv(id);
		pickMode=false;
		exitPolygonAggregation();
	}

}

function saveAs(theFile)
{
	//alert('the File = '+theFile)
	if(theFile == null || theFile == '') {return;}
	if (fadeLayer != null)
	{	
		document.getElementById("formHolder").style.display="block"; 
		document.getElementById("collName").focus(); 
	}
}
function activateGfiClickControl()
{
	// make sure any click event is deactivated
	deleteSelection();
	
	// now create a new click control
	clickGetFeatureInfo();
	click = new OpenLayers.Control.Click();          
	map.addControl(click);
	click.activate();
	pickMode = true;
}

function highlightSelectedPolygons(layerName, filter, name, title, attName, labelName, solidBorder, colorBdy, lineWeight, colorFill, fillOpac, fillPatt, fillPattForm, abstract)
{	
	filter = filter.toString();

	// set some defaults
	if (labelName == ''){	labelName = null;	}		
	if (colorFill == ''){colorFill = "#00FF00";}	
	if (colorBdy == '') {colorBdy = "#FF0000";} 	
	if (title == '' || title == null){title = "Temporaqry SLD for Highlighting Purposes";}
	if (fillOpac == '' || fillOpac == null || fillOpac == 'undefined') {fillOpac = '0.3';} 
	if (lineWeight == '' || lineWeight == null || lineWeight== 'undefined') {lineWeight = '4';}

	// bust up the filter into array
	
	if(filter == '')	{ return; }
	var pieces = filter.split(",");
	var numbOfFeats = pieces.length;

	// write the first part of the SLD
	var highlightSld = "<StyledLayerDescriptor version='1.0.0' xmlns='http://www.opengis.net/sld' xmlns:sld='http://www.opengis.net/sld' xmlns:ogc='http://www.opengis.net/ogc' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.opengis.net/sld http://schemas.cubewerx.com/schemas/sld/1.0.0-cw/StyledLayerDescriptor.xsd'>";
	highlightSld += "<NamedLayer><Name>"+layerName+"</Name><UserStyle><Name>"+name+"</Name><Title>"+title+"</Title>";
	if(abstract != ''){	highlightSld += "<Abstract>"+abstract+"</Abstract>";	}			
	highlightSld += "<FeatureTypeStyle>";

	// ----------------------- Write out a new rule for a collection  --------------------------
	highlightSld += "<Rule>";
	
//	highlightSld +="<MaxScaleDenominator>4000000</MaxScaleDenominator>";
	
	highlightSld += "<Filter>";	
	if(numbOfFeats == 1)
	{	highlightSld += "<SqlExpression>"+attName+" = '"+filter+"'</SqlExpression>";	}
	else if(numbOfFeats > 1)
	{	
		cnt = 0;
		highlightSld += "<Or>";
		// Now write out the filter rules in batches of 50 as here+++
		// e.g. <SqlExpression>ILOC_CODE IN('ILOC2001301','ILOC2003101','ILOC2001501'++++)</SqlExpression>
		for (i=0; i<numbOfFeats; i=i+500)
		{
			
			
			string=attName+" IN(";
			for (j=i; j<i+500; j++)
			{
				if(j < numbOfFeats-1 && j < i+499)
				{	string = string+"'"+pieces[j]+"',";	}
				else
				{	string = string+"'"+pieces[j]+"')";
					if(j == numbOfFeats-1){break;}
				}
				
				// report on the progress of the process
				//cnt++;
				//var percentDone = Math.round(cnt/numbOfFeats*100);
				//alert(percentDone)
				//genLoadStatus(percentDone+'% Added to Styling Filter ...', true);
			}			
			highlightSld += "<SqlExpression>"+string+"</SqlExpression>";	
		}
		highlightSld += "</Or>";		
	}
	highlightSld += "</Filter>";
	

	// ------------------------ Add Area Fill ---------------------------
	if(colorFill != 'transparent' && !solidBorder)
	{
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Fill>";		
		highlightSld +=			"<CssParameter name='fill'>"+colorFill+"</CssParameter>";		
		highlightSld +=			"<CssParameter name='fill-opacity'>"+fillOpac+"</CssParameter>";		
		highlightSld +=		"</Fill>";		
		highlightSld += "</PolygonSymbolizer>";		
	}
	else if(colorFill != 'transparent' && solidBorder)
	{
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Stroke>";		
		highlightSld +=			"<CssParameter name='stroke'>"+colorBdy+"</CssParameter>";		
		highlightSld +=			"<CssParameter name='stroke-width'>5</CssParameter>";		
		highlightSld +=		"</Stroke>";		
		highlightSld += "</PolygonSymbolizer>";		
		
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Fill>";		
		highlightSld +=			"<CssParameter name='fill'>"+colorFill+"</CssParameter>";		
		highlightSld +=			"<CssParameter name='fill-opacity'>1</CssParameter>";		
		highlightSld +=		"</Fill>";		
		highlightSld += "</PolygonSymbolizer>";		
	}
	else if(colorFill == 'transparent' && !solidBorder)
	{
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Fill>";		
		highlightSld +=			"<CssParameter name='fill'>transparent</CssParameter>";		
		highlightSld +=		"</Fill>";		
		highlightSld +=	"</PolygonSymbolizer>";		
	}
	else if(colorFill == 'transparent' && solidBorder)
	{
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Stroke>";		
		highlightSld +=			"<CssParameter name='stroke'>"+colorBdy+"</CssParameter>";		
		highlightSld +=			"<CssParameter name='stroke-width'>5</CssParameter>";
		highlightSld +=		"</Stroke>";		
		highlightSld += "</PolygonSymbolizer>";		
		
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Fill>";		
		highlightSld +=			"<CssParameter name='fill'>transparent</CssParameter>";
		//highlightSld +=		"<CssParameter name='fill-opacity'>1</CssParameter>";
		highlightSld +=		"</Fill>";		
		highlightSld += "</PolygonSymbolizer>";		
	}

	// ------------------------- Add Pattern Fill
	if(fillPatt != '' && fillPattForm != '')
	{
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Fill>";		
		highlightSld +=			"<GraphicFill>";		
		highlightSld +=				 "<Graphic>";		
		highlightSld +=					"<ExternalGraphic>";		
		highlightSld +=						"<OnlineResource xlink:href='"+fillPatt+"' />";		
		highlightSld +=						"<Format>"+fillPattForm+"</Format>";		
		highlightSld +=					"</ExternalGraphic>";		
		highlightSld +=				"</Graphic>";		
		highlightSld +=			"</GraphicFill>";		
		highlightSld +=		"</Fill>";		
		highlightSld += "</PolygonSymbolizer>";		
	}

	// -------------------------- Add the Border line Symbolizer
	if(lineWeight != '' && lineWeight != 0 && colorBdy != '' && colorBdy != 'transparent' && !solidBorder)
	{
		highlightSld += "<PolygonSymbolizer>";		
		highlightSld +=		"<Stroke>";		
		highlightSld +=			"<CssParameter name='stroke'>"+colorBdy+"</CssParameter>";		
		highlightSld +=			"<CssParameter name='stroke-width'>"+lineWeight+"</CssParameter>";		
		highlightSld +=		"</Stroke>";		
		highlightSld += "</PolygonSymbolizer>";		
	}

	// ------------------------- Add Text Symbilizer
	
	if(labelName != null)
	{
		// check to see if there are more than one label name
		var labels = labelName.split(",");
		for (var k=0; k<labels.length; k++ )
		{	
			highlightSld += "<TextSymbolizer>";		
			highlightSld +=		"<Geometry>";		
			highlightSld +=			"<PropertyName>GEOMETRY</PropertyName>";		
			highlightSld +=		"</Geometry>";

			highlightSld +=		"<Label>";
			highlightSld +=			"<PropertyName>"+labels[k]+"</PropertyName>";
			highlightSld +=		"</Label>";
		
			highlightSld +=		"<Font>";		
			highlightSld +=			"<CssParameter name='font-family'>Verdana</CssParameter>";		
			highlightSld +=			"<CssParameter name='font-size'>12</CssParameter>";		
			highlightSld +=			"<CssParameter name='font-weight'>bold</CssParameter>";		
			highlightSld +=		"</Font>";		
			highlightSld +=		"<Fill>";		
			highlightSld +=			"<CssParameter name='fill'>#000000</CssParameter>";		
			highlightSld +=		"</Fill>";		
			highlightSld +=		"<Halo>";		
			highlightSld +=			"<CssParameter name='fill'>#FFFFFF</CssParameter>";		
			highlightSld +=		"</Halo>";		
			highlightSld += "</TextSymbolizer>";
		}
	}		
	//------------------------ close off the Rule
	highlightSld += "</Rule>";
	
	// now close off Sld
	highlightSld += "</FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";
	
	// now create the mask layer
	if(DrapeHighlight != null){	DrapeHighlight.destroy(); DrapeHighlight = null;}
	
	// create the Mask layer
	DrapeHighlight = new OpenLayers.Layer.WMS.Untiled( "Highlight Layer", meshBlocksBase, { sld_Body: highlightSld,  format: 'image/png', version:'1.1.3', quality: 'BEST', reaspect: false, transparent: true}, { tileSize: new OpenLayers.Size(512,512)});
	DrapeHighlight.addOptions({isBaseLayer: false,  buffer:2, visibility: true, reproject:true});
	map.addLayer(DrapeHighlight);
	registerLoadWheel(DrapeHighlight,  'loadWheelDrape');
	DrapeHighlight.setZIndex(map.Z_INDEX_BASE['Popup'] -4200);
	resetZlevels();
	//if(maskLayer){bringToTop(maskLayer);}
	//document.getElementById("eventsLogID").style.display='none'
}