// ------------------------ function to get layer data from XML file into arrays -----------------
function getDrapeData(drapes)
{
	//alert('drapes = '+drapes)
	Datts= new Array();
	var query='';
	var fileForDelete = '';
	var dummy = 0;

	// Get the Drapelist XML file
	if(drapes == 'nuservbeta' || drapes == 'numapsService' || drapes == 'numaps' || drapes == 'nuserv')
	{
		// set up the proxy call
		var appsUrl = applicationBase+'cf/proxycall.cfm?'			// coldfusion version proxycall
	 			
		// set up the drapelist server request and get drapelist
		drapeService  = 'url='+ meshBlocksBase.split('?')[0]+'&request=getnumadrapelist&accCode='+account+'&drapeclass=STANDARD';
		//alert(appsUrl+drapeService)
		ajaxRequest = fetchXml(appsUrl, drapeService, false, 'POST');
		
		// Find out how many Themes
		var drapesObj = ajaxRequest.responseXML.getElementsByTagName("Drapes"); // should only be one of these!
		var themes = drapesObj[0].getElementsByTagName("Theme");		
		//alert('number of themes available via DB = '+themes.length)
	}		
	else
	{
		// load the drapelist xml file into DOM from user specified file
		var query="?bruid="+new Date().getTime();		// this is to avoid browser cache issues
		//alert(applicationBase + drapes + query);
		ajaxRequest = loadXml(applicationBase + drapes, query);
		
		// Find out how many Themes
		var drapesObj = ajaxRequest.responseXML.getElementsByTagName("Drapes"); // should only be one of these!
		var themes = drapesObj[0].getElementsByTagName("Theme");		
		//alert('number of themes available via XML = '+themes.length)
	}

	if (themes.length == 0) {return false;}
	var k=0;
	
	// now loop through each Theme collecting theme level data 
	for (l=0; l<themes.length; l++)
	{
		Theme= '';	Title= '';	Dir= ''; Layer='';	

		// get Theme level attributes
		Theme = themes[l].getAttribute ("name");	// name is the only mandatory attribute
		if (themes[l].getAttribute("title"))	{Title = themes[l].getAttribute("title"); }
		if (themes[l].getAttribute("abstract"))	{Title = themes[l].getAttribute("abstract");}// abstract will always overwrite Title
		if (themes[l].getAttribute("dir"))		{Dir = themes[l].getAttribute("dir"); }
		if (themes[l].getAttribute("layer"))	{Layer = themes[l].getAttribute("layer");}
		if (themes[l].getAttribute("wmslayer"))	{WmsLayer = themes[l].getAttribute("wmslayer");}
		
		// get each set of Drape Attributes
		var drapeObj = themes[l].getElementsByTagName("Drape");		
		if (drapeObj.length > 0)
		{
			// step through each Layer tag getting all the attribute elements
			for (i=0; i<drapeObj.length; i++)
			{
				// If a type attribute is present process this DDrape
				Dtype = ''; Dstyle = ''; Dname = '';  Dtitle = ''; WmsLayer= ''; Dfile = ''; DDrapeId = ''; Sldflag = '' ; Dopac = 1; SldLoc = ''; cacheLocation = ''; DDeditable=false;
				if(drapeObj[i].getAttribute('name'))	{Dname = drapeObj[i].getAttribute('name');}
				
				// process the Drape
				if(drapeObj[i].getAttribute('type') != '')	
				{	
					// get all attributes from xml file 
					Dtype = drapeObj[i].getAttribute('type');
												
					// get optional attributes
					if(drapeObj[i].getAttribute('name'))	{Dname = drapeObj[i].getAttribute('name');}
					if(Dname == 'NO NAME') {break;}
					
					if(drapeObj[i].getAttribute('title'))	{Dtitle = drapeObj[i].getAttribute('title');}
					if(drapeObj[i].getAttribute('layer'))	{WmsLayer = drapeObj[i].getAttribute('layer');}
					if(drapeObj[i].getAttribute('file'))	{Dfile = drapeObj[i].getAttribute('file');}
					
					// for database generated drapelist attributes
					if(drapeObj[i].getAttribute('canuseSLD'))	{Sldflag = drapeObj[i].getAttribute('canuseSLD');}
					if(drapeObj[i].getAttribute('drapeEditable'))	{DDeditable = drapeObj[i].getAttribute('drapeEditable');}
					if(drapeObj[i].getAttribute('sldfile'))		
					{	
						//turn SLD location into a file URL for editing purposes
						SldLoc = drapeObj[i].getAttribute('sldfile');
						SldLoc = SldLoc.replace(/\\/g, "/");
						Dfile = SldLoc.split('sld/')[1];
						cacheLocation = Dfile;
					}

					// this is when a style is specified rather than a SLD
					if(drapeObj[i].getAttribute('style'))	
					{	
						if(drapeObj[i].getAttribute('style') != 'default') // skip past default styles
						{	Dstyle = drapeObj[i].getAttribute('style');	}
					}

					if(drapeObj[i].getAttribute('numapsDrapeID'))	
					{	
						// Insert the DID: string to signify a DrapeID
						DDrapeId = "DID:"+drapeObj[i].getAttribute('numapsDrapeID'); 
					}
					//alert('layer Sld = '+WmsLayer+'   style = '+Dstyle)
					//alert('sld = '+SldLoc+ '  Drape Id = '+DDrapeId)
					//alert ('Dfile = '+Dfile)

					// now just get the SLD details if available and if needed
					if(Dfile != 'coming' && Dfile != '' && (Dtitle == '' || WmsLayer == '' || Dname == '' || Dopac == ''))
					{
						//alert('opening sld = '+applicationBase+"inc/sld/"+Dfile)
						getSldInfo(applicationBase+"inc/sld/"+Dfile)
						if (sldAbstract != '')	{Dtitle = sldAbstract;}
						if (layerName != '')	{WmsLayer = layerName;}
						if (nameData != '')		{Dname = nameData;}
						if (opValue != '')		{Dopac = opValue;}
					}
					if(Dfile == '')
					{
						Dfile = 'getLegendGraphic';
						//if(Dname == '') {	Dname = Dstyle;	} 
					}
					
					// now stuff into the multidimension array string
					//alert('DDrapeId = '+DDrapeId)
					Datts[k] = WmsLayer+'|'+Theme+"|"+Title+"|"+Dir+'|'+Layer+'|'+Dname+"|"+Dfile+"|"+Dstyle+"|"+Dtype+"|"+Dtitle+'|'+Dopac+'|'+SldLoc+'|'+DDrapeId+'|'+DDeditable;
					//alert(Dname+"\n"+Datts[k])
					k=k+1;
				}
				else
				{ 
					alert('DDrape does not have a type set - skipping '+Dname+' DDrape')	
				}
			}
		}
	}
/*
	for (var i=0; i<Datts.length; i++)
	{		
		alert('attribute = '+Datts[i]);	
	}
*/
	//alert (numDrapes);
	return true;
}

// -------------------- function to get list of drapes and build a user Select List ---------------------//
function buildDrapeList(kill)
{
	//alert('kill Highlight = '+ kill)
	if(!getDrapeData(drapes)){alert('error in '+drapes+' file'); return false;}
	
	// now loop through all the themes/DDrape elements in DDrape Arrays
	var k=-1;
	var kk=0;
	var themeName = ''; var themeAvail = '';

	// please note that every row in the Datts array contains Theme and DDrape information
	// you need to recognise when a DDrape's theme changes to create a Theme level in tree
	//alert(Datts.length)
	for (var ii=0; ii<Datts.length; ii++)
	{
		// bust up the attributes into atts array
		var atts = Datts[ii].split("|")

		// If this is a new Theme then create the tree branch
		if(atts[1] != themeName) 
		{	
			k=k+1;
			kk=kk+1;
			themeName = atts[1]
			var themeTitle = atts[2];
			
			// look ahead to see if there are no valid DDrapes for this theme
			themeAvail = checkForDdrapes(ii, themeName);
			
			// save the layer name for swapSLD
			var back = kk;
			var themeUrl = "#";
				
			// if the buundle is not available to this user grey out the Theme level
			if (atts[8] != 'free' && atts[8] != 'FreeDrapes'  && atts[8] != 'subscribed' && atts[8] != 'DrapeStd') 
			{
				themeUrl = 'javascript:swapSld("", "", "coming", "", "", false);'
			}

			// Now build the Theme level in Tree
			Tree[k] = kk+"|0|"+themeName+"|"+themeUrl+"|"+themeTitle+"|"+themeAvail;
		}

		// continue on to build subordinate tree branches within a Theme
		k=k+1;
		kk=kk+1;
		var filename = atts[6];
		var dname = atts[5];
		var type = atts[8];
		var title = atts[9]; // this is the abstract
		var style = atts[7];
		var drapeid = atts[12];
		var editable = atts[13];
		//alert(dname+" : "+editable)
		//alert('Abstract for '+dname+'\n'+title) ;
		//alert(style)
		//alert('style = '+ style+ " type = "+type+ " file = "+filename+" drapeid = "+drapeid)

		// for typical free/subscribed SLD defined DDrape
		if ((type == 'subscribed' || type == 'free' || type == 'DrapeStd' || type == 'FreeDrapes' ) && (style == 'default' || style == '') && (filename != '' ) && editable) 
		{	
			//alert('available = '+drapeid+' and style = '+style)
			var highlight = true; 
			if(kill) 
			{	
				var swapper = "javascript:if(DrapeHighlight){DrapeHighlight.destroy();DrapeHighlight=null;	removeCreateVectors();} swapSld(\""+filename+"\", \""+style+"\",  \""+type+"\", \""+drapeid+"\", "+highlight+", "+gfiDoubleClick+");";
			}
			else 
			{	
				var swapper = "javascript:swapSld(\""+filename+"\", \""+style+"\",  \""+type+"\", \""+drapeid+"\", "+highlight+", "+gfiDoubleClick+");	if(collectLayer){collectLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -8000);}";
			}
		}
		
		// for unsubscribed DDrape or one with not enough information
		else if (type == 'unsubscribed' || type == 'coming' || filename == '' || (style != 'default' && style != '') || !editable)
		{
			//alert('unavailable = '+drapeid+' and style = '+style)
			//k=k+1;
			//kk=kk+1;
			var highlight = false;
			if(kill) 
			{	
				var swapper = "javascript:if(DrapeHighlight){DrapeHighlight.destroy(); DrapeHighlight=null; removeCreateVectors();} swapSld(\""+filename+"\", \""+style+"\",  \""+type+"\", \""+drapeid+"\", "+highlight+", "+gfiDoubleClick+");";
			}
			else 
			{	
				var swapper = "javascript:swapSld(\""+filename+"\", \""+style+"\",  \""+type+"\", \""+drapeid+"\", "+highlight+", "+gfiDoubleClick+"); if(collectLayer){collectLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -8000);}";
			}
		}

		// Now write out the DDrape tree level
		Tree[k] = kk+"|"+back+"|"+dname+"|"+swapper+"|"+title+"|"+highlight;
		//alert(Tree[k])
		
	totalTreeLength = kk
	}
/*	
	//------ Debugging -----
	
	for (var z = 0; z< kk; z++)
	{
		alert(Tree[z]);
	}
*/
}

// this fiunction just looks ahead in the array to make sure there are available DDrapes in a theme
function checkForDdrapes(ii, tName)
{
	var goodDrapes = 0
	// look at all DDrape rows from here until Theme changes
	for (var j=ii; j<Datts.length; j++ )
	{
		var jatts = Datts[j].split("|");
		if (jatts [1] == tName)
		{
			if (jatts[8] == 'subscribed' || jatts[8] == 'free' || jatts[8] == 'DrapeStd' || jatts[8] == 'FreeDrapes')
			{
				goodDrapes++;
			}
		}
		else
		{	break;	}
	}
	// now return true if there is more than zero available Ddrapes
	if(goodDrapes > 0) {return true;}
	else {return false;}
}

function removeAllDrapeLayers()
{
	// reset legend
	fadeLayer = '';
	showHideLegend('legendDD');		
	manageLegendControls();
	
	// remove the DDrape layer
	while(DemoDrape){DemoDrape.destroy(); DemoDrape = null;}
	buildTheDrapePickaTree();

	// remove all associated layers
	var i=0
	while(DrapeHighlight){DrapeHighlight.destroy(); DrapeHighlight = null; }
	while(SelectHighlight){SelectHighlight.destroy(); SelectHighlight = null; }	
	while(vectorLayer)	{vectorLayer.destroyFeatures(); vectorLayer = null; }
		
	// remove the doublclick for DDrapes layer
	if(map) {map.events.remove('dblclick');}
	//if(click){	map.removeControl(click); click.destroy(); click=null; }
}


