function activateGfiClickControl()
{
	// create a new click control
	clickGetPolygon();		
	click = new OpenLayers.Control.Click();          
	map.addControl(click);
	click.activate();
}

// set up a click control for a DDrape layer
function clickGetPolygon()
{
	// setup a new single mouse click control for getfeatureinfo request
	if(click){click.destroy();}	
	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) 
		{
			// note e is generated on a mouse click event
			
			// get the event data including Bbox of window
			bbox = map.getExtent().toBBOX(); 

			x = e.xy.x; 
			y = e.xy.y; 
			width = map.size.w; 
			height = map.size.h;
              
			// pixels to real world coords
			var XY = map.getLonLatFromPixel(e.xy); 
			// real world coords to longitude-latitude for getFeatureRequest
			if (srs == "EPSG:900913")
			{
				var p =	decodePoint(XY);
				var point = google2geogs(p);
				p = decodePoint (point);			
			}

			// set up target layer parameters fro SLD
			getSldInfo(currentSldFile);
			//alert(layerName+" - "+titleData+" - "+nameData+" - "+themeData+" - "+opValue+"\n"+sldAbstract)
			//MochaUI.RptWindow(layerName,p[0],p[1]);

			// carry out the getfeatureinfo request and build highlight layer
			highlightPolygonsByGfi(5,1);
			
			// Build the Area Information Popup panel
			numaloadReport(layerName,p[0],p[1]); // see in init.js
		}			
	});
}

function highlightPolygonsByGfi(rad, count)
{
	// rad = radius about the point in pixels
	// count = max number allowed in collection
	if(currentSldFile)
	{
		// carry out the getfeatureinfo request	
		ajaxRequest = getFeatureInfoRequest(meshBlocksBase, 'GetFeatureInfo', currentSldFile, '1.3.2', 'WMS', srs, bbox, x, y, width, height, rad, count, infoForm);
		
		// was the GFI OK?
		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;
			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
		{
			// use the GML parser to load data into reporting arrays
			var featAtts = gmlParser(ajaxRequest);
			var feats   = featAtts.split(":")[0];
			var attribs = featAtts.split(":")[1];
				
			// look for an attribute with CODE/NAME as its name otherwise use first attribute following GEOMETRY
			for(var z=0; z<attribs; z++)
			{	
				//alert("z = "+ z +" : "+defArray[0][z])
				var code = defArray[0][z].split('CODE');
				if(code.length > 1){attName = defArray[0][z]; var ptr=z; break;}
				var code = defArray[0][z].split('NAME');
				if(code.length > 1){attName = defArray[0][z]; var ptr=z; break;}
			}

			// now split into polygon groups
			var filter = '';
			for(var i=0; i<feats ; i++)
			{
				//alert(contArray[i][ptr])
				if(i==0){filter = contArray[i][ptr];}
				else {filter+= ","+contArray[i][ptr];}

				// look for the BBox of the attributes
				//var bboxValue = '';
				//for(var a=0; a<attribs; a++)
				//{
				//	var code = defArray[0][z].split('BOX');
				//	if(code.length > 1){var bboxValue = contArray[0][z]; break;}
				//}
			}
			//alert('filter = '+filter); 
			//alert('bboxValue = '+bboxValue);
			labelName=attName;			
							
			// setup styling for highlight
			var fillColour = '#FFFFFF';
			var lineColour = '#FF0000';
			var lineThickness = '4';
			var fillOpacity = '0.5';
			var fillPat = areaFillBase+'blackdiagonal.gif';
			var fillPatForm = 'image/gif';
			var solidBorder = false; // this can optionally be used when there are multiple polygons in filter
		
			// construct the SLD xml string for the highlight layer - see utilsSld.js
			var newSld = buildTemporarySld
			(
				layerName,
				nameData,
				titleData,
				attName,
				sldAbstract,
				filter,
				fillColour,
				fillOpacity,
				lineColour,
				lineThickness,
				fillPat,
				fillPatForm,
				labelName,
				solidBorder
			)
			
			// create the DrapeHighlight layer
			//alert(newSld)
			if(DrapeHighlight){DrapeHighlight.destroy();}
			DrapeHighlight = new OpenLayers.Layer.WMS.Untiled( 'PolygonHighlight', numapsService, {SLD_BODY: newSld, format: drapeImage, version:'1.1.3', quality: 'BEST', reaspect: false, transparent:'true'});
			DrapeHighlight.addOptions({isBaseLayer: false, visibility: true, wrapDateLine: true, buffer: buff, reproject: true, opacity:'0.8' });
			registerLoadWheel(DrapeHighlight, 'loadWheelDrape');
			map.addLayer(DrapeHighlight);
			bringToTop(DrapeHighlight);
		}
	}
	else{alert('oops! no sld specified!'); }
}

//--------------------- GML Parser ------------------//
function gmlParser(ajaxRequest)
{
	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 attnum = 0;
	for (var j=0; j<featureCollection.length; j++)
	{
		// Find Out how many FeatureSets in collection
		var featureSet = featureCollection[j].getElementsByTagName("FeatureSet");

		
		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");
			attnum = propertyDef.length;
			var feature = featureSet[jj].getElementsByTagName("Feature");
			
			//setup the multi dimension array
			defArray = new Array(feature.length);
			contArray = new Array(feature.length);
			for (var i=0 ; i<feature.length; i++)
			{
				defArray [i] = new Array (attnum);
				contArray [i] = new Array (attnum);
			}

			// now pickoff all attributes and store in arrays
			//alert('features = '+feature.length)
			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)
					var k = 0;
					if(propertyVal.length>0)
					{										
						// now process each Feature's property Value
						for (var jjj=0; jjj<propertyVal.length; jjj++)
						{
							// now get the PropertyDefs and the PropertyVal matched up	
							defArray[xml][k] = propertyDef[jjj].getAttribute('name');
							if(propertyVal[jjj].firstChild) {contArray[xml][k] = propertyVal[jjj].firstChild.nodeValue;}
							k=k+1;					
						}
					}
				}
			}
		}
		
	}
	//alert('total elements = '+defs.length+ ' in groups of '+propertyVal.length);
	return feature.length+":"+attnum;
}

function getFeatureInfoRequest(uri, request, lineSld, version, type, srs, bbox, x, y, width, height, rad, count, infoForm)
{
	// check that lineSld a full url
	var parts = lineSld.split('://');
	if(parts.length < 2){lineSld = applicationBase+'inc/sld/'+lineSld;}
	
	// get basic info from SLD
	getSldInfo(lineSld);
	//alert ("SLD Data = "+layerName+" : "+sldTitleData+" : "+nameData+" : "+opValue+"\n"+sldAbstract);
	
	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;				
	gfiParams += "&VERSION="+version;
	gfiParams += "&SERVICE="+type;
	gfiParams += "&SRS="+srs;
	gfiParams += "&BBOX="+bbox;
    gfiParams += "&X="+x;
    gfiParams += "&Y="+y;
    gfiParams += "&QUERY_LAYERS="+layerName;
	gfiParams += "&WIDTH="+width;
	gfiParams += "&HEIGHT="+height;
	gfiParams += "&RADIUS="+rad;
	gfiParams += "&FEATURE_COUNT="+count;
	
	// set up an alternate request that can be shown ina popup window
	altGfiParams = gfiParams+'&INFO_FORMAT=text/html';

	// set up for a getfeatureinfo request
	gfiParams += '&INFO_FORMAT='+infoForm;
	if(account!=''){gfiParams += "&accCode="+account;}
	
	// execute the getFeatureInfo request on server via proxy
	//alert(uri+gfiParams)
	ajaxRequest = proxyRequest(uri, gfiParams, '','POST')
	
	// produce the attribute report in a popup (optional)
	//makePopup(uri+altGfiParams, '800', '400', 'both');
	return ajaxRequest;
}

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 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)

	// 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
	//alert(uri+gfiParams)
	ajaxRequest = proxyRequest(uri, gfiParams, '', 'POST');
	return ajaxRequest;

}
*/