//---------------------- Update the database with the new DDrape definition  ---------------------
function saveNewDrapeFile(newFileName)
{
	//alert('new file in saveNewDrapeFile= '+newFileName)	
	if(newFileName == '' || newFileName == null) {return;}
	
	// get file info from filename
	var fileParts = newFileName.split('/');
	var path = fileParts[1]
	var drapePath = fileParts[0]+'/'+path+'/';
	var drapeFile = fileParts[2];
	var fileParts = newFileName.split('.');
	var drapeExt = fileParts[1];
	var newDrapeId = ''
	
	// get the entered name from the user form
	var handle = document.getElementById('collName').value;
	var saveFileName = drapePath+handle.replace(/ /g, "_")+'.'+drapeExt;
	var newDrapeFileName = path+'/'+handle.replace(/ /g, "_")+'.'+drapeExt;
	var fullDrapeFileName = applicationBase+'inc/'+saveFileName;

	// check if already exists on server here;
	//alert('checking for new DDrape name = '+saveFileName)
	if (filePresent(saveFileName))
	{ 
		if(!confirm ('"'+handle+'" already exists.\nIf you continue you will overwrite this the existing DemographicDrape.\n\n Do you wish to continue?'))
		{
			document.getElementById("collName").focus();
			document.getElementById("collName").value='';
			return;
		}
	}

	// strip off the leading newSld and the trailing date stamp
	var parts = newFileName.split('_');
	var oldDrapeName='';

	// get and reconstruct the embedded source Ddrape SLD name
	if(parts.length > 1)
	{
		for(var i = 0;	i < parts.length-1 ; i++)
		{
			if(i == 1){oldDrapeName = parts[i];}
			else if(i > 1 ){oldDrapeName = oldDrapeName+'_'+parts[i];}
		}
	}
	
	oldDrapeName = drapePath + oldDrapeName + "." + drapeExt;
	oldDrapeFileName = oldDrapeName.replace(/sld\//, '');
	//alert('old DDrape Filename = '+oldDrapeFileName);
	
		
	// replace the new SLD file name with the destination filename on the server
	var source = '/inc/'+newFileName; 
	var destination = '/inc/'+saveFileName;

	if(!replaceFileCF(source, destination) ){alert('error replacing existing file');}
	//alert('file updated')

	// now make the form invisible
	document.getElementById('formHolder').style.display='none';
	
	// if drapelist from data base then update the database
	var result = 'OK';
	if(drapes == 'nuservbeta' || drapes == 'numapsService' || drapes == 'numaps' || drapes == 'nuserv')
	{	
		// set putstyles to false so that they can't write a new style
		putStyles=false;
		//alert('updating Numa Drapes DB')
		result = updateNumaDrapes(oldDrapeFileName, newDrapeFileName);
	}	
	if(result == 'Insert of SLD Drape Failed')
	{	alert('result = '+result);}
	

	// this will go back to the source and recreate the DrapeTree
	buildTheDrapePickaTree();
		
	// get data for searching
	prepareSearch();
	genLoadStatus('', false);
	loaded=true;
}

function updateNumaDrapes(oldDrapeFileName, newDrapeFileName)
{
	//alert(oldDrapeFileName)
	//alert(newDrapeFileName)
	
	// set up the parameters needed to create a database Drape record xxx
	var appsUrl = applicationBase+'cf/proxycall.cfm?'			// coldfusion version proxycall

	// switch file and path to location syntax
	var sldLocationFormat = newDrapeFileName.replace(/\//g, '\\');

	//if old and new files & namedata of both SLDs are the same assume an overwrite of exiting DDrape
	var overwriteSwitch = 'false';
	if(oldDrapeFileName == newDrapeFileName && checkForSameNamedata(oldDrapeFileName, newDrapeFileName))
	{		overwriteSwitch = 'true'; }
	
	var accnt = '';
	if(account!=''){accnt = "&accCode="+account;}

	// set up the drapelist server request and get drapelist
	drapeService  = "url="+ meshBlocksBase.split("?")[0] +
		"&request=numaPostSld&sld="+sldLocationFormat+
		accnt +
		"&Overwrite="+overwriteSwitch +
		"&putstyle="+putStyles;
	
	// run the update transaction
	//alert(appsUrl+drapeService)
	ajaxRequest = fetchXml(appsUrl, drapeService, false, 'POST');
	var result = ajaxRequest.responseText;
	//alert(result)
	return result;
}

function checkForSameNamedata(oldDrapeFileName, newDrapeFileName)
{	
	// get the DDrape name from the original DDrape
	getSldInfo(applicationBase+"inc/sld/"+oldDrapeFileName);
	var oldName = nameData;
	getSldInfo(applicationBase+"inc/sld/"+newDrapeFileName);
	var newName = nameData;	
	//alert(newName +", "+oldName);

	if(newName == oldName) {return true;}
	else {return false;}
}

// This will update the xml control file with the new DDrape
function updateDrapeListFile(drapename, newDrape, position)
{
	// set up the php url
	var parts = drapename.split('/');
	var Url = 'inc/insertNewDrape.php';
	
	// set up the parameters
	var params = '?file='+parts[1];
	params += '&datts='+newDrape;
	params += '&pos='+position;

	// do the work
	makeFile(applicationBase+Url, params, false, 'GET');
}

// ----------- update the Datts array -----------
function updateDatts (oldDrapeFileName, newDrapeFileName, oldName, newName, newDrapeId, oldTheme, newTheme)
{	
	// make sure you have a DDrape name to locate in Datts array
	if (newName == '' || newName == null)
	{	getSldInfo(applicationBase+"inc/sld/"+oldDrapeFileName); 
		newName=nameData;
	}

	// now get the new Abstract and old drape name from the new SLD
	if (oldName =='' || oldName == null && oldDrapeFileName != newDrapeFileName)
	{	getSldInfo(applicationBase+"inc/sld/"+newDrapeFileName);
		var newAbstract = sldAbstract;
		oldName=nameData;
	}
	
	// Update the old Datts Array with the new DDrapes data 
	var newDrapeDatts = []; var found=false;
	//alert('old Theme = '+oldTheme+' -- old Drape = '+oldName);
	//alert('new Theme = '+newTheme+' -- new Drape = '+newName);

	loop:
	for (var i=0; i<Datts.length; i++ )
	{
		var DattsParts = Datts[i].split('|')

		// If the same DDrape being updated
		if(DattsParts[5] == oldName )
		{
			// take a copy of the Datts array of this old Ddrape 
			newDrapeDatts = DattsParts;
			newDrapeDatts[1] = newTheme;
			newDrapeDatts[5] = newName;
			newDrapeDatts[6] = newDrapeFileName;
			newDrapeDatts[9] = newAbstract;
			var parts = newDrapeDatts[11].split('/sld/');
			newDrapeDatts[11] = parts[0]+"/sld/"+newDrapeFileName;
			newDrapeDatts[12] = newDrapeId;
			//alert(newDrapeDatts);

			// encode into a string element 
			for (k=0; k<DattsParts.length ; k++)
			{
				if(k == 0) {var newDrapeString = DattsParts[0];}
				else {newDrapeString = newDrapeString+'|'+DattsParts[k];}
			}

			// update existing Ddrape or insert the new one
			if(oldDrapeFileName != newDrapeFileName)	// if filenames are not the same the same assume an insert
			{	Datts.splice(i+1, 0, newDrapeString); 		}
			else										// else filenames are the same so this is an update 	
			{	Datts[i] = newDrapeString;		}
			found = true;
			break loop;	// we're done
		}
	}

	// set up the return string
	if (found)
	{
		//alert('position = '+position)
		//alert(i+"::"+newDrapeString)
		return i+"::"+newDrapeString;	// this returns the location of the old DDrape element in Datts
	}
	else
	{
		alert('no matching DDrape name');
		return 'error';
	}
}
//------ function to do as Save or replace old with new ----------//
function swapNewSld(newFileName,  currentSld)
{
	//alert('DrapeId = '+drapeId)
	//alert('currentDrapeId = '+currentDrapeId)
	//alert('currentDrapeStyle = '+currentDrapeStyle)
	//alert('currentDrapeLayer = '+currentDrapeLayer)
	oldFileName = currentSld;
	//alert(oldFileName+' >> '+newFileName)

	// if old file name and new file name are not blank the proceed
	if(oldFileName == '' || newFileName == '') 
	{	return;	}
	else
	{	
		getSldInfo(applicationBase+"inc/sld/"+oldFileName);
		oldName = nameData;
		oldTheme = themeData.toString();
		getSldInfo(applicationBase+"inc/"+newFileName);
		newTheme = themeData.toString();
		newName = nameData;
	}
	//alert  ('old theme = '+oldTheme+"   new theme = "+newTheme)
	//alert  ('old name = '+oldName+"   new name = "+newName)
		//alert(newFileName)
	// make sure that a new file exists on disk
	if ( filePresent(newFileName) )
	{
		// check for attempts to change the Theme or Drape Name on a replace for a style based DDrape
		if(putStyles || !isEditable)  
		{
			if (confirm('Cannot Overwrite the existing DemographicDrape stored as a Style in the database.\nNor can you edit a DDrape that is owned by another user.\nBy proceeding you will create a brand new DemographicDrape. \n\nDo you wish to proceed?'))
			{
				// undertake a new DDrape create
				saveAs(newFileName);
				return;
			}
		}

		// check if user is changing the theme
		else if (newTheme != oldTheme || oldName != newName)
		{
			//alert  ("old theme = <"+oldTheme+">   new theme = <"+newTheme+">")
			if (confirm('Cannot Overwrite the existing DemographicDrape Theme/Name in the database.\nBy proceeding you will create a brand new DemographicDrape. \n\nDo you wish to proceed?'))
			{
				// undertake a new DDrape create
				saveAs(newFileName);
				return;
			}
		}

		// for a legitimate SLD file replace only
		else 
		{
			// make sure user agrees to do this because oldFileName file will get stamped on
			if (confirm('By proceeding you will PERMANENTLY replace the existing DDrape with the newly edited DDrape. \n\nAre you sure you wish to proceed ?'))
			{
				// Clear the cache for the temporary new file
				//alert(oldFileName+' >> '+newFileName)
				getAndPurgeDrapeCache()

				// remove any DDrape from then screen
				removeAllDrapeLayers();
				//swapSld("", "", "", "", "", false);
				
				// rename the new filename to the old name
				newname = 'sld/'+oldFileName;
				existingFile = 	newFileName;
				if(!replaceFileCF('/inc/'+existingFile, '/inc/'+newname)){alert('could not rename the file');}
				
				// this will go back to the source and recreate the DrapeTree
				buildTheDrapePickaTree();
			
				// get data for searching
				prepareSearch();
				genLoadStatus('', false);
				loaded=true;

				return;
			
			}
		}
		
		
	}
}
function redraw(currentSld)
{
	// this will purge any Cache for the target DDrape	
	if(currentDrapeLayer == '' || currentDrapeLayer == 'undefined' || currentDrapeLayer == null)
	{	
		getSldInfo(applicationBase+"inc/sld/"+currentSld);
		currentDrapeLayer = layerName ;
	}
	oldFileName = currentSld;
	getAndPurgeDrapeCache();
	//purgeDrapeCache(currentSld); 
	DemoDrape.redraw(true); 
	document.getElementById("search").focus();
}

// this will go to the source defined in 'drapes' ,and build a new replacement DrapeTree	
function buildTheDrapePickaTree()
{
	
	// build the Drape tree
	genLoadStatus('DDrapes Loading XML File ....', true);
	getDrapeData(drapes)
	
	genLoadStatus('DDrapes Building Control ....', true);
	buildDrapeList(true);
	
	genLoadStatus('DDrapes Building Tree ....', true);
	treeTitle = "DemographicDrapes Library";
	//alert(Tree)
	createTree('treeContainer',  Tree,  0,  0,  treeTitle,  false);
	configRequest= '';
	configParams = '';
	genLoadStatus('', false);

}

function getAndPurgeDrapeCache()
{
	// get the drape number from the ID
	var drapeNumber = currentDrapeId.split(":");
	var drapeNo = drapeNumber[1];
	//alert('newFileName in purge = '+newFileName)
	
	// Clear the cache for the temporary new file
	if(newFileName != '')
	{
		var tempCache = newFileName.replace(/sld\//, '');	// trim off leading sld/
		tempCache = tempCache.replace(/.xml/, '');		// trim off trailing .xml
		//alert('cache being purged = '+tempCache)
		purgeDrapeCache(tempCache, drapeNo);
		//alert('temp cache gone')
	}
	// save the name of the name of the new SLDs cache group
	//oldTempCache = cacheGroup[0];

	// if this is a style-based DDrape then kill off the Style Cache
	//alert('style = '+currentDrapeStyle)
	//alert('drape layer = '+currentDrapeLayer)
	if(currentDrapeStyle != '' && currentDrapeLayer != '')
	{
		//alert(currentDrapeLayer)
		//alert(currentDrapeStyle)
		var cacheLayer = currentDrapeLayer.replace(/:/g, '');
		cacheLayer = cacheLayer.replace(/_/g, '');
		var cacheStyle = currentDrapeStyle.replace(/ /g, '');
		cacheStyle = cacheStyle.replace(/_/g, '');
		cacheStyle = cacheStyle.replace(/-/g, '');
		var styleCache = cacheLayer+"/"+cacheStyle;
		purgeDrapeCache(styleCache, drapeNo);
		//alert('style cache gone');
	}
		else
	{
		// clear existing cache for the old SLD file
		var oldCache = oldFileName.replace(/.xml/, '')	// trim off trailing .xml
		//alert('oldCache = '+oldCache)
		purgeDrapeCache(oldCache, drapeNo);
		//alert('non style cache gone')	
	}
}



/*
function dropCache(cacheLocation, drapeIdKill) 
{ 
	// set up the request to drop the cache for this sld
	var cUrl = meshBlocksBase+"request=dropNumaCache&cacheItem="+cacheLocation+"&drapeid="+drapeIdKill;
	var ldr = new Image(); 
	ldr.onError = function() {alert('NUMAPS ERROR: Failed to connect');}
	ldr.src = cUrl;
	ldr = "";
}
*/

function purgeDrapeCache(cacheName, drapeNo)
{
	// clear existing cache for the old SLD
	cacheGroup = cacheName.split('.')[0];
	clearCache(cacheGroup, drapeNo);
}
function clearCache(cacheLocation, drapeIdKill)
{
	//alert('drapeIdKill = '+drapeIdKill)
	//alert('cache location = '+cacheLocation)
	if(drapeIdKill)
	{	var request = 'request=dropNumaCache&cacheItem='+cacheLocation+'&drapeid='+drapeIdKill;	}
	else
	{	var request = 'request=dropNumaCache&cacheItem='+cacheLocation;	}
	//request += "&numakey="+numapsKey+"&domain=*.numaps.com.au";

	// set up the request to clear out the cache for this sld via the coldfusion proxy server
	//var query  = 'request=numaGetBBOX&typeid='+polyLayers+'&address='+currentAddress;
	
	//alert('before the purge \n' +request)
	var ajaxRequest = proxyRequest(request, '', 'GET');
	//alert(ajaxRequest.responseText)
	
	//var appsUrl = meshBlocksBase+'cf/proxycall.cfm?';					
	//var query  = 'url='+meshBlocksBase.split('?')[0]+"&"+request;


	//http://brad.ws.numaps.com.au/nuserv.cfm?request=dropNumaCache&cacheItem=cw/newSld_median_age_bordered_1298433448026&numakey=6A51FF3AF5DB50-22B-99999999&domain=*numaps.com.au
	//alert(meshBlocksBase + request)
	//var ajaxRequest = fetchXml(meshBlocksBase, request, false, 'GET');
	
}

// this is called in initialising function 
function prepareSearch()
{
	atts = [];
	attsStr = [];
	infoStr = [];

	// loop through all DDrapes and build a searchable array
	//alert(Datts.length)
	for(var i=0; i< Datts.length; i++)
	{
		// if a style then make it not accessible like the DDrape tree
		var accessible = true;
		atts = Datts[i].split("|");
		if(atts[7] != 'default' && atts[7] != '') 
		{	accessible = false;		}

		// build the search string for this DDrape
		var searchString = 	atts[5]+" :: "+atts[7]+" :: "+atts[9] ;
		attsStr[i] = searchString.toString(); 
		infoStr[i] = atts[5]+" :: "+atts[6]+" :: "+atts[9]+" :: "+atts[12]+" :: "+accessible+" :: "+atts[7];
	}
	
}

function doSearch(searchArray, keywordArray, caseSensitive)
{
	for (var n=0; n<keywordArray.length; n++)
	{
		// do the search here building up a list array of matched DDrapes
		for (var i=0; i<searchArray.length ; i++)
		{
			if(!caseSensitive) 
			{
				//alert(keywords[n])
				source = searchArray[i].toLowerCase();
				keyWd = keywordArray[n].toLowerCase();
			}
			else
			{
				source=	searchArray[i];
				keyWd = keywordArray[n];
			}
			if(source.search(keyWd) >= 0)
			{	
				// check to see if this match is already in list
				var included = false;
				for(var m=0; m<list.length; m++)
				{	
					if(list[m] == i) {included = true; break;}
				}
				// if not included already then add it
				if(!included) {list.push(i); }
				//included = false;
			}
		}
	}
	return list;
}

// search the searchable arrays to find any DDrape/Territory with matching keyword
function findIt(keyword, holdingDivId)
{
	//set up the searching and reporting arrays from the two different sources
	searchArray = []; 
	infoArray = [];

	// for DDrape searching
	if(searchOriginator == 'searchDD') 
	{
		searchArray = attsStr;
		infoArray = infoStr;
	}
	// for Territory searching
	else if(searchOriginator == 'searchTerr') 
	{	
		searchArray = searchTarget; 
		infoArray = infoTarget;
	}
	
	// check for multiple keywords separated by hyphan and get caseSensitivity indicator
	var keywords = keyword.split(',')
	var caseSensitive = document.getElementById('caseSens').checked;
	list = [];
	if(keywords.length > 0)
	{
		// do the search here building up a list array of matched DDrapes
		list = doSearch(searchArray, keywords, caseSensitive)
		
		// build the internal reporting div
		checkRemoveObject('searchResultsHolder');
		var searchTable = document.createElement('table');
		searchTable.id='searchResultsHolder'; 
		searchTable.setAttribute('id','searchResultsHolder');
		searchTable.style.marginLeft='5px';
		searchTable.style.marginRight='25px';
		searchTable.style.marginTop='5px';
		searchTable.style.marginBottom='5px';
		searchTable.style.width='90%';
		searchTable.style.height='100%';

			// build the table body
			var searchTableBody = document.createElement('body');
			searchTableBody.style.width='100%';
			searchTableBody.style.height='100%';
				
				// ------- write out number of matches line
				var row = document.createElement('tr');
					var cell = document.createElement('td');
					var textNode = document.createTextNode('There were '+list.length+' matches');
					cell.appendChild(textNode);
					cell.id='drape:'+i;
					cell.setAttribute('id','drape:'+i);
					row.appendChild(cell);
				searchTableBody.appendChild(row);
				
				// ------- write out spacer row
				var row = document.createElement('tr');
					var cell = document.createElement('td');
					cell.style.width='100%';
					row.appendChild(cell);
				searchTableBody.appendChild(row);
					
				// now list all the Object Names plus Abstracts
				for (var i=0; i<list.length ; i++)
				{
					// 
					var row = document.createElement('tr');
						var cell = document.createElement('td');
						cell.style.width='100%';
						var DDparts = infoArray[list[i]].split(" :: ");
						
						// ------- write out the Object Name
						var textNode = document.createTextNode(DDparts[0]); // assumes first in array is its name
						cell.appendChild(textNode);
						cell.style.fontSize = '12px';
						cell.style.fontWeight='bold';
						cell.style.color='#840404';
					
						// set interaction for DDrape searching
						if(searchOriginator == 'searchDD')  
						{
							cell.id='drapeName:'+i;
							cell.setAttribute('id','drapeName:'+i);
							var ddtype='Editable';
							if(!DDparts[4] || DDparts[4] == 'false'){cell.style.color='#3B52EB'; ddtype='Read Only';}
						
							// set the onclick event
							cell.title='Click here to load this '+ddtype+' DDrape';
							bindEvent(cell, 'click', loadDrape, 'false');
						}
						else if(searchOriginator == 'searchTerr') 
						{
							cell.id='territoryName:'+i;
							cell.setAttribute('id','territoryName:'+i);
							cell.style.color='#3B52EB'
							
							// set the onclick event
							cell.title='Click here to load this Territory';
							bindEvent(cell, 'click', loadTerritory, 'false');
						}
						row.appendChild(cell);
					searchTableBody.appendChild(row);

					// Optional Style row
					if(DDparts[5] > '' && searchOriginator == 'searchDD')
					{	
						var row = document.createElement('tr');
							var cell = document.createElement('td');
							var textNode = document.createTextNode("("+DDparts[5]+")");
							cell.appendChild(textNode);
							cell.style.color='#3B52EB';
							cell.style.width='100%';
							row.appendChild(cell);
						searchTableBody.appendChild(row);
					}
						
					// write out spacer row
					var row = document.createElement('tr');
						var cell = document.createElement('td');
						cell.style.width='100%';
						row.appendChild(cell);
					searchTableBody.appendChild(row);

					// write out the DDrape Abstract
					var textNode = document.createTextNode(DDparts[2]);
					cell.appendChild(textNode);
					cell.style.fontSize = '10px';
					cell.style.fontWeight = 'normal';
					cell.style.color='#3C3C3C';
					if(searchOriginator == 'searchDD')
					{
						cell.id='drapeAbs:'+i;
						cell.setAttribute('id','drapeAbs:'+i);
					}
					else
					{
						cell.id='territoryAbs:'+i;
						cell.setAttribute('id','territoryAbs:'+i);
					}
					//if(!DDparts[4] || DDparts[4] == 'false'){cell.style.color='#A3A3A3';}
					cell.style.whiteSpace='normal';
					row.appendChild(cell);
				searchTableBody.appendChild(row);
				
				// write out spacer row
				var row = document.createElement('tr');
					var cell = document.createElement('td');
					cell.style.width='100%';
					row.appendChild(cell);
				searchTableBody.appendChild(row);
			}
			searchTable.appendChild(searchTableBody);
		document.getElementById(holdingDivId).appendChild(searchTable);
		
/*
		// now highlight the search string
		for (var v=0; v<list.length; v++ )
		{
			var id = "drapeAbs:"+v;
			alert(id)
			for (var m=0; m<keywords.length ; m++)
			{
				var reslt = highlightText(document.getElementById(id), keywords[m], "boldText"); 
			}
		}
  */
		document.getElementById('details').style.display = 'block';
		//normalDiv('searchDD');
	}
}

function highlightText(container, what, spanClass) 
{
	var content = container.innerHTML,
        pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'),
        replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
        highlighted = content.replace(pattern,replaceWith);
    return (container.innerHTML = highlighted) !== content;
}

function loadDrape(evt)
{
	var e_out = getThisId(evt)
	var elNo = e_out.split(":");
	var parts = infoStr[list[elNo[1]]].split(" :: ");
	currentDrape = parts[1];
	swapSld('sld/'+parts[1], parts[5], '', parts[3], parts[4], gfiDoubleClick);
	
	// move selecetd DDrape up into current DDrape display window
	textDisplay('selectedDrape', parts[0])
		
	Event.stop(evt);
}
function loadTerritory(evt)
{
	var e_out = getThisId(evt);
	//alert('load Territory id = '+e_out)
	var elNo = e_out.split(":");
	var parts = infoTarget[list[elNo[1]]].split(" :: ");
	currentDrape = parts[1];

	// move selecetd file name up into current Territory display window
	textDisplay('selectedTerr',  parts[0]);
	
	// now go and display the newly selected Territory
	showTerritory(territoryFolder+parts[4])
		
	Event.stop(evt);
}

function toggleSearch(id)
{
	searchOriginator = id;
	var searchButt = document.getElementById(id);
	if(searchButt.title == 'Launch search panel')
	{
	
		document.getElementById("searchHolder").style.display="block";
		document.getElementById("keyword").focus();
		searchButt.title = 'Close search panel';
		highlightDiv(id);
	}
	else
	{
		document.getElementById("searchHolder").style.display="none";
		searchButt.title = 'Launch search panel';
		normalDiv(id);
	}
}

// -------------------------------------------------------------------------------------
function loadAnalysisOptions()
{
	// if this xml file has not been opened do it here
	if(analysisData == null)
	{	analysisData = loadXml(applicationBase + analysisDataXmlFile, '');}
	//alert(analysisData.responseXML.getElementsByTagName("Analysis").length); // should only be one of these!

	// build the Analysis options Input element
	checkRemoveObject('configDrapeLevelList');
	var selectBox = document.createElement('select');
	selectBox.id='configDrapeLevelList';
	selectBox.setAttribute('id','configDrapeLevelList');
	selectBox.style.width='100%';
	selectBox.style.height='20px';	
	bindEvent(selectBox, 'change', swapLevel, 'false');

	// now populate the Levels from XML
	AggLevel =  analysisData.responseXML.getElementsByTagName("AggLevel");
	var themesFound=false;
	for(var i=0; i<AggLevel.length; i++)
	{	
		if(normalThemesPresent(AggLevel[i]))
		{
			var name  = AggLevel[i].getAttribute("name");
			var title = AggLevel[i].getAttribute("abstract");
			var option = document.createElement('option');
			if(i == 0){option.checked = true;}
			option.value = name;
			var nameText = document.createTextNode(name);
			option.appendChild(nameText);
			option.title = title;
			option.id = 'anal:'+i;
			option.setAttribute('id','anal:'+i);
			//bindEvent(option, 'click', swapLevel, 'false');
			selectBox.appendChild(option);
			var themesFound = true;
		}
		
	}
	if(themesFound)
	{
		document.getElementById('configDrapeLevel').appendChild(selectBox);	
		// load sub levels at element zero
		loadLayerLevel(0, 0, 0);			
		//swapLevel(null, 0);
	}
}
function normalThemesPresent(aggObj)
{
	var ThemeObj = aggObj.getElementsByTagName('Thematic');
	{
		for (var j=0; j<ThemeObj.length; j++)
		{
			var classes = ThemeObj[j].getAttribute('class');
			if(classes == 'false'){return true;	}			
		}
	}	
	return false;
}

function swapLevel(evt)
{	
	var e_out = getThisId(evt);
	var selectedRow = document.getElementById(e_out);
	var level = selectedRow.selectedIndex;
	
	//alert('new selected level = '+level);
	
	// load the theme select object
	loadLayerLevel(level, 0, 0);
	Event.stop(evt);
}

function loadLayerLevel(level, layer, theme)
{
	//alert('loading layer level '+level+" : "+layer+" : "+theme)
	
	// clear out any existing select box
	checkRemoveObject('themeSelectList');
	
	// create a new select control
	var selectBox = document.createElement('select');
	selectBox.id='themeSelectList';
	selectBox.setAttribute('id','themeSelectList');
	selectBox.style.width='100%';
	selectBox.style.height='20px';
	selectBox.title = 'level:'+level+':layer:'+layer;
	//selectBox.title = 'Select the level required';
	bindEvent(selectBox, 'change', swapThemeLevel, 'false');
		
	// now populate the Levels from XML
	LayerLevel =  AggLevel[level].getElementsByTagName("Layer");
	currentPath = LayerLevel[layer].getAttribute('path');
	//alert('new path = '+currentPath)
	defaultHigh = parseInt(AggLevel[level].getAttribute('pophigh'));
	document.getElementById('hiValue').value = defaultHigh;

	// now build up the options for this targetTheme
	var next = 0;
	for (var i=0; i<LayerLevel.length; i++)
	{
		// now get all the Thematic Level for each LayerLevel
		ThemeLevel = LayerLevel[i].getElementsByTagName('Thematic');
		//alert('loading '+ThemeLevel.length+ ' Thematics');
		for (var j=0; j<ThemeLevel.length; j++)
		{
					
				// get all the Themeatic level attributes
				var name  = ThemeLevel[j].getAttribute("name");
				var title = ThemeLevel[j].getAttribute("abstract");
				var avail  = ThemeLevel[j].getAttribute("avail");
				var id = "level:"+level+":layer:"+i+":theme:"+j;

				// build the options for each Thematic tag	
				var option = document.createElement('option');
				if(next == 0){option.checked = true;}
				option.value = name;
				var nameText = document.createTextNode(name);
				option.appendChild(nameText);
				option.id = id;
				option.setAttribute('id',id);
				option.checked = false;
				option.title = title;
				if(avail == 'false' && classes == 'false')
				{option.disabled=true;}	
				selectBox.appendChild(option);
				//bindEvent(selectBox, 'change', swapThemeLevel, 'false');
				next++;
			
		}
	}	
	document.getElementById('configDrapeTheme').appendChild(selectBox);
	
	// load these attributes
	loadAttribsLevel(level, layer, theme);
}

function swapThemeLevel(evt)
{	
	// get user requests
	var thisId = getThisId(evt);
	var selectedRow = document.getElementById(thisId);
	var theme = selectedRow.selectedIndex;
	var title = document.getElementById(thisId).title;
	var parts = title.split(":");
	var level = parts[1];
	var layer = parts[3];
	
	// load the Attributes into select
	loadAttribsLevel(level, layer, theme)
	
	// temporarily set the default total value
	//saveTotalName = defaultTotal;
	//setDefaultTotal(theme);
	Event.stop(evt);
}


function loadAttribsLevel(level, layer, theme)
{	
	//alert('loading Attributes for '+level+" : "+layer+" : "+theme)
	
	LayerLevel =  AggLevel[level].getElementsByTagName("Layer");
	ThemeLevel =  LayerLevel[layer].getElementsByTagName("Thematic");
	currentPath = LayerLevel[layer].getAttribute('path');
	defaultHigh = parseInt(AggLevel[level].getAttribute('pophigh'));
	document.getElementById('hiValue').value = defaultHigh;

	// clear out any existing select box
	checkRemoveObject('themeAttribSelectList');
	
	// create new select control
	var selectBox = document.createElement('select');
	selectBox.id='themeAttribSelectList';
	selectBox.setAttribute('id','themeAttribSelectList');
	selectBox.style.width='100%';
	selectBox.style.height='20px';
	bindEvent(selectBox, 'change', resetRange, 'false');


	// get all the attributes for this theme level
	var avail  = ThemeLevel[theme].getAttribute("avail");
	var total  = ThemeLevel[theme].getAttribute("total");
	var percent  = ThemeLevel[theme].getAttribute("percent");
	var density  = ThemeLevel[theme].getAttribute("density");
	defaultTotal  = ThemeLevel[theme].getAttribute("defaultTotal");
	var allAttributes  = ThemeLevel[theme].getAttribute("allAttributes");
	
	// now build up the attribute options for this targetTheme
	if(allAttributes == 'false')
	{
		// get the Attribtes Tags into Options
		AttribsLevel = ThemeLevel[theme].getElementsByTagName("Attribute");
	
	//alert('number of atts = '+AttribsLevel.length)
		for (var i=0; i<AttribsLevel.length; i++)
		{
			// get the attribute Name
			var attName = AttribsLevel[i].firstChild.nodeValue;

			// create a unique id
			var thisId = 'level:'+level+':layer:'+layer+':theme:'+theme+':attrib:'+attName;

			// build the option tag
			var option = document.createElement('option');
			option.value = attName;
			var nameText = document.createTextNode(attName);
			option.appendChild(nameText);
			option.title = attName;
			option.id = thisId;
			option.setAttribute('id',thisId);
			option.checked=false;
			
			// bind the onclick event to this option
			//bindEvent(option, 'click', resetRange, 'false');
			//bindEvent(option, 'mouseover', getDescription, 'false');
			//bindEvent(option, 'mouseout', hideDescription, 'false');

			selectBox.appendChild(option);
		}
	}
	else // automatically get all the attributes from databse
	{
		var layerName = LayerLevel[layer].getAttribute("name");
		var ajaxRequest = getAttributeSchema(meshBlocksBase, layerName);
		if (ajaxRequest.status == 200)
		{
			// 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)){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");		

			// loop through all Element tags
			var bboxFound=false;
			//alert('number of elements = '+elements.length)
			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 attName = elements[j].getAttribute('name');
					var attNameParts = attName.split('.');
					
					// check for when BBOX is found
					if(bboxFound)
					{
						// get Attribute Name
						var attName = attNameParts[1];
						
						// create a unique id
						var thisId = 'level:'+level+':layer:'+layer+':theme:'+theme+':attrib:'+attName;
						
						// create the option tag	
						var option = document.createElement('option');
						option.value = attName;
						var nameText = document.createTextNode(attName);
						option.appendChild(nameText);
						option.title = attName;
						//alert('attValue = '+attValue)
						option.id = thisId;
						option.setAttribute('id',thisId);
						//option.id = attValue+':'+theme+':'+i;
						//option.setAttribute('id',attValue+':'+theme+':'+i);
						option.checked=false;
			
						// bind the onclick event to this option
						//bindEvent(option, 'click', resetRange, 'false');
						//bindEvent(option, 'mouseover', getDescription, 'false');
						//bindEvent(option, 'mouseout', hideDescription, 'false');
						selectBox.appendChild(option);
					}
					else
					{
						if(attNameParts[1] == 'BBOX') {bboxFound = true;}
					}
				}
			}
		}
		
	}
	document.getElementById('drapeAtts').appendChild(selectBox);

	// now get and set the functions permissible for this theme
	if(total == 'true')
	{	document.getElementById('totalIt').disabled = false;}
	else
	{	document.getElementById('totalIt').disabled= true;
		document.getElementById('totalIt').checked=true;}
	if(percent == 'true')
	{	document.getElementById('percentIt').disabled = false;}
	else
	{	document.getElementById('percentIt').disabled = true;
		document.getElementById('totalIt').checked=true;}
	if(density == 'true')
	{	document.getElementById('densityIt').disabled = false;}
	else
	{	document.getElementById('densityIt').disabled = true;
		document.getElementById('totalIt').checked=true;}
}

function resetRange(evt)
{
	// get the level ids of this attribute
	var thisId = getThisId(evt);
	var selectedRow = document.getElementById(thisId);
	var theme = selectedRow.selectedIndex;	
	var optId = selectedRow.options[theme].id;	
	var parts = optId.split(":");
	var level = parts[1];
	var layer = parts[3];
	var theme = parts[5];

	// traverse the xml to get the attribute name
	LayerLevel =  AggLevel[level].getElementsByTagName("Layer");
	ThemeLevel =  LayerLevel[layer].getElementsByTagName("Thematic");
	defaultHigh = parseInt(AggLevel[level].getAttribute('pophigh'));
	defaultTotal = ThemeLevel[theme].getAttribute('defaultTotal');
	currentPath = LayerLevel[layer].getAttribute('path');
	//alert('default total = '+defaultTotal)
	//alert('current Path = '+currentPath)
	//alert('default High = '+defaultHigh)
	
	// temporarily set the default total value
	numaMin = 0; numaMax = defaultHigh;
	saveTotalName = defaultTotal;
	
	// find out what type of analysis is selected
	var type = getSelectedRadioValue('themeType');
	populateRanges(type);
	
	Event.stop(evt);
}


//----------------------------------------------------------------------------------------------//
function loadFilterOptions()
{
	// if this xml file has not been opened do it here
	if(filterData == null)
	{	filterData = loadXml(applicationBase + filterDataXmlFile, '');}
	//alert(filterData.responseXML.getElementsByTagName("Analysis").length); // should only be one of these!

	// build the Analysis options Input element
	checkRemoveObject('filterDrapeLevelList');
	var selectBox1 = document.createElement('select');
	selectBox1.id='filterDrapeLevelList';
	selectBox1.setAttribute('id','filterDrapeLevelList');
	selectBox1.style.width='100%';
	selectBox1.style.height='20px';	
	selectBox1.size="1";
	bindEvent(selectBox1, 'change', swapClassLevel, 'false');

	// now populate the Levels from XML of only the classified attribute data
	AggFilter =  filterData.responseXML.getElementsByTagName("AggLevel");
	for(var i=0; i<AggFilter.length; i++)
	{
		if(classThemesPresent(AggFilter[i]))
		{
			var AggName  = AggFilter[i].getAttribute("name");
			var AggAbstract = AggFilter[i].getAttribute("abstract");

			// determine if this level is required by looking for Taxonomy tags
			var onts = AggFilter[i].getElementsByTagName("Ontology");
			var onts = AggFilter[i].getElementsByTagName("Taxonomy");
			if(onts.length > 0)
			{
				// create the select Statistical Level element
				var option = document.createElement('option');
				if(i == 0){option.checked = true;}
				option.value = AggName;
				var nameText = document.createTextNode(AggName);
				option.appendChild(nameText);
				option.title = AggAbstract;
				option.id = 'filt:'+i;
				option.setAttribute('id','filt:'+i);
				//bindEvent(option, 'click', swapClassLevel, 'false');
				selectBox1.appendChild(option);
			}	
			document.getElementById('filterDrapeLevel').appendChild(selectBox1);			
		}			
	}
	standardRendering = [];		
	loadLayerClassLevel(0, 0, 0);
		
}		

function classThemesPresent(aggObj)
{
	var ThemeObj = aggObj.getElementsByTagName('Thematic');
	{
		for (var j=0; j<ThemeObj.length; j++)
		{
			var classes = ThemeObj[j].getAttribute('class');
			if(classes == 'true'){return true;	}			
		}
	}	
	return false;
}

function swapClassLevel(evt)
{		
	// find out what class level was selected
	var e_out = getThisId(evt);
	var selectedRow = document.getElementById(e_out);
	level = selectedRow.selectedIndex;	
	//alert('level = '+level);
	
	// load the theme select object
	//currentStandardFile = [];
	loadLayerClassLevel(level, 0, 0);
	Event.stop(evt);
}


function loadLayerClassLevel(level, layer, theme)
{	
	// clear out any existing select box
	checkRemoveObject('themeClassSelectList');
	
	// create a new select control
	var selectBox = document.createElement('select');
	selectBox.id='themeClassSelectList';
	selectBox.setAttribute('id','themeClassSelectList');
	selectBox.style.width='100%';
	selectBox.style.height='20px'
	bindEvent(selectBox, 'change', swapClassThemeLevel, 'false');;
		
	// now populate the Levels from XML
	LayerFilter =  AggFilter[level].getElementsByTagName("Layer");
	currentLayerAbstract =  LayerFilter[layer].getAttribute('abstract')
	currentPath = LayerFilter[layer].getAttribute('path');
	layerName = LayerFilter[layer].getAttribute('name');
	uniqueKeyAttribute = LayerFilter[layer].getAttribute('keyAttribute');
	
	// load all attributes and force the unique key
	loadAllAttributes(uniqueKeyAttribute);


	// now build up the options for this targetTheme
	var next = 0;
	for (var i=0; i<LayerFilter.length; i++)
	{
		// now get all the Thematic Level for each LayerLevel
		ThemeFilter = LayerFilter[i].getElementsByTagName('Thematic');
		//alert(layName+ ' has '+ThemeLevel.length+' THEMES');
		for (var j=0; j<ThemeFilter.length; j++)
		{
			// get all the Themeatic level attributes
			var name  = ThemeFilter[j].getAttribute("name");
			var title = ThemeFilter[j].getAttribute("abstract");
			var avail  = ThemeFilter[j].getAttribute("avail");
			var clas  = ThemeFilter[j].getAttribute("class");
			var standardFile = ThemeFilter[j].getAttribute("defaultFile");
			var classSldFile = ThemeFilter[j].getAttribute("classFile");
			//alert('class file = '+classSldFile)
			
			if(clas == 'true')
			{
				var id = "level:"+level+":layer:"+i+":theme:"+j;;

				// build the options for each Thematic tag	
				var option = document.createElement('option');
				if(next == 0){option.checked = true;}
				option.value = name;
				var nameText = document.createTextNode(name);
				option.appendChild(nameText);
				option.id = id;
				option.setAttribute('id',id);
				option.name = 'themeOption';
				option.setAttribute('name','themeOption');
				option.checked = false;
				option.title = title;
		
				if(avail == 'true'){option.disabled=true;}
				//bindEvent(option, 'click', swapClassThemeLevel, 'false');
				
				selectBox.appendChild(option);
				//bindEvent(selectBox, 'change', swapThemeLevel, 'false');
				next++;
			}
		}
	}	
	document.getElementById('filterDrapeTheme').appendChild(selectBox);
	
	// load the attributes
	loadClassificationLevel(level, layer, theme);
}

function swapClassThemeLevel(evt)
{	
	var e_out = getThisId(evt);
	// get the selected theme number and translate into layername
	var selectedRow = document.getElementById(e_out);
	theme = selectedRow.selectedIndex;
	//alert('theme = '+theme);

	var optId = selectedRow.options[theme].id;	
	//alert('item selected id = '+optId)
	

	var parts = optId.split(":");
	level = parts[1];
	layer = parts[3];
	theme = parts[5];
		
	//alert('xxxxxxx level = '+level+' layer = '+layer+' theme = '+theme);
	
	// load the Attributes into select
	//loadLayerClassLevel(level, layer, theme)
	loadClassificationLevel(level, layer, theme)
	
	// temporarily set the default total value
	//saveTotalName = defaultTotal;
	//setDefaultTotal(row);
	Event.stop(evt);
}

function buildRuleRow(fillColr, fillOpac, strokeColr, strokeWidth, classCode, classValue, operator, classTitle, i, holderObj, layerName, currentPath, rowAbs)
{
	//alert('classCode = '+classCode); alert('classValue = '+classValue); alert('classTitle = '+classTitle);
	
	// now get any rendering rules that may be in xml				
	var row = document.createElement('tr');		

	// now the checkbox cell
	var tdCell1 = document.createElement('td');
	tdCell1.style.width='20px';
	tdCell1.style.height='20px';
	tdCell1.style.border='1px solid gray';

	// insert the checkbox
	var tdCheck = document.createElement('input');
	tdCheck.type='checkbox';
	tdCheck.checked=true;
	tdCheck.id='attVal:'+i; tdCheck.setAttribute('id','attVal:'+i);
	tdCell1.appendChild(tdCheck);
	row.appendChild(tdCell1);

	// insert the symbology cell
	var tdCell2 = document.createElement('td');
	tdCell2.style.width='20px';
	tdCell2.style.height='20px';
	tdCell2.style.border='1px solid gray';
	tdCell2.id='tdCell:'+i; tdCell2.setAttribute('id','tdCell:'+i);

	// insert the Div cell
	renderRules = document.createElement('div');
	renderRules.id='color:'+i; renderRules.setAttribute('id','color:'+i);
	renderRules.style.width='90%';
	renderRules.style.height='90%';
		
	// set the fill colour
	var renders = '';
	if(fillColr == '')
	{	
		var randomColor = random_color('hex');
		while(!checkHex(randomColor))
		{	randomColor = random_color('hex');}
		document.getElementById('defaultButton').disabled = true;
		document.getElementById('defaultButton').style.color='gray';
		standardColorScheme = false;
	}
	else 
	{
		randomColor = fillColr;
		document.getElementById('defaultButton').disabled = false;
		document.getElementById('defaultButton').style.color = 'black';
		standardColorScheme = true;
	}
	renderRules.style.backgroundColor = randomColor;
	renders = randomColor;
		
	// set the fill opacity
	if(fillOpac == ''){	var randomOpac = .70;}
	else {randomOpac = fillOpac;}
	renders+= ":"+randomOpac;
	randomOpac = Number(randomOpac) * 100;
	//alert(randomOpac)
	setOpacity(renderRules, randomOpac);

	// set the line color 
	if(strokeColr == ''){	var lineColor = randomColor;}
	else {lineColor = strokeColr;}
	renders += ":"+lineColor;

	// set the line thickness
	if(strokeWidth == ''){	var lineWidth = 1;}
	else {lineWidth = strokeWidth;}

	if(lineWidth > 0 && lineWidth != null)
	{	var lineStyle = lineWidth+"px solid "+lineColor;
		renderRules.style.border = lineStyle;}
	else{renderRules.style.borderStyle = 'none';}
	renders += ":"+lineWidth;
		
	bindEvent(renderRules, 'click', colourPaletteTool, 'false');
	tdCell2.appendChild(renderRules);
	row.appendChild(tdCell2);

	// insert attribute value cell
	var tdCell3 = document.createElement('td');
	tdCell3.style.border='1px solid gray';	
	tdCell3.style.height='20px';
	tdCell3.style.width='155px';
	if (browser =='firefox'){tdCell3.style.width='130px';}
	tdCell3.id = 'code:'+i; tdCell3.setAttribute('id','code:'+i);
	var nameText = document.createTextNode(classTitle);
	tdCell3.appendChild(nameText);
	tdCell3.name = classValue +" : "+classCode+ " : "+layerName+" : "+currentPath+" : "+classTitle+" : "+operator;
	tdCell3.value = renders;
	tdCell3.title = rowAbs;
	standardRendering[i] = renders;
	row.appendChild(tdCell3);
	holderObj.appendChild(row);	
}
function swapClassLevels(classIndicator)
{
	//alert(classIndicator)
	currentStandardFile = null;
	if(classIndicator == 'classes')
	{
		if(ThemeFilter[theme].getAttribute('classFile') )
		{	currentStandardFile = ThemeFilter[theme].getAttribute('classFile');}
	}
	else
	{
		if(ThemeFilter[theme].getAttribute('defaultFile'))
		{	currentStandardFile = ThemeFilter[theme].getAttribute('defaultFile');}
	}
	//alert('new standard file = '+currentStandardFile)
	if(currentStandardFile)	{	buildAttribsTable(currentStandardFile);	}
}


function loadClassificationLevel(level, layer, theme)
{	
	//alert('level = '+level+' layer = '+layer+' theme = '+theme)
	LayerFilter =  AggFilter[level].getElementsByTagName("Layer");
	layerName = LayerFilter[layer].getAttribute('name');
	//alert('layer = '+layer)
	currentFilterLayer = layer;
	ThemeFilter =  LayerFilter[layer].getElementsByTagName("Thematic");
	currentPath = LayerFilter[layer].getAttribute('path');
	ThemeTitle = ThemeFilter[0].getAttribute("name");
	currentStandardFile='';
	if(ThemeFilter[theme].getAttribute('defaultFile'))
	{	currentStandardFile = ThemeFilter[theme].getAttribute('defaultFile');
		document.getElementById('attribsIt').checked = true;
		document.getElementById('classIt').disabled=true;
		//document.getElementById('attribsIt').value = currentStandardFile;
	}
	if(ThemeFilter[theme].getAttribute('classFile') )
	{	currentStandardFile = ThemeFilter[theme].getAttribute('classFile');
		document.getElementById('attribsIt').checked = false;
		document.getElementById('classIt').checked = true;
		document.getElementById('classIt').disabled=false;
		//document.getElementById('classIt').value = currentStandardFile;
	}
	// build the Attributes/Class checkbox table
	buildAttribsTable(currentStandardFile);
}
	
function buildAttribsTable(currentStandardFile)
{
	// clear out any existing select box
	checkRemoveObject('themeClassificationSelectList');
	document.getElementById('allAttsToggleControl').checked=true;

	// insert a table for even alighnment
	// build the Table within the Form
	var layerTable = document.createElement('table');
	layerTable.id='themeClassificationSelectList';
	layerTable.setAttribute('id','themeClassificationSelectList');
	layerTable.style.color='#000000'; 
	layerTable.style.position='relative';	
	layerTable.border=0;
	layerTable.style.paddingTop='0px'; 
	layerTable.style.paddingBottom='2px'; 
	layerTable.style.width='92%';
	if(browser == 'firefox'){layerTable.style.width='100%';}
	layerTable.style.maxHeight='120px'; 
	layerTable.style.borderCollapse='collapse'; 
	layerTable.style.fontWeight='bold'; 
	layerTable.style.fontSize='9px'; 
	layerTable.style.backgroundColor='#FFFFFF';
	layerTable.style.overflowX='hidden';
	layerTable.style.overflowY='scroll';

	var layerTableBody = document.createElement('tbody');
	//layerTableBody.style.height='150px'; 
	
	// get all the attributes for this theme level
	//var avail  = ThemeFilter[theme].getAttribute("avail");
	
	// if standard rendering requested and an SLD is provided then build the menu from the SLD
	//alert('sld = '+currentStandardFile)
	//alert(standardColorScheme)
	
	if(currentStandardFile != '' && standardColorScheme)
	{
		//alert('sld = '+currentStandardFile)

		// get standard SLD data
		currentSld = 'inc/sld/'+currentPath+'/'+currentStandardFile
		//getSldRuleData(currentSld);
		getSldInfo(currentSld);
		//alert (currentSld+" \nLayer = "+layerName+" \nTitle = "+titleData+" \n name = "+nameData+" \n Abs = "+sldAbstract);
		initRulesArrays();

		// attache Bruid for browsaer caching if required
		var query = '';
		var parts = currentSld.split("?bruid");
		if(parts.length <= 1){ query = "?bruid="+new Date().getTime();}
		
		// get all rule details into arrays
		//alert(applicationBase+'inc/'+currentSld+query)
		Request = loadXml(applicationBase+currentSld, query, false);
		var sldRules = Request.responseXML.getElementsByTagName("Rule");
		numOfRules = sldRules.length;

		// Loop through all the rules in the SLD file and build legend rows for each
		for (var i = 0; i < numOfRules ; i++)
		{	
			var fillColr = null
			var fillOpac = null
			var fillPat = null
			var fillPatForm = null;
			var strokeOpac = null;
			var strokeDash = null;
			var strokeColr = null;
			var strokeWidth = null;
			
			// get the heading data for each Rule
			RuleName[i]=''; RuleTitle[i]='';  RuleAbstract[i]='';
			if(sldRules[i].getElementsByTagName("Name")[0])
			{	RuleName[i]= sldRules[i].getElementsByTagName("Name")[0].firstChild.nodeValue;	}
			var classTitle = RuleName[i];
			if(sldRules[i].getElementsByTagName("Title")[0])
			{	RuleTitle[i]= sldRules[i].getElementsByTagName("Title")[0].firstChild.nodeValue; 
				classTitle = RuleTitle[i];	
			}
			if(sldRules[i].getElementsByTagName("Abstract")[0])
			{	RuleAbstract[i]= sldRules[i].getElementsByTagName("Abstract")[0].firstChild.nodeValue;}
			//alert("rule Name = "+RuleName[i]);
			//alert("rule Title = "+RuleTitle[i]);
			//alert("rule Abstract = "+RuleAbstract[i]);

			// get the scale denominators if present
			if(sldRules[i].getElementsByTagName("MinScaleDenominator")[0])
			{	ruleMinScale[i]= sldRules[i].getElementsByTagName("MinScaleDenominator")[0].firstChild.nodeValue;	}
			if(sldRules[i].getElementsByTagName("MaxScaleDenominator")[0])
			{	ruleMaxScale[i]= sldRules[i].getElementsByTagName("MaxScaleDenominator")[0].firstChild.nodeValue;	}
			//alert("rule MinScale = "+ruleMinScale[i]);
			//alert("rule MaxScale = "+ruleMaxScale[i]);

			// get the rendering information for each rule
			if (sldRules[i].getElementsByTagName("PolygonSymbolizer"))
			{	
				var polygonSymboliser = sldRules[i].getElementsByTagName("PolygonSymbolizer");
				var numPsym = polygonSymboliser.length;
				// precess each polygon symboliser tag
				for (var ii=0 ; ii<numPsym ; ii++ )
				{
					var sldFill = polygonSymboliser[ii].getElementsByTagName("Fill");
					if (sldFill.length > 0) // check to see if we have any Fills first
					{
						// find out how many CssParameter tags there are
						var sldFillCss = sldFill[0].getElementsByTagName("CssParameter");
						
						// if we have a regulat solid fill process here
						if (sldFillCss.length > 0 )
						{
							var fillColr = ""; 
							//var fillOpacity = opacityValue;
							// process each Fill CssParemeter attribute	
							for (var j=0; j<sldFillCss.length ; j++)
							{
								var fillAtt = sldFillCss[j].getAttribute("name");
								if (fillAtt == "fill") 
								{
									fillColr = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
									if (fillColr == ''){fillColr='transparent'}
								}
								if (fillAtt == "fill-opacity")
								{			
									fillOpac = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
								}
							}
						}
						else if(sldFill[0].getElementsByTagName("GraphicFill"))
						{
							// we now have a graphic fill so get the data for inclusion in legend fill
							var graphicFill = sldFill[0].getElementsByTagName("GraphicFill");
							var graphic = graphicFill[0].getElementsByTagName("Graphic");
							var externalGraphic = graphic[0].getElementsByTagName("ExternalGraphic");
							var onlineResource = externalGraphic[0].getElementsByTagName("OnlineResource")
							var fillPat = onlineResource[0].getAttribute("xlink:href"); 
							//alert ("source = "+fillPat);
							var fillPatForm = externalGraphic[0].getElementsByTagName("Format")[0].firstChild.nodeValue;
							//alert ("format = "+fillPatForm)
						}
					}
					//alert("fill = "+fillColr)
					// find out how many Stroke Rule nodes
					if(sldRules[i].getElementsByTagName("Stroke"))
					{
						var sldStroke = sldRules[i].getElementsByTagName("Stroke");
						if (sldStroke.length > 0)
						{
							var sldStrokeCss = sldStroke[0].getElementsByTagName("CssParameter");
							
							//alert ("sldStrokeCss = "+sldStrokeCss.length)
							
							if(sldStrokeCss.length > 0)
							{
								
								// process each Stroke CssParemeter attribute				
								for (var j=0; j<sldStrokeCss.length ; j++)
								{
									var strokeAtt = sldStrokeCss[j].getAttribute("name");
									if (strokeAtt == "stroke") 
									{
										strokeColr = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;		
									}
									if (strokeAtt == "stroke-width")
									{
										strokeWidth = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
									}
									if (strokeAtt == "stroke-opacity")
									{
										strokeOpac = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
									}
									if (strokeAtt == "stroke-dasharray")
									{
										strokeDash = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
									}
								}
							}
						}
					}
				}
			}
		/*	
			alert("fillColr = "+fillColr)
			alert("fillOpac = "+fillOpac)
			alert("fillPat = "+fillPat)
			alert("fillPatForm = "+fillPatForm)
			alert("strokeColr = "+strokeColr)
			alert("strokeWidth = "+strokeWidth)
			alert("strokeOpac = "+strokeOpac)
			alert("strokeDash = "+strokeDash)
*/
			// get the filter expression
			var sldFilter = sldRules[i].getElementsByTagName("Filter");			
			var sqlExpress = sldFilter[0].getElementsByTagName("SqlExpression");	
			//alert ("number of SQLs = "+sqlExpressions.length);
			var sqlExpression = sqlExpress[0].firstChild.nodeValue;
			//alert(sqlExpression)
			//var cleanSqlExp= sqlExpression.replace(/\'/g,'');

			var operator = getOperatorUsed(sqlExpression)
			var classCode = sqlExpression.split(operator)[0];
			var classValue = sqlExpression.split(operator)[1];
			if(operator == " IN ") { classValue = classValue.replace(/,/g,"::");}
			//alert('classCode >> classValue =  '+classCode+"  "+operator+"  "+classValue)
			//attName = classCode;
			
			buildRuleRow(fillColr, fillOpac, strokeColr, strokeWidth, classCode, classValue, operator, classTitle, i, layerTableBody, layerName, currentPath, ruleAbstract[i]);	
			//alert(standardRendering)
		}
		layerTable.appendChild(layerTableBody);
		var holdingDiv = document.getElementById('drapeAtts2');
		holdingDiv.appendChild(layerTable);
		
	}
	// else build up the attribute options for this target Theme from the xml file	
	else
	{	
		//alert('get from XML file')
		//AttribsFilter = ThemeFilter[theme].getElementsByTagName("Ontology");
		AttribsFilter = ThemeFilter[theme].getElementsByTagName("Taxonomy");

		// check for number os classes
		var classes = AttribsFilter[0].getElementsByTagName("Class")
		//alert('numb of classes in '+AttribsFilter[0].getAttribute('name')+ " = "+classes.length);
	
		//alert('number of atts = '+AttribsLevel.length)
		for (var i=0; i<AttribsFilter.length; i++)
		{
			// get the attribute Name
			var attName = AttribsFilter[i].getAttribute('name');

			// now get the Taxonomy options
			ClassFilter = AttribsFilter[i].getElementsByTagName("Value");
			//alert('Number in taxonomy Value tags for '+attName+' = '+ClassLevel.length);
			//selectBox2.size=ClassLevel.length;
			numOfRules = ClassFilter.length

			for (var j=0; j<numOfRules ;j++ )
			{
				// pick off the classification code to be used 
				var classValue = ClassFilter[j].firstChild.nodeValue;
				var classCode = ClassFilter[j].getAttribute('value');
				attName = classCode;
				
				// set the fill colour
				var renders = '';
				if(ClassFilter[j].getAttribute('fill-color') == '')
				{	
					var randomColor = random_color('hex');
					while(!checkHex(randomColor))
					{	randomColor = random_color('hex');}
				}
				else 
				{
					randomColor = ClassFilter[j].getAttribute('fill-color');
				}
				fillColr = randomColor;
				
				// set the fill opacity
				if(ClassFilter[j].getAttribute('fill-opacity') == ''){	var randomOpac = .70;}
				else {randomOpac = ClassFilter[j].getAttribute('fill-opacity');}
				//renders+= ":"+randomOpac;
				fillOpac = Number(randomOpac);

				// set the line color 
				if(ClassFilter[j].getAttribute('stroke-color') == ''){	var lineColor = fillColr;}
				else {lineColor = ClassFilter[j].getAttribute('stroke-color');}
				//renders += ":"+lineColor;
				strokeColr = lineColor;

				// set the line thickness
				if(ClassFilter[j].getAttribute('stroke-width') == ''){	var lineWidth = 1;}
				else {lineWidth = ClassFilter[j].getAttribute('stroke-width');}
				//renderRules.style.border = lineWidth+"px solid "+lineColor;
				//renders += ":"+lineWidth;
				strokeWidth = lineWidth;
				standardColorScheme = false;
				//alert('classCode = '+classCode); alert('classValue = '+classValue); alert('classTitle = '+classTitle)
				operator = ' = ';// WRONG
				buildRuleRow(fillColr, fillOpac, strokeColr, strokeWidth, classCode, classValue, operator, classTitle, j, layerTableBody, layerName, currentPath);
			}
		}
		layerTable.appendChild(layerTableBody);
		var holdingDiv = document.getElementById('drapeAtts2');
		holdingDiv.appendChild(layerTable);	
	}
	//document.getElementById('drapeAtts2').appendChild(selectBox2);
	currentFilterLevel = level; currentFilterLayer = layer; currentFilterTheme = theme;
}

function getOperatorUsed(sqlStatement)
{
	// look for equals
	var parts = sqlStatement.split(' = ');
	if(parts.length > 1) {return  ' = ';}
	// look for <
	var parts = sqlStatement.split(' < ');
	if(parts.length > 1) {return  ' < ';}
	// look for >
	var parts = sqlStatement.split(' > ');
	if(parts.length > 1) {return  ' > ';}
	// look for <=
	var parts = sqlStatement.split(' <= ');
	if(parts.length > 1) {return  ' <= ';}
	// look for >=
	var parts = sqlStatement.split(' >= ');
	if(parts.length > 1) {return  ' >= ';}
	// look for <>
	var parts = sqlStatement.split(' <> ');
	if(parts.length > 1) {return  ' <> ';}
	// look for LIKE
	var parts = sqlStatement.split(' LIKE ');
	if(parts.length > 1) {return  ' LIKE ';}
	// look for IN
	var parts = sqlStatement.split(' IN ');
	if(parts.length > 1) {return  ' IN ';}
	// look for BETWEEN
	var parts = sqlStatement.split(' BETWEEN ');
	if(parts.length > 1) {return  ' BETWEEN ';}
	// look for EXISTS
	var parts = sqlStatement.split(' EXISTS ');
	if(parts.length > 1) {return  ' EXISTS ';}
	// look for IS NULL
	var parts = sqlStatement.split(' IS NULL ');
	if(parts.length > 1) {return  ' IS NULL ';}
	// look for IS NOT NULL
	var parts = sqlStatement.split(' IS NOT NULL ');
	if(parts.length > 1) {return  ' IS NOT NULL ';}
	// look for AND
	var parts = sqlStatement.split(' AND ');
	if(parts.length > 1) {return  ' AND ';}
	// look for OR
	var parts = sqlStatement.split(' OR ');
	if(parts.length > 1) {return  ' OR ';}
	// look for NOT
	var parts = sqlStatement.split(' NOT ');
	if(parts.length > 1) {return  ' NOT ';}
}

function colourPaletteTool(evt)
{
	targetDiv = getThisId(evt);
	var row = targetDiv.split(":")[1];
	var parentDiv = document.getElementById('sidebar:2');

	//var parentTargetDiv = parent.document.getElementById(targetDiv);
	//parentTargetDiv.style.border = '3px solid red';
	document.getElementById('code:'+row).className = 'selectedItem';
	
	buildGeneralColorPalette(parentDiv, targetDiv);
	standardColorScheme = false;

	Event.stop(evt);
}

function toggleAllTicks(status)
{
	//alert(status)
	//alert('number of rules = '+numOfRules)
	for (var i=0; i<numOfRules; i++)
	{	document.getElementById('attVal:'+i).checked=status;	}
}

function setCheckBoxes(keywordValue)
{
	var values = keywordValue.split(',');
	var searchArray = []; 
	list = [];
	for (var i=0; i<numOfRules; i++)
	{	
		var string = document.getElementById('code:'+i).name;
		searchArray[i] = string.split(" : ")[4];
	}
	//alert(searchArray);
	//alert(values);
	
	// scan through all checkboxes and if keyword is present in name check box
	list = doSearch(searchArray, values, false);
	if(list.length <= 0) 
	{	alert('There are no classifications that match the entered keywords');	}
	else
	{
		// set appropriate checkboxews
		toggleAllTicks(false);
		for (var i=0; i<list.length; i++)
		{		document.getElementById('attVal:'+list[i]).checked=true;}	
	}
}

// function to make a new DDrape from the Filter panel
function makeNewFilteredDDrape()
{
	//alert('standard = '+standardColorScheme)
	
	// remove any existing DDrape file
	//alert('ddrape sld = '+getFile)
	if(getFile)	
	{	
		var parts = getFile.split('newSld_');
		if(parts.length >1)
		{
			//alert ('deleting file = '+getFile); 
			deleteit(getFile);

			// also purge the cache for this temp SLD
			var tempCache = getFile.replace(/sld\//, '');	// trim off leading sld/
			tempCache = tempCache.replace(/.xml/, '');		// trim off trailing .xml
			//alert('cache being purged = '+tempCache)
			purgeDrapeCache(tempCache, '');

		}
	}
	
	// get all the data from the filter panel
	classValueArraySel = [];
	classCodeArraySel = [];
	classOperArraySel = [];
	classTitleArraySel = [];
	colorBdyArraySel = [];
	colorFillArraySel = [];
	fillOpacArraySel = [];
	lineWeightArraySel = [];
	//alert('class Filter Array = '+ClassFilter.length)
	
	var k=0;
	for (var i=0; i<numOfRules; i++)
	{	if(document.getElementById('attVal:'+i).checked)
		{
			var title = document.getElementById('code:'+i).name;
			//alert('title = '+title)
			classValueArraySel[k] = title.split(" : ")[0];
			classCodeArraySel[k] = title.split(" : ")[1];
			classOperArraySel[k] = title.split(" : ")[5];

//alert(classCodeArraySel[k]+"  and  "+classValueArraySel[k])


			//var attName = title.split(" : ")[2];
			var layerName = title.split(" : ")[2];
			var path = title.split(" : ")[3]+"/";
			classTitleArraySel[k] = title.split(" : ")[4];

			// now get the rendering rules
			var ruleString = document.getElementById('code:'+i).value; 
			//alert('ruleString = '+ruleString)
			var renderArray = ruleString.split(":");

			// save the rendering params
			var newColorCode = document.getElementById('color:'+i).style.backgroundColor;
			//alert('new Color = '+newColorCode)
			if(browser == 'firefox' && newColorCode != 'transparent'){	newColorCode = "#"+convertRBGtoHEX(newColorCode);}
			//alert('new hex Code = #'+newColorCode)
			
			var thisOpacity = renderArray[1];
			var thisLineColor = newColorCode;
			if(newColorCode == 'transparent')
			{	
				newColorCode = "#FFFFFF"; 
				thisOpacity = 0.01;
				thisLineColor = "";
			}
			
			colorFillArraySel[k] = newColorCode;
			colorBdyArraySel[k]  = thisLineColor;	
			fillOpacArraySel[k]  = thisOpacity;			
			lineWeightArraySel[k]= renderArray[3];
			k++;
		}	
	}

	// if we have any attribute rules make the SLD
	//alert('k = '+k)
	//alert('num of rules = '+numOfRules)
	
	if(k-1 >= 0)
	{				
		// check for standard rendering and no user changes //currentSld = 'sld/'+currentPath+'/'+currentStandardFile
		if(standardColorSelected() && k == numOfRules)
		{	
			file = currentStandardFile; 	
			currentPath = path;
			newFileName = applicationRoot + njsSldDir + path+ file;		
			getFile = "sld/"+ path+ file;
			//alert('get standard file = '+getFile)
		}
		else 
		{   
			//alert(layerName)
			var filePart = layerName.split(":")[0];
			file = 'newSld_'+filePart+ "_"+new Date().getTime()+'.xml'; 
			//alert(file)
			currentPath = path;
			//newFileName = path+ file;
			newFileName = applicationRoot + njsSldDir + path+ file;	
			//alert(newFileName)
			getFile = "sld/"+ path+ file;	
			//alert(getFile)
			genLoadStatus('Building new SLD Filter ...', true);
			makeNewSldForFilter(getFile, layerName, classCodeArraySel, classValueArraySel, classOperArraySel, classTitleArraySel, colorBdyArraySel, colorFillArraySel, fillOpacArraySel, lineWeightArraySel, '', '');
		}
		if(document.getElementById('labelsToggleControl'))
		{var labels = document.getElementById('labelsToggleControl').checked;}
		
		//load the newly edited SLD string into editor
		genLoadStatus('Applying SLD Filter ...', true);
		//var accessible = false;
		//if(standardColorScheme){accessible=true;}
		//alert('going into swapSld getFile = '+getFile);
		newSldOpen = true;
		//alert('getFile = '+getFile)
		swapSld('inc/'+getFile, '', "apply", '', nuCache, true );
	
		//alert('eliminate status')
		genLoadStatus('', false);
	}
	else
	{	alert('No attribute values were checked?');}
}

function standardColorSelected()
{
    // scan through the seleced items checking render rules against standard rules
	for (var i=0; i<colorFillArraySel.length; i++)
	{	
		standardRendering[i] = standardRendering[i].toUpperCase();
		var renderParts = standardRendering[i].split(":");
		//alert(renderParts+'\n'+ colorFillArraySel[i] +":"+ fillOpacArraySel[i]   +":"+colorBdyArraySel[i]   +":"+lineWeightArraySel[i])
		if (renderParts[0] != colorFillArraySel[i].toUpperCase() ||
			renderParts[1] != fillOpacArraySel[i].toUpperCase())   
			//renderParts[2] != colorBdyArraySel[i].toUpperCase()   
			//renderParts[3] != lineWeightArraySel[i].toUpperCase()
		{  return false;}
	}
    return true;
}

function applyDefaultColours()
{
	//alert(currentFilterLevel+" >> "+level);
	//alert(currentFilterlayer+" >> "+layer);
	//alert(currentFilterTheme+" >> "+theme);
	standardColorScheme = true;
	loadClassificationLevel(currentFilterLevel, 0, currentFilterTheme)

}



function getDescription(evt)
{
	var parts = getThisId(evt).split(":");
	var level = parts[1];
	var layer = parts[3];
	//var theme = parts[5];
	var attrib = parts[7];
	
	LayerLevel =  AggLevel[level].getElementsByTagName("Layer");
	layerName = LayerLevel[layer].getAttribute('name');

	//alert(layerName+"  >>  "+attrib)
	var Description = this.title;

	// lookup the attribute name for its long description if available ????????
	if(layerName == 'POA_MARITAL_STATUS:ABS')
	{
		Attribute = getNumaAttributes(layerName, attrib);
		if(Attribute)
		{
			// get xml attribute name as a check only
			Description = Attribute[0].getElementsByTagName("Description")[0].firstChild.nodeValue;
		}
	}
	genLoadStatus(Description,false);
	Event.stop(evt);
}
function hideDescription(evt)
{
	genLoadStatus('',false);
	Event.stop(evt);
}
/*
function setDefaultTotal(row)
{
	// temporaarily hardcode the Total Name defaults
	saveTotalName = '';
	parentFlag = false;
	if(templatePath[row] == 'cw'){saveTotalName = 'abs_Total_Total';}
	if(templatePath[row] == 'icd'){saveTotalName = 'ABS_TOTAL_P_P';}
	if(templatePath[row] == 'poa_pop'){saveTotalName = 'TOTAL_P_P';}
	if(templatePath[row] == 'poa_mar'){saveTotalName = 'PERSONS_TOTAL_TOTAL';}
	if(templatePath[row] == 'arthvic'){saveTotalName = 'TOTAL_2010_P';}
	//alert('saveTotalName =' + saveTotalName);
}
*/	

function populateRanges(type)
{
	if(type == "totals" ) 
	{	var low = numaMin;  var high = numaMax; 
		document.getElementById('percentagesRow').style.display='none';
		document.getElementById('sidebar:2').style.height='420px';
		document.getElementById('content:2').style.height='420px';
		document.getElementById('ddrapeControls').style.top='365px';
	}
	else if(type == "percentages" ) 
	{
		var low = 0;  var high = 100;
		if(parentFlag)
		{
			document.getElementById('percentagesRow').style.display='block'; 
			document.getElementById('sidebar:2').style.height='440px';
			document.getElementById('content:2').style.height='420px';
			document.getElementById('ddrapeControls').style.top='370px';
		}
	}
	else 
	{
		var low = numaMin;  var high = numaMax; 
		document.getElementById('percentagesRow').style.display='none';
		document.getElementById('sidebar:2').style.height='420px';
		document.getElementById('content:2').style.height='420px';
		document.getElementById('ddrapeControls').style.top='365px';
	}
	document.getElementById('loValue').value = low;
	document.getElementById('hiValue').value = high;
}

function showPercentTotals(totalsParentArray)
{
	// set up the select box
	checkRemoveObject('listOfTotals');
	var selectBox = document.createElement('select'); 
	selectBox.id='listOfTotals';
	selectBox.setAttribute('id','listOfTotals');
	selectBox.style.width='200px';
	selectBox.style.height='20px';
	
	document.getElementById('percentTotals').appendChild(selectBox);

	//now build the options from the webservice
	for(var i=0; i<totalsParentArray.length ; i++)
	{
		var totAttribute = totalsParentArray[i].getElementsByTagName('Attribute');
		var totName = totAttribute[0].getAttribute('name');								// this is what we are after to use in % formula
		var totDesc = totAttribute[0].getElementsByTagName('Description')[0].firstChild.nodeValue;
		//var totMin = totAttribute[0].getElementsByTagName('Min').firstChild.nodeValue;
		//var totMax = totAttribute[0].getElementsByTagName('Max').firstChild.nodeValue;
		//var totAve = totAttribute[0].getElementsByTagName('Average').firstChild.nodeValue;

		// now create the Option row
		var option = document.createElement('option');
		option.checked=false;
		if(i == 0){option.checked = true;}
		option.value = totName;
		var text = document.createTextNode(totName);
		option.appendChild(text);
		option.id = 'percentTotal:'+i;
		option.setAttribute('id','percentTotal:'+i);
		selectBox.appendChild(option);
		parentFlag = true;
	}

	// write out the opton row to the holding div
	document.getElementById('percentTotals').appendChild(selectBox);

}
function resetRanges(evt)
{
	// get the selected theme number and translate into layername
	var selectedDrape = document.getElementById('themeSelectList');
	var themeNumber = selectedDrape.selectedIndex;
	//alert('themeNumber = '+themeNumber)

	// now get the selected attribute from this select box array[i]+':'+row+':'+i;
	var thisId = getThisId(evt);
	var attribNumber = thisId.split(":")[2];
	numaAttribute = listOfThemes[themeNumber][attribNumber];
	//alert('numaAttribute = '+numaAttribute)
	
	// temporarily set the default total value
		numaMin = 0; numaMax = 1000;
		saveTotalName = defaultTotalAttribute[themeNumber]
		//setDefaultTotal(themeNumber);
	
/*	// ***************just get the values for one layer for now ***************
	if(numaLayers[themeNumber] == 'POA_MARITAL_STATUS:ABS')
	{	
		Attribute = getNumaAttributes(numaLayers[themeNumber],numaAttribute);
		if(Attribute)
		{
			// get xml attribute name as a check only
			//var Description = Attribute[0].getElementsByTagName("Description")[0].firstChild.nodeValue;
			//alert('attribute Description = '+Description)
			var xmlAttribute = Attribute[0].getAttribute('name').toUpperCase();

			// now go and get the high and low values for this attribute
			if(xmlAttribute == numaAttribute)
			{
				numaMax = Attribute[0].getElementsByTagName('Max')[0].firstChild.nodeValue;
				numaMin = Attribute[0].getElementsByTagName('Min')[0].firstChild.nodeValue;
			}
				
			// how many TotalsParents tags are there
			var totalsParent = Attribute[0].getElementsByTagName('TotalsParent');
			if(totalsParent.length > 0)
			{	showPercentTotals(totalsParent);	}
		}	
	}
*/	
	// find out what type of analysis is selected
	var type	= getSelectedRadioValue('themeType');
	populateRanges(type);
	
	Event.stop(evt);
}

function getNumaAttributes(nameOfLayer, nameOfAttribute)
{
	// build up the numagetattributestats web service request
	params =  '&request=numagetattributestats';
	params += '&layer='+nameOfLayer;
	params +='&attribute='+nameOfAttribute;
	numaUrl = meshBlocksBase;
	ajaxRequest = '';
	
	// get the numa stats xml file into DOM
	//alert(numaUrl+params);
	//makePopup(numaUrl+params, '500', '500', 'both'); 
	ajaxRequest = proxyRequest(params, '', 'POST')	
	if(ajaxRequest.status != 200 || ajaxRequest.responseXML == null) { return null;}

	//--------------- Parsing xml in DOM --------------//
	// Pick off high and low valued for this attribute 
	var numapsObj = ajaxRequest.responseXML.getElementsByTagName("NuMaps"); // there should only be one of these!
	//alert('number of NuMaps Tags = '+numapsObj.length)
	var Layer = numapsObj[0].getElementsByTagName("Layer");
	var xmlLayer = Layer[0].getAttribute('name').toUpperCase();
	var Attribute = Layer[0].getElementsByTagName("Attribute");

	// return the attribute object
	return Attribute;

}

//http://ben.www.numaps.com.au/nuserv.cfm?request=numagetattributestats&layer=POA_MARITAL_STATUS:ABS&attribute=Male_15_19_Married

function makeNewDDrape()
{
	// get the selected drape
	var selectedDrape = document.getElementById('themeSelectList');
	var themeNumber = selectedDrape.selectedIndex;
	//alert(titleOfThemes[themeNumber])
	//alert(templatePath[themeNumber]);

	// get the hi & lo values from form here
	var lowValue = parseInt(document.getElementById('loValue').value);
	var highValue = parseInt(document.getElementById('hiValue').value);
	if(lowValue > highValue) 
	{
		alert('low value is higher than high value - please set correctly');
		//alert(lowValue+" >> "+highValue)
		document.getElementById('loValue').value = '';
		document.getElementById('hiValue').value = '';
		document.getElementById('loValue').focus();
		return;
	}

	// get user preferred calssification
	var classificationType = document.getElementById('classOpt');
	var classSelected = classificationType.options[classificationType.selectedIndex].value;
	var noc = classSelected.split('-')[0];

	// get the selected attribute
	var selectedAttribute = document.getElementById('themeAttribSelectList');
	//var attribNumber = selectedAttribute.selectedIndex;
	//var attName = listOfThemes[themeNumber][attribNumber];
	var attName = selectedAttribute.options[selectedAttribute.selectedIndex].value;
	//alert('attName = '+attName)

	// get the total to be used for percentages
	totalName = defaultTotal;
/*	if(numaLayers[themeNumber] == 'POA_MARITAL_STATUS:ABS')
	{
		var selectedTotals = document.getElementById('listOfTotals');
		var totalName = selectedTotals.options[selectedTotals.selectedIndex].value;
		totalName = totalName.toUpperCase();
	}
*/	
	//alert('totalName  = '+totalName)
	
	// get the selected thematic map options
	var type	= getSelectedRadioValue('themeType');
	var color	= getSelectedRadioValue('themeColors');
	var border	= getSelectedRadioValue('themeBorder');	

	// set up Drape colour fill selection
	colorFill='none'; fillOpac = 0.75;
	if(color == 'red')	{colorFill = colorRange[0];}
	if(color == 'blue')	{colorFill = colorRange[1];}
	if(color == 'green'){colorFill = colorRange[2];}

	// set up Drape border selection
	lineWeight = '0';
	if(border == 'addBorders') {colorBdy = '000000'; lineWeight = '1';}
	
	// build the correct template filename
	var file = ''; 
	var file = currentPath+'/template_'+currentPath+'_'+type+'_'+noc+'.xml';		
	newFile = currentPath+'/'+type+'_'+noc+'_'+new Date().getTime()+'.xml';
	newFile = 'sld/'+newFile;
	applicationBase + njsSldDir;

	// clear out any cache for this sld
	var sldCacheGroup = newFile.split('sld/');		// trim off leading sld/
	var drapeCache = sldCacheGroup[1].split('.')[0] ;	// trim off trailing .xml
	clearCache(drapeCache, null)
	
	// get the layer info from template file
	getFile = applicationRoot + njsSldDir + file;
	if(!getSldInfo(getFile)){alert('problem with template file in makeNewDDrape'); return;}
	layName=layerName;
	layStyle='';
	//alert('totalName = '+totalName)

	// Set up the file header information and create file 
	configQuery = "?file="+getFile;
	configQuery+= "&new=";//+newFile;
	configQuery+= "&att="+attName;
	configQuery+= "&total="+totalName;
	configQuery+= "&lo="+lowValue;
	configQuery+= "&hi="+highValue;
	configQuery+= "&class="+classSelected;
	configQuery+= "&bcol="+colorBdy;
	configQuery+= "&fcol="+colorFill;
	configQuery+= "&opac="+fillOpac;
	configQuery+= "&line="+lineWeight;

	// send this request off to the server to create a modified SLD
	configRequest = applicationRoot + "inc/makeNewSldFile_clone2.php";
	//alert(configRequest+configQuery)
	//var aquery = query.split('?')[1];
	//makeNewSldForConfigure(layerName, type, attName, totalName, loValue,hiValue, classSelected, colorBdy, colorFill, fillOpac, lineWeight)

	
	// clear out the layer and any cache
	if(DemoDrape != null) 
	{
		DemoDrape.destroy(); 
		DemoDrape = null;
		getAndPurgeDrapeCache()
	}

	// set the new opacity for the new DDrape
	newOpacity = (parseFloat(lastKnownPosition)).toFixed(1);
	newOpacity = Math.min(maxOpacity, Math.max(minOpacity, newOpacity));

	// now add the sld rendered layer to the map
	DemoDrape = new OpenLayers.Layer.WMS(layName, numapsService, {SLD: configRequest+configQuery, format: drapeImage, version:'1.1.3',   quality: 'BEST', reaspect: false, transparent:'true'});		
	DemoDrape.addOptions({isBaseLayer: false, visibility: true, wrapDateLine: true, buffer: buff, reproject: true, opacity: newOpacity, tileSize: new OpenLayers.Size(tileSize,tileSize) });
	map.addLayer(DemoDrape);
	DemoDrape.setZIndex(map.Z_INDEX_BASE['Popup'] -9000);
	if(maskLayer){bringToTop(maskLayer);}
	
	// build the DDrape legend
	fadeLayer = DemoDrape;
	getSldInfo(configRequest+configQuery);
	legendSld = configRequest+configQuery;
	drapeFile = configRequest+configQuery;
	layFile = configRequest+configQuery;
	currentSldFile = configRequest+configQuery;
	currentSld=currentSldFile;

	// create legend from sld file if available
	legendBuilder("mapSurround", legendSld, null, dvbdy1, dvhdr1, false, 'config');
	document.getElementById('legendDD').title = 'show legend';
	showHideLegend('legendDD');
	manageLegendControls();
	dblClickGetFeatureInfo();
	
	
	//resetZlevels();
}





function makeNewSldForConfigure(layerName, type, attName, divisorName, lowValue, hiValue, classSelected, colorBdy, colors, fillOpac, lineWeigh)
{
	// calculate the classification criteria
	var numChar = classSelected.split('-');
	var number = parseInt(numChar[0]);
	var increment = (parseInt(hiValue) - parseInt(lowValue)) / number;
	var value = new Array(number+1);
	for(var i = 0; i< number+1 ; i++)
	{
		if(i == 0)	{	value[i] = lowValue;}
		else		{	value[i] = value[i-1] + increment;}
	}
	value[number+1] = hiValue;
	
	// separate colours into an array
	colors = colors.split(",")

	// build up the type descriptions
	if(type == 'totals'){var absstractDesc = 'Totals for 2006 ABS Population';}
	if(type == 'percentages'){var abstractDesc = 'Percentage of 2006 ABS Population';}
	if(type == 'densities'){ var abstractDesc = 'Densities of 2006 ABS Population';} 
	
	// now start building the sld string
	var sldBody = "<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'>";
	sldBody+="<NamedLayer><Name>"+layerName+"</Name><UserStyle><Title>Temporary SLD for "+type+" analysis</Title>";
	sldBody+="<Name>"+attName+"</Name>";
	sldBody+="<Abstract>ABS Census Collector District Boundaries depicting "+attName+" within the CCDs.</Abstract>";
	sldBody+="<FeatureTypeStyle>";
	sldBody+="<Rule><Name>zero</Name><Title>Zero</Title><Abstract>Total 2006 ABS Population by Census Collection Districts is Zero</Abstract>";
	sldBody+="<Filter>";
	if(type == 'Percent' || type == 'Density'){sldBody+="<Or>";}
	sldBody+="<SqlExpression>"+attName+" = '0'</SqlExpression></Filter>";
	if(type == 'Percent' || type == 'Density')
	{
		sldBody+="<SqlExpression>"+divisorName+" = '0'</SqlExpression></Filter>";
		sldBody+="</Or>";
	}	
	sldBody+="<PolygonSymbolizer><Fill><CssParameter name='fill'>transparent</CssParameter></Fill></PolygonSymbolizer></Rule>";
	
	// now build each rule
	for(var i=0; i<number ; i++)
	{
		sldBody+="<Rule>";
		sldBody+="<Name>"+value[i]+" - "+value[i+1]+"</Name>";
		sldBody+="<Abstract>"+abstractDesc+" by Census Collection Districts between "+value[i]+" and "+value[i+1]+" people</Abstract>";
		sldBody+="<Filter><And>";
		if(type == 'totals')
		{
			sldBody+="<SqlExpression>"+attName+" &gt; '"+value[i]+"'</SqlExpression>";
			sldBody+="<SqlExpression>"+attName+" &lt; '"+value[i+1]+"'</SqlExpression>";
		}
		else if(type == 'percentages')
		{
			sldBody+="<SqlExpression>"+divisorName+" &gt; '0'</SqlExpression>";
			sldBody+="<SqlExpression>"+attName+" &gt; '0.0'</SqlExpression>";
			sldBody+="<SqlExpression>"+attName+" / "+divisorName+" * 100 &gt; '"+value[i]+"'</SqlExpression>";
			sldBody+="<SqlExpression>>"+attName+" / "+divisorName+" * 100 &gt; '"+value[i+1]+"'</SqlExpression>";
		}
		else if(type == 'densities')
		{
			sldBody+="<SqlExpression>"+attName+" &gt; '0.0'</SqlExpression>";
			sldBody+="<SqlExpression>"+divisorName+" &gt; '0'</SqlExpression>";
			sldBody+="<SqlExpression>"+attName+" / "+divisorName+" &gt; '"+value[i]+"'</SqlExpression>";
			sldBody+="<SqlExpression>"+attName+" / "+divisorName+" &lt; '"+value[i+1]+"'</SqlExpression>";
		}
		sldBody+="</And></Filter>";

		// now add the colour fill rendering
		sldBody+="<PolygonSymbolizer><Fill><CssParameter name='fill'>#"+colors[i]+"</CssParameter>";
		sldBody+="<CssParameter name='fill-opacity'>1</CssParameter></Fill></PolygonSymbolizer>";
					
		// now the optional liune rendering
		if(lineWeight == '0'){lineSymboliser = '';}
		else 
		{	sldBody+="<PolygonSymbolizer><Stroke>";
			sldBody+="<CssParameter name='stroke'>#"+colorBdy+"</CssParameter>";
			sldBody+="<CssParameter name='stroke-width'>"+lineWeight+"</CssParameter>";
			sldBody+="</Stroke></PolygonSymbolizer>";
		}	
		sldBody+="</Rule>";
	}
			
	// now close off the SLD string
	sldBody+="</FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";

	return sldBody;

}

function makeNewSldForFilter(newFile, layerName, classCodeArray, classValueArray, classOperArray, classTitleArray, colorBdyArray, colorFillArray, fillOpacArray, lineWeightArray, minScale, maxScale)
{
	
	var layerParts = layerName.split(":");
	var layer = layerParts[0];
	var sldAbstract ='Thematic Map showing '+layer+ ' classified by user selected attribute values.';
	
	// Set up the file header information and create file stubb
	var query = "?file="+newFile;
	query+= "&layer="+layerName;
	query+= "&title=Temporary DDrape for "+layer;
	query+= "&name="+layer+" Analysis";
	query+= "&theme=";
	query+= "&abstract="+sldAbstract;
	//alert(newFile)

	// send this request off to the server to create a new header section in a new SLD file
	var url = "inc/createSldStubb.php";	
	//alert(url+query)
	if (!makeXml(url, query, false)) {alert ('Oops an error here'); return;}
	
	// rules look for input arrays
	for (var i=0; i<classCodeArray.length; i++)
	{
		var query="?file="+newFile;

			// start with the mandatory rule elements
			query+="&nam="+classTitleArray[i];
			query+="&tit="+classTitleArray[i]; 
			query+="&abs=When attribute "+classCodeArray[i]+classOperArray[i]+classValueArray[i];
			query+="&min="+minScale;
			query+="&max="+maxScale;

			// escape any + or - sign is sqlExp
			var sqlExpression = classCodeArray[i]+classOperArray[i]+classValueArray[i];
			var sqlCoded = sqlExpression.replace(/\+/g, "*plus*");
			sqlCoded = sqlCoded.replace(/\-/g, "*minus*");
			query+="&sql="+sqlCoded;
			//alert('new sql = '+sqlCoded)
		
			// now get the symbology data for color fill
			if (colorFillArray[i] != 'transparent' && colorFillArray[i] != null)
			{	colorFillArray[i] = colorFillArray[i].split("#")[1];	// strip off # sign
				query+="&fillc="+colorFillArray[i];
			}
			else
			{	query+="&fillc=";	}

			if (fillOpacArray[i] != '' && fillOpacArray[i] !='transparent') 
			{	query+="&fillo="+fillOpacArray[i]; }
			else {query+="&fillo=";}

			if (colorBdyArray[i] != '' && colorBdyArray[i] != null && colorBdyArray[i] != 'undefined' )  
			{	
				// this means a line colour has been selected
				colorBdyArray[i] = colorBdyArray[i].split("#")[1];	// strip off # sign
				query+="&linc="+colorBdyArray[i];

				if (lineWeightArray[i] != '') 
				{	query+="&linw="+lineWeightArray[i];}	
				else {query+="&linw=";}

			}
			else 
			{	
				query+="&linc=";
				query+="&linw=";
				query+="&lino=";
			
			}
					
			// send this query string rule to the server to be appended into file
			var url = "inc/insertSldRule.php";
			//alert(url+query)
			makeXml(url, query, false);
	}
				
}
/*//--------------- function to create a new SLD from arrays ----------------------
	function makeNewSld2()
	{
		//alert('makeNewSld drapeId = '+drapeId)
		// kill off last temporary SLD file
		if(newFileName)
		{	deleteit(newFileName);		}
		
		// set up the new temp sld file as newFileName
		newFileName = sldOffset;
		//alert('newfilename in buildSld = '+newFileName)

		// to make sure you get all updates revisit all header data 
		nameData = document.getElementById('sldName').value;
		titleData= document.getElementById('sldTitle').value;
		sldAbstract= document.getElementById('sldAbsNo').value;
		//alert('theme obj = '+document.getElementById('drapeTheme'));
		var selObj = document.getElementById('drapeTheme');

		sldTheme = selObj.options[selObj.selectedIndex].value;
		//alert ('Theme = '+sldTheme)
		
		// to be sure just pick up the Rule Condition header info of current row
		RuleName[currentRow] = document.getElementById('nameNo').value;
		RuleAbstract[currentRow] = document.getElementById('absNo').value;
		RuleTitle[currentRow] = document.getElementById('titleNo').value;
		
		// Set up the file header information and create file stubb
		var query = "?file="+newFileName;
		query+= "&layer="+layerName;
		query+= "&title="+titleData;
		query+= "&name="+nameData;
		query+= "&theme="+sldTheme;
		query+= "&abstract="+sldAbstract;

		// send this request off to the server to create a new header section in a new SLD file
		var url = "inc/createSldStubb.php";	
		//alert(url+query)
		if (!makeXml(url, query, false)) {alert ('Oops an error here'); return;}
		
		// loop through rule arrays and create the SLD rules
		for (var i=0; i<sqlExp.length; i++)
		{
			//sqlExp[i] = sqlExp[i].replace(/ /, "")
			//alert("rule No = " +i+" = "+sqlExp[i]);
			var query="?file="+newFileName;

			// start with the mandatory rule elements
			query+="&nam="+RuleName[i];
			query+="&tit="+RuleTitle[i];
			query+="&abs="+RuleAbstract[i];
			query+="&min="+ruleMinScale[i];
			query+="&max="+ruleMaxScale[i];

			// escape any + or - sign is sqlExp
			var sqlCoded = sqlExp[i].replace(/\+/g, "*plus*");
			sqlCoded = sqlCoded.replace(/\-/g, "*minus*");
			query+="&sql="+sqlCoded;
		
			// now get the symbology data
			if (fillColor[i] != 'transparent' && fillColor[i] != null)
			{	var fillColorCode = fillColor[i].split("#")	// strip off # sign
				query+="&fillc="+fillColorCode[1];
			}
			else
			{	query+="&fillc=";	}

			if (fillOpacity[i] != '' && fillOpacity[i] !='transparent') 
			{	query+="&fillo="+fillOpacity[i]; }
			else {query+="&fillo=";}

			if (fillPattern[i] != '') 
			{	query+="&fillp="+fillPattern[i]; }
			else {query+="&fillp=";}

			if (lineColor[i] != '' && lineColor[i] != null && lineColor[i] != 'undefined' )  
			{	
				// this means a line colour has been selected
				var lineColorCode = lineColor[i].split("#")	// strip off # sign
				query+="&linc="+lineColorCode[1];

				if (lineWeight[i] != '') 
				{	query+="&linw="+lineWeight[i];}	
				else {query+="&linw=";}

				if (lineOpacity[i] != '') 
				{	query+="&lino="+lineOpacity[i];}	
				else {query+="&lino=";}
			}
			else 
			{	
				query+="&linc=";
				query+="&linw=";
				query+="&lino=";
			
			}
					
			//alert('query = '+query)
			// send this query string rule to the server to be appended into file
			var url = "inc/insertSldRule.php";
			//alert(url+query)
			makeXml(url, query, false);
			//sldBuilderDiv.style.display='none';
			document.getElementById('drapeBuilder').style.display="none";
			document.getElementById('editDDIn').title='SHOW StyleBuilder';

		}
	}

*/




function getSelectedRadioValue(objName)
{	
	// search through all the elements in form for this objName
	if(document.getElementsByName(objName))
	{
		var radioObj = document.getElementsByName(objName);
		for(var i=1; i<radioObj.length; i++)
		{	
			if(radioObj[i].checked)
			{	return radioObj[i].value;		}
		}
	}
	return '';
}

function toggleDDrapeModes(thisId)
{
	var title = document.getElementById(thisId).title;
	var thisFunction = thisId.split("Mode")[0];
//alert(thisFunction)	
	
	// check for an enter button selection 
	if(title == 'enter library mode' || title == 'enter analysis mode' || title == 'enter filter mode')
	{
		//alert('exit polygon Aggregation mode')		
		//exitPolygonAggregation();		
		showHideLegend('legendDD');		
		manageLegendControls();
		
		if(thisFunction == 'library') 
		{
			//alert('processing '+thisFunction)
			// set library buttons
			mousedown('libraryMode');
			document.getElementById('libraryModeSection').style.display='block';
			document.getElementById(thisId).title = 'exit library mode';
			updateTitle('Library');
			mode='library';
			
			// attend to other buttons
			if(configFlag) { mouseup('configMode'); }
			if(infoFlag)
			{	
				document.getElementById('gfiDD').style.display='block';
				mouseup('gfiDD');
			}
			if(filterFlag)
			{	
				mouseup('filterMode');
				document.getElementById('filterModeSection').style.display='none';
				document.getElementById('filterMode').title = 'enter filter mode';
			}
			document.getElementById('configModeSection').style.display='none';		
			if(configFlag){document.getElementById('configMode').title = 'enter library mode';}

			LibraryMode = true; FilterMode = false; ConfigMode = false;
		}
		else if(thisFunction == 'config' && configFlag ) 
		{
			//alert('processing '+thisFunction)
			// set config buttons
			mousedown('configMode');
			document.getElementById('configModeSection').style.display='block';
			document.getElementById(thisId).title = 'exit analysis mode';
			updateTitle('Analysis');
			mode='config';
			// attend to other buttons
			mouseup('libraryMode'); 
			document.getElementById('gfiDD').style.display='none';
			if(filterFlag)
			{
				mouseup('filterMode');
				document.getElementById('filterModeSection').style.display='none';
				document.getElementById('filterMode').title = 'enter filter mode';
			}
			document.getElementById('libraryModeSection').style.display='none';
			document.getElementById('libraryMode').title = 'enter library mode';
			LibraryMode = false; FilterMode = false; ConfigMode = true;
			level=0; layer=0; theme=0;
			loadAnalysisOptions();
			
		}
		else if(thisFunction == 'filter' && filterFlag) 
		{
			//alert('processing '+thisFunction)
			// set filter buttons
			mousedown('filterMode');
			document.getElementById('filterModeSection').style.display='block';
			document.getElementById(thisId).title = 'exit filter mode';
			updateTitle('Filter');
			mode='filter';
			
			// attend to other buttons
			mouseup('libraryMode'); mouseup('configMode');
			document.getElementById('gfiDD').style.display='none';
			document.getElementById('libraryMode').title = 'enter library mode';
			if(configFlag){document.getElementById('configMode').title = 'enter filter mode';}
			document.getElementById('libraryModeSection').style.display='none';
			document.getElementById('configModeSection').style.display='none';

			LibraryMode = false; FilterMode = true; ConfigMode = false;
			level=0; layer=0; theme=0;
			loadFilterOptions();
		}

		// now remove any DDrapes already displayed
		if(DemoDrape){removeAllDrapeLayers();}
		
		// remove any existing temp DDrape file 
		if(getFile)	
		{	
			var parts = getFile.split('newSld_');
			if(parts.length >1)
			{	
				// delete temp sld first
				deleteit(getFile);
				
				// delete temp cache next
				//alert(getFile);	
				getAndPurgeDrapeCache();
			
			}
		}
		
	}
	else // when a button set to Exit was hit
	{
		alert('to exit this function you need to select an alternative function.')
	}
	
}

