// Usage:
//	builder	= the id of the Div that holds the Sld Builder forms
//	sld		= the full name of the SLD current and to be used as a template for a new SLD
//
function initRulesArrays()
{
		layerAttributes = new Array();
		layerAtts = new Array();
		RuleName = new Array(); 
		RuleTitle = new Array();
		RuleAbstract = new Array();
		ruleMinScale = new Array();
		ruleMaxScale =  new Array();
		fillColor = new Array();
		fillOpacity = new Array(); 
		fillPattern = new Array();
		lineWeight = new Array();
		lineColor = new Array();
		lineOpacity = new Array();
		lineDash = new Array();
		sqlExp = new Array();
		attNames = new Array();
		format = new Array();
		sqlExpressions = new Array();
		sqlExpTemp = new Array();
		areaFillSymbols = new Array();
		
		// apply XML browser difference here
		prefix='xs:';
		if ((browser =='firefox' && version == '2') || (browser == 'safari'))
		{	prefix='';	}
		//alert('your bowser is '+browser+' version ' +version)
		arrayNo = 0;
}

function sldBuilder(builder, currentSld)
{
	 removeOldDrape = false;
	 //alert('sldBuilder currentDrapeId = '+currentDrapeId)
	 //alert('current Drape Style = '+currentDrapeStyle);
	//alert (theme); alert(themeTitle);
	//alert(currentSld) // note that this is the full file url
	//alert('sldBuilder drapeId = '+drapeId)
	//alert('sldBuilder input SLD = '+currentSld)
	// open the SLD file and load data into SLD editing arrays
	genLoadStatus('Loading SLD ....', true)
	getSldRuleData(currentSld);
	getSldInfo(currentSld);
	//alert (currentSld+" \n "+layerName+" \n "+titleData+" \n "+nameData+" \n "+sldAbstract);
	if(sqlExp.length == 0) 
	{
		checkRemoveObject('drapeBuilder');
		alert('The DemographicDrape SLD is incompatible with this application');
		genLoadStatus('', false)
		return false;
	}
	//alert('builder = '+builder) // wholeThing
	// initialise arrays
	initRulesArrays();
	checkRemoveObject('drapeBuilder');
	
	// make the application visible
	sldBuilderDiv = document.createElement('div');
	sldBuilderDiv.style.display='block';
	sldBuilderDiv.style.zIndex='60001';
	sldBuilderDiv.style.position='absolute';
	sldBuilderDiv.style.top='50px'; 
	sldBuilderDiv.style.left='320px';
	sldBuilderDiv.style.width='760px'; 
	sldBuilderDiv.style.height='450px';
	//sldBuilderDiv.style.backgroundColor='#ECE9D8'; 
	//sldBuilderDiv.style.border='2px solid #0055E5';
	sldBuilderDiv.id = 'drapeBuilder';
	sldBuilderDiv.setAttribute("id", 'drapeBuilder');

	// create the banner div
	var sldBuilderDivBanner = document.createElement('div');
	sldBuilderDivBanner.className = 'popupDDrapeHeader';
	sldBuilderDivBanner.style.backgroundImage='url(images/banner_760.gif)';
	sldBuilderDivBanner.id = 'appHolder';
	sldBuilderDivBanner.style.zIndex='6002';

	// create the numaps logo symbol image tag
		var symbolImg = document.createElement('img');
		symbolImg.src='images/logo_symbol_small.gif';
		symbolImg.style.position='absolute';
		symbolImg.style.top='7px'; 
		symbolImg.style.left='8px';
		sldBuilderDivBanner.appendChild(symbolImg);
		
		// now add the title in the Banner
		var spanTag = document.createElement('span');
		spanTag.style.position='absolute';
		spanTag.style.top='4px';
		spanTag.style.left='34px';
		var bannerText = document.createTextNode('DemographicDrape(TM) Styler');	
		//var bannerText = document.createTextNode('DemographicDrape(TM) Builder');	
		spanTag.appendChild(bannerText);
		sldBuilderDivBanner.appendChild(spanTag);
	

		// create the filename info box
		var sldFileNameBox = document.createElement('div');
		sldFileNameBox.style.position='absolute';
		sldFileNameBox.style.top='3px';
		sldFileNameBox.style.color='#000';
		sldFileNameBox.style.left='300px';
		sldFileNameBox.width='250px';
		sldFileNameBox.height='20px';
		sldFileNameBox.style.fontSize = '10px';
		sldFileNameBox.style.id='sldInfoBox';
		sldFileNameBox.setAttribute('id','sldInfoBox');

		// get the new temp sld filename and path
		//alert('currentSld = '+currentSld)
		var parts = currentSld.split(applicationBase);
		if(parts.length > 1){  getNewSldName(parts[1]);		}
		else				{  getNewSldName(currentSld);	}						// this outputs newTempSldPath and newTempSldFile
		sldOffset = newTempSldPath + newTempSldFile;
		
		// create a filename text node to sld builder banner
		var fileOnly = parts[1].split('/');
		var originalFile = fileOnly[fileOnly.length-1]
		var fileText = document.createTextNode('FileName = '+originalFile);
		sldFileNameBox.appendChild(fileText);
		sldBuilderDivBanner.appendChild(sldFileNameBox);

		// add the view SLD button
		var symbolImg = document.createElement('img');
		symbolImg.src='images/world_edit.png';
		symbolImg.id= 'sldTextEditor';
		symbolImg.setAttribute('id','sldTextEditor');
		symbolImg.style.position='absolute';
		symbolImg.style.top='5px'; 
		symbolImg.style.right='28px';
		symbolImg.style.cursor='pointer';
		symbolImg.value = currentSld;
		symbolImg.title = 'click here to open SLD in a popup Editor';
		bindEvent(symbolImg, 'click', popupTextEditor, 'false');
		sldBuilderDivBanner.appendChild(symbolImg);

		// add the close button
		var symbolImg = document.createElement('img');
		symbolImg.src='images/close.gif';
		symbolImg.style.width='15px';
		symbolImg.style.height='15px';
		symbolImg.style.cursor='pointer';
		symbolImg.style.position='absolute';
		symbolImg.style.top='5px'; 
		symbolImg.style.right='8px';
		bindEvent(symbolImg, 'click', closeBuilder, 'false');
		sldBuilderDivBanner.appendChild(symbolImg);
	sldBuilderDiv.appendChild(sldBuilderDivBanner);

	// create the drapeBody div
	var drapeBody = document.createElement('div');
	drapeBody.style.backgroundColor='#ECE9D8'; 
	drapeBody.style.border='2px solid #0000CE';
	drapeBody.style.top='22px';
	drapeBody.style.width='756px';
	drapeBody.style.height='435px';
	
	
	// header section label
	var ddrapeSection = document.createElement('div');
	var sectionText = document.createTextNode('Header Section');
	ddrapeSection.appendChild(sectionText);
	ddrapeSection.className='ddrapeSection';
	ddrapeSection.style.position='absolute'; 
	ddrapeSection.style.top='25px'; 
	ddrapeSection.style.left='20px';
	drapeBody.appendChild(ddrapeSection);

	// Legend Editor label
	var legendSection = document.createElement('div');
	var sectionText = document.createTextNode('Legend Editor Section');
	legendSection.appendChild(sectionText);
	legendSection.className='legendSection';
	legendSection.style.position='absolute'; 
	legendSection.style.top='25px'; 
	legendSection.style.left='530px';
	drapeBody.appendChild(legendSection);

	// Rules Editing Form section
	var rulesSection = document.createElement('div');
	var sectionText = document.createTextNode('Rules Editing Section');
	rulesSection.appendChild(sectionText);
	rulesSection.className='rulesSection';
	rulesSection.style.position='absolute'; 
	rulesSection.style.top='95px'; 
	rulesSection.style.left='20px';
	drapeBody.appendChild(rulesSection);
				
	// get the header information of the SLD
	// this returns as global vars layerName, titleData and nameData 
	if(!getSldInfo(currentSld)) {alert ("cannot read SLD file in getSldInfo"); return false;}
	
	// remove all DDrape Tables
	checkRemoveObject('builderTable');
	checkRemoveObject('info');
	checkRemoveObject('legendt');
	checkRemoveObject('sldAbstract');
	//alert(layerName);
	//alert(titleData);
	//alert(nameData);
	
	// create a holding Div for two tables
	var sldDiv = document.createElement('div');
	sldDiv.style.position='absolute';
	sldDiv.className="sldBuild";
	sldDiv.style.top='40px';
	sldDiv.style.left='20px';
	sldDiv.style.width='500px'; 
	sldDiv.style.height='50px';

		// create the new DDrape Header table
		var table = document.createElement('table');
		table.style.position='absolute';
		table.style.top='0px';
		table.style.left='0px';
		table.style.width='500px'; 
		table.style.height='20px';
		table.setAttribute('border','0');
		table.id='builderTable';
		table.setAttribute('id','builderTable');
		var headerTable = document.createElement('tbody');		

			// SLD Name  
			var headRow = document.createElement('tr');
				var headCell1 = document.createElement('td');
				//headCell1.className="headTitleCell";
				headCell1.style.width='45px';
				headCell1.style.height='15px';
				headCell1.style.paddingLeft='2px';
				headCell1.style.fontWeight='bold';
				var cell1Text = document.createTextNode('Name: * ');
				headCell1.appendChild(cell1Text);
				headCell1.title="Name of DemographicDrape - This appears at the top of the generated legend and is editable";
				headRow.appendChild(headCell1);

				var headCell2 = document.createElement('td');
				headCell2.className="headDataCell";
				headCell2.style.width='165px';
				headCell2.style.height='15px';
				headCell2.title="Simply click in this cell and edit the Demographic Drape Name - limit this to approximately 25 characters (max 30) as a long title will not look nice in the Editing legend";
				var headCell2Edit2 = document.createElement('Input');
				headCell2Edit2.className='headDataCellEdit';
				headCell2Edit2.style.width='165px';
				headCell2Edit2.setAttribute('maxLength','30');
				headCell2Edit2.maxLength = '60';
				headCell2Edit2.value = nameData;
				headCell2Edit2.id = 'sldName'; 
				headCell2Edit2.setAttribute("id", 'sldName');
				headCell2Edit2.style.width='165px';
				bindEvent(headCell2Edit2, 'change', saveTitle, 'false');
				headCell2.appendChild(headCell2Edit2);
				//var cell2Text = document.createTextNode(nameData);
				//headCell2.appendChild(cell2Text);
				headRow.appendChild(headCell2);

				// SLD Title 
				var headCell1 = document.createElement('td');
				headCell1.className="headTitleCell";
				headCell1.style.width='45px';
				headCell1.style.height='15px';
				var cell1Text = document.createTextNode('Title: ');
				headCell1.appendChild(cell1Text);
				headCell1.title="Title of DemographicDrape. This shows up as a tool tip when you mouseover the legend Title and is editable";
				headRow.appendChild(headCell1);

				var headCell2 = document.createElement('td');
				headCell2.className="headDataCell";
				headCell2.style.width='165px';
				headCell2.style.height='15px';
				headCell2.title="Simply click in this cell and edit the Demographic Drape Title.";
				var headCell2Edit1 = document.createElement('Input');
				headCell2Edit1.className='headDataCellEdit';
				headCell2Edit1.value = titleData;
				headCell2Edit1.id = 'sldTitle'; 
				headCell2Edit1.setAttribute("id", 'sldTitle');
				headCell2Edit1.style.width='165px';
				bindEvent(headCell2Edit1, 'change', saveTitle, 'false');
				headCell2.appendChild(headCell2Edit1);
				//var cell2Text = document.createTextNode(sldTitleData);
				//headCell2.appendChild(cell2Text)
			headRow.appendChild(headCell2);
		headerTable.appendChild(headRow);
		
	table.appendChild(headerTable);
	sldDiv.appendChild(table);
	genLoadStatus('', false)


// ------------------ now add the SLD Abstract as a sigle row --------------------
		// build the Rule header information Table
		var absTable = document.createElement('table');
		absTable.setAttribute('border','0');
		absTable.style.position='absolute';
		absTable.style.top='25px'; 
		absTable.style.left='0px';
		absTable.style.width='auto' ;
		absTable.id='sldAbstract';
		absTable.setAttribute('id','sldAbstract');
		absTable.style.height='auto';
		//absTable.setAttribute('border','1');
		absTable.className='abstractTable';
		var absTableBody = document.createElement('tbody');
		
		var abstractRow = document.createElement('tr');
			var headCell1 = document.createElement('td');
			headCell1.className="ruleTitleCell";
			headCell1.style.width='50px';
			var cell1Text = document.createTextNode('Abstract:');
			headCell1.appendChild(cell1Text);
			abstractRow.appendChild(headCell1);

			var absCell = document.createElement('td');
			absCell.className="abstractDataCell";
			absCell.style.width='165px';
			var abstractCell2Edit1 = document.createElement('Input');
			abstractCell2Edit1.className='headDataCellEdit';
			//abstractCell2Edit1.className='abstractDataCellEditInput';
			//abstractCell2Edit1.style.width='415px';
			abstractCell2Edit1.style.width='165px';
			if(sldAbstract != ''){	abstractCell2Edit1.value = sldAbstract;}
			else {abstractCell2Edit1.value =''}
			abstractCell2Edit1.id = 'sldAbsNo'; 
			abstractCell2Edit1.setAttribute("id", 'sldAbsNo');
			//var rowsInTextBox = 3
			//if (browser == 'firefox' && version == '2')
			//{	rowsInTectBox = 2;	}		
			//abstractCell2Edit1.setAttribute("rows", rowsInTextBox);
			abstractCell2Edit1.title='The Abstract contains detailed information about the DemographicDrape';
			bindEvent(abstractCell2Edit1, 'change', saveTitle, 'false');
			absCell.appendChild(abstractCell2Edit1);
		abstractRow.appendChild(absCell);

			// add the abstract editor button
			var innerRowCell = document.createElement('td');
				var popupButt = document.createElement('div');		
				popupButt.style.width='20px';
				popupButt.style.height='18px';
				popupButt.title='click here for the larger Abstract Editor form'
				popupButt.style.cursor='pointer';
					
					// add the internal image
					var symbolImg = document.createElement('img');
					symbolImg.src='images/world_edit.png';
					symbolImg.id= 'abstract:sldAbsNo';
					symbolImg.setAttribute('id','abstract:sldAbsNo');
					bindEvent(symbolImg, 'click', popupAbstractEditor, 'false');
					
				popupButt.appendChild(symbolImg);
			innerRowCell.appendChild(popupButt);
		abstractRow.appendChild(innerRowCell);
		//setOpacity(symbolImg, 50)

		// create the Theme Pick list field
			var headCell1 = document.createElement('td');
			headCell1.className="ruleTitleCell";
			headCell1.style.width='56px';
			var cell1Text = document.createTextNode('Theme: *');
			headCell1.appendChild(cell1Text);
		abstractRow.appendChild(headCell1);

			var headCell2 = document.createElement('td');
			//headCell2.className="ruleDataCell";
			headCell2.style.width='190px';
			headCell2.style.height='15px'
			var ruleCell2Edit1 = document.createElement('div');
			//ruleCell2Edit1.className='headDataCellEdit';
			ruleCell2Edit1.style.width='100%';
			//ruleCell2Edit1.value = RuleTitle[row];		
			ruleCell2Edit1.id = 'themeNo'; 
			ruleCell2Edit1.setAttribute("id", 'themeNo');
			//ruleCell2Edit1.style.zIndex='202';
			ruleCell2Edit1.title='Please select one Theme from this pick list'
			//bindEvent(ruleCell2Edit1, 'change', saveTheme, 'false');
			headCell2.appendChild(ruleCell2Edit1);
		abstractRow.appendChild(headCell2);
			
		absTableBody.appendChild(abstractRow);
		absTable.appendChild(absTableBody);
		sldDiv.appendChild(absTable);
	
	drapeBody.appendChild(sldDiv);
	sldBuilderDiv.appendChild(drapeBody);
	document.getElementById(builder).appendChild(sldBuilderDiv)
	Drag.init(sldBuilderDivBanner, sldBuilderDiv);

	// get the theme list from the server
	getThemeList();
	
	// create the theme picker element
	createThemePicker(ruleCell2Edit1, theme)
		
	// get the rules of the current SLD
	getSldRuleData(currentSld);
	
	// build the editing legend from the edit rules array
	currentRow = 0;
	previousRow = 0;
	buildEditLegend(drapeBody)

	// load the first rule into editor
	var id1="tdBox:"+currentRow;
	var id2="rule:"+currentRow;
	document.getElementById(id1).className='selectedItem';
	document.getElementById(id2).className='selectedItem';
	//document.getElementById(id1).style.border='3px solid red';
	//document.getElementById(id2).style.border='3px solid red';
	
	// build the rules editing section
	buildEditorForm(drapeBody, currentRow);

	// Go back and add the Replace element components to Edit Legend
	buildReplaceForm(drapeBody);
	
	// Drape Builder setup now we can exit
	return;

}

//-------------------------------------------------------------------------------------------------------------
//				Assumes that all the legend rendering info is loaded into arrays already

function buildEditLegend(sldBuilderDiv)
{
	if(!document.getElementById('ruleControlButtons'))
	{
		//alert ('creating buttons')
	// ---------------- create the Buttons for Rule controls ---------------------
		var ruleControls = document.createElement('div');
			ruleControls.style.position='absolute';
			ruleControls.style.top='37px';
			ruleControls.style.left='526px';
			ruleControls.style.width='220px';
			ruleControls.id='ruleControlButtons';
			ruleControls.setAttribute('id','ruleControlButtons');
			var innerTable = document.createElement('table');
			innerTable.style.width='220px';
			//innerTable.setAttribute('border',1);
			//innerTable.style.borderCollapse='collapse';
				var innerTableBody = document.createElement('tbody');
				var innerRow = document.createElement('tr')

					// ---------------- create a New SLD button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
						var saveButt = document.createElement('div');
						saveButt.id='newSld';
						saveButt.style.width='49px';
						saveButt.setAttribute('id','newSld');
						saveButt.className ='buttonUp';
							var titleText = document.createTextNode('New');
							saveButt.appendChild(titleText);
						//saveButt.value='New';
						saveButt.title='Clears out all the Rules for Creating a NEW DemographicDrape';
						bindEvent(saveButt, 'mousedown', buttonDepress, 'false');
						bindEvent(saveButt, 'click', clearSld, 'false');
						innerRowCell.appendChild(saveButt);
					innerRow.appendChild(innerRowCell);

					// ---------------- create a big Global replace SLD button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
						var saveButt = document.createElement('div');
						saveButt.id='replaceSld';
						saveButt.style.width='49px';
						saveButt.setAttribute('id','replaceSld');
						saveButt.className ='buttonUp';
							var titleText = document.createTextNode('Replace');
							saveButt.appendChild(titleText);
						//saveButt.value='New';
						saveButt.title='Allows you to globally change an attribute to generate a Similar DemographicDrape';
						bindEvent(saveButt, 'mousedown', buttonDepress, 'false');
						bindEvent(saveButt, 'click', replaceSld, 'false');
						innerRowCell.appendChild(saveButt);
					innerRow.appendChild(innerRowCell);

					// ---------------- create a big Global color Theme select SLD button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
						var saveButt = document.createElement('div');
						saveButt.id='fillTheme';
						saveButt.style.width='49px';
						saveButt.setAttribute('id','fillTheme');
						saveButt.className ='buttonUp';
							var titleText = document.createTextNode('Theme');
							saveButt.appendChild(titleText);
						//saveButt.value='New';
						saveButt.title='Allows you to globally select/change a 9-colour theme';
						bindEvent(saveButt, 'mousedown', buttonDepress, 'false');
						bindEvent(saveButt, 'click', themeSld, 'false');
						innerRowCell.appendChild(saveButt);
					innerRow.appendChild(innerRowCell);


					// ---------------- create a big Save SLD button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
						var saveButt = document.createElement('div');
						saveButt.style.width='49px';
						saveButt.id='saveSld';
						saveButt.setAttribute('id','saveSld');
						saveButt.className ='buttonUp';
								var titleText = document.createTextNode('Save');
								saveButt.appendChild(titleText);
						//saveButt.value='Save';
						saveButt.title='SAVE the current DemographicDrape for testing outside of this Builder';
						bindEvent(saveButt, 'mousedown', buttonDepress, 'false');
						bindEvent(saveButt, 'click', saveSld, 'false');
					innerRowCell.appendChild(saveButt);
					innerRow.appendChild(innerRowCell);
			
					

				innerTableBody.appendChild(innerRow);
				innerTable.appendChild(innerTableBody);
			ruleControls.appendChild(innerTable);

				
			var innerTable = document.createElement('table');
				innerTable.style.position='absolute';
				innerTable.style.top='20px';
				innerTable.style.left='0px';
				var innerTableBody = document.createElement('tbody');
				var innerRow = document.createElement('tr')

				// ---------------- create the Insert button ZZZZ ---------------------
					var innerRowCell = document.createElement('td')
					innerRowCell.style.height='16px';
					var insertButt = document.createElement('div');
					insertButt.className ='buttonUp';
						var titleText = document.createTextNode('Insert');
						insertButt.appendChild(titleText);
					insertButt.style.width='35px';
					insertButt.id='insertRule';
					insertButt.setAttribute('id','insertRule');
					insertButt.className ='buttonUp';
					//insertButt.value='Insert';
					insertButt.title='Insert a new empty rule after the currently selected condition';
					bindEvent(insertButt, 'mousedown', buttonDepress, 'false');
					bindEvent(insertButt, 'click', insertRule, 'false');
					innerRowCell.appendChild(insertButt);
					innerRow.appendChild(innerRowCell);

					// ---------------- create the Delete button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
					var delButt = document.createElement('div');
					delButt.className ='buttonUp';
						var titleText = document.createTextNode('Delete');
						delButt.appendChild(titleText);
					delButt.style.width='35px';
					delButt.id='deleteRule';
					delButt.setAttribute('id','deleteRule');
					delButt.className ='buttonUp';
					//delButt.value='Delete';
					delButt.title='Delete the currently selected rule';
					bindEvent(delButt, 'mousedown', buttonDepress, 'false');
					bindEvent(delButt, 'click', deleteRule, 'false');
					innerRowCell.appendChild(delButt);
					innerRow.appendChild(innerRowCell);

					// ---------------- create the Clear button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
					var clearButt = document.createElement('div');
					clearButt.className ='buttonUp';
						var titleText = document.createTextNode('Clear');
						clearButt.appendChild(titleText);
					clearButt.style.width='35px';
					clearButt.id='clearRule';
					clearButt.setAttribute('id','clearRule');
					clearButt.className ='buttonUp';
					//clearButt.value='Clear';
					clearButt.title='Clear out all the components of this rule and leave this as the current condition';
					bindEvent(clearButt, 'mousedown', buttonDepress, 'false');
					bindEvent(clearButt, 'click', clearRule, 'false');
					innerRowCell.appendChild(clearButt);
					innerRow.appendChild(innerRowCell);
			
					// ---------------- create the Clone button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
					var cloneButt = document.createElement('div');
					cloneButt.className ='buttonUp';
						var titleText = document.createTextNode('Clone');
						cloneButt.appendChild(titleText);
					cloneButt.style.width='35px';
					cloneButt.id='cloneRule';
					cloneButt.setAttribute('id','cloneRule');
					cloneButt.className ='buttonUp';
					//cloneButt.value='Clone';
					cloneButt.title='Clone the components of this rule into a newly created Rule';
					bindEvent(cloneButt, 'mousedown', buttonDepress, 'false');
					bindEvent(cloneButt, 'click', cloneRule, 'false');
					innerRowCell.appendChild(cloneButt);
					innerRow.appendChild(innerRowCell);
					
					
					// ---------------- create the UP SLD button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
					var saveButt = document.createElement('div');
					saveButt.className ='buttonUp';
						var titleText = document.createTextNode('Up');
						saveButt.appendChild(titleText);
					saveButt.style.width='20px';
					saveButt.id='ruleUp';
					saveButt.setAttribute('id','ruleUp');
					saveButt.className ='buttonUp';
					//saveButt.style.fontSize='9px';
					//saveButt.value='Up';
					saveButt.title='Move this Rule UP in the Legend';
					// insert the up arrow image
						//var symbolImg = document.createElement('img');
						//symbolImg.src='images/arrow_up.png';
						//symbolImg.style.height='12px';
						//symbolImg.style.width='12px';
						//symbolImg.id='upit';
						//symbolImg.setAttribute('id','upit');
					//saveButt.appendChild(symbolImg);
					bindEvent(saveButt, 'mousedown', buttonDepress, 'false');
					bindEvent(saveButt, 'click', ruleUp, 'false');
					innerRowCell.appendChild(saveButt);
					innerRow.appendChild(innerRowCell);
					
					// ---------------- create the DOWN SLD button  ---------------------
					var innerRowCell = document.createElement('td');
					innerRowCell.style.height='16px';
					//innerRowCell.style.border='1px solid blue';
					var saveButt = document.createElement('div');
					saveButt.className ='buttonUp';
						var titleText = document.createTextNode('Dn');
						saveButt.appendChild(titleText);
					saveButt.style.width='20px';
					saveButt.id='ruleDwn';
					saveButt.setAttribute('id','ruleDwn');
					saveButt.className ='buttonUp';
					//saveButt.value='Dn';
					//saveButt.style.fontSize='9px';
					saveButt.title='Move this Rule DOWN in the Legend';
						// insert the up arrow image
						//var symbolImg = document.createElement('img');
						//symbolImg.src='images/arrow_down.png';
						//symbolImg.style.height='12px';
						//symbolImg.style.width='12px';
						//symbolImg.id='upit';
						//symbolImg.setAttribute('id','upit');
					//saveButt.appendChild(symbolImg);
					bindEvent(saveButt, 'mousedown', buttonDepress, 'false');
					bindEvent(saveButt, 'click', ruleDown, 'false');
					innerRowCell.appendChild(saveButt);
					innerRow.appendChild(innerRowCell);	

	
				innerTableBody.appendChild(innerRow);
				innerTable.appendChild(innerTableBody);

			ruleControls.appendChild(innerTable);
		sldBuilderDiv.appendChild(ruleControls);
	}
	if(document.getElementById('legendt')){checkRemoveObject('legendt');}
	
	

	
	// --------------- create a new Editing Legend ---------------------
	
	// build up the legend DIV
	var editor = document.createElement('div');
	editor.id='legendt';
	editor.setAttribute('id','legendt');
	editor.className="editLegend";
	editor.style.position='absolute';
	editor.style.top='85px';
	editor.style.left='530px';
	editor.style.width='200px';
	editor.style.height='350px';
	//editor.style.border='1px solid blue';
	editor.style.overflowX='hidden'; 
	editor.style.overflowY='auto';
	editor.style.paddingBottom='10px';

		// --------------- create the div for the title text using nameData --------------
		var editTitle = document.createElement('div');
		var titleText = document.createTextNode(nameData);
		editTitle.id = 'editLegendTitle';
		editTitle.setAttribute('id','editLegendTitle');
		editTitle.appendChild(titleText);
		editTitle.className = "editTitle";
		editTitle.style.position='absolute'; 
		editTitle.style.height='35px'; 
		editTitle.style.width='100%'; 
		editTitle.style.top='5px';
		editTitle.style.left='0px';
		//editTitle.style.overflowX='hidden'; 
		//editTitle.style.overflowY='auto';
		//editTitle.style.border='1px solid red';
		editTitle.setAttribute("title", "header=[DemographicDrape Description] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+sldAbstract+"]");
		editTitle.title="header=[DemographicDrape Description] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+sldAbstract+"]";
		editor.appendChild(editTitle);
		
		// ----------------Set up the editing legend table ------------------
		var legendTab = document.createElement('table');
		//legendTab.className="editLegendTable";
		legendTab.style.position='absolute'; 
		legendTab.style.top='45px'; 
		legendTab.style.left='0px';
		legendTab.style.height='auto'; 
		legendTab.style.width='100%';
		var editTableBody = document.createElement('tbody');
		//editTableBody.className='editTableBody';
		editTableBody.style.position='absolute'; 
		editTableBody.style.top='40px'; 
		editTableBody.style.left='0px';
		editTableBody.style.height='auto'; 
		editTableBody.style.width='100%';
		
		// Loop through all the rules in the SLD file and build legend rows for each
		var num = RuleName.length;
		if(num > 0)
		{
			//alert ("building edit legend body")
			for (var i = 0; i < num ; i++)
			{	
				// create a table row element
				var ruleId="rule:"+i;
				var tdIdbox="tdBox:"+i;
				var rowId="row:"+i;
				var divId="div:"+i;
				var outDivId="divOut:"+i;
				var textId="text:"+i;
				
				// build each row
				var row = document.createElement('tr');
				row.setAttribute ("id", rowId);
				row.id=rowId;
				
				// generate the edit legend symbol and rule info cells
				buildSymbolBox(row, tdIdbox, divId, outDivId, ruleId, i);
					
				editTableBody.appendChild(row);
			}
		}
		else if(num == 0)	// this is for a brand new SLD
		{
		// create a table row element
			var ruleId="rule:0";
			var tdIdbox="tdBox:0";
			var rowId="row:0";
			var divId="div:0";
			var outDivId="divOut:0";
			var textId="text:0";
				
			// build a row
			var row = document.createElement('tr');
			row.setAttribute ("id", rowId);
			row.id=rowId;
				
			// generate the edit legend symbol and rule info cells
			buildSymbolBox(row, tdIdbox, divId, outDivId, ruleId, 0);
					
			editTableBody.appendChild(row);
		}
		
		// Append Table Body to Table
		legendTab.appendChild(editTableBody);
	editor.appendChild(legendTab);
	sldBuilderDiv.appendChild(editor);
	document.getElementById("sldTitle").focus();
}

//---------------------- build the table cells for the editing legend ---------------------
function buildSymbolBox(parentObj, tdIdbox, divId, outDivId, ruleId, irow)
{
	//alert( tdIdbox +" : "+ divId+" : "+ outDivId+" : "+ ruleId)
	
	// now create the legend symbol box
	var td1 = document.createElement("td");
		td1.style.width='40px';
		td1.style.height='20px';
		//td1.style.backgroundColor='transparent';
		td1.setAttribute ("id", tdIdbox);
		td1.id = tdIdbox;  
		td1.className='unselectedItem';
		//td1.style.border="1px solid gray";
		
		// now the internal Div used to colour fill
		var divNode = document.createElement("div");
		divNode.style.width = '36px';
		divNode.style.height = '16px';
		divNode.setAttribute ("id", divId);
		divNode.id = divId;
		//divNode.zIndex='209';
		divNode.style.borderStyle='none';
		divNode.style.marginLeft='auto';
		divNode.style.marginRight='auto';
			
		// fill in color if required
		if (fillColor[irow] != 'transparent'   )
		{	
			//alert('fill = '+fillColor[irow])
			divNode.style.backgroundColor = fillColor[irow];
			var op=Number(fillOpacity[irow]);
			var fillNumber = Math.abs(op*100);
			setOpacity(divNode, fillNumber);
		}
		// now check for fill patterns
		if (fillPattern[irow] != null)
		{
			var divNode2 = document.createElement("div");
			divNode2.style.width='36px';
			divNode2.style.height='15px';
			divNode2.style.backgroundImage = "url("+fillPattern[irow]+")";
			divNode2.style.backgroundRepeat='repeat';
			divNode.appendChild(divNode2);
		}
		
		// set up borders
		if (lineWeight[irow] == "" || lineWeight[irow] =="0" || lineWeight[irow] == null || lineColor[irow] == "" || lineColor[irow] =="0" || lineColor[irow] == null)
		{	divNode.style.borderStyle="none";	}
		else
		{	divNode.style.border = lineWeight[irow]+"px solid "+lineColor[irow];	}
		td1.appendChild(divNode);
		
		// strip out the file name of the pattern image if present
		var patternImg=null;
		if(fillPattern[irow] != null)
		{	
			patternImg = fillPattern[irow].split("/");
			if(patternImg[patternImg.length-1] == 'empty' ) 
			{	
				fillPattern[irow] = ''; 
				var pat = '';
			}
			else
			{	var pat = patternImg[patternImg.length-1];}
		}
		else
		{ var pat = '';}
		
		// prepare the tooltip for the moseover of the polygon rendering cell
		var renderingRuleTip =	
						"Min Scale		 : 1:"+ruleMinScale[irow]+"<br/>"+
						"Max Scale		 : 1:"+ruleMaxScale[irow]+"<br/>"+
						"Fill Colour	 : "+fillColor[irow]+"<br/>"+
						"Fill Pattern	 : "+pat+"<br/>"+
						"Fill Opacity	 : "+fillOpacity[irow]+"<br/>"+
						"Border Colour	 : "+lineColor[irow]+"<br/>"+
						"Border Thickness: "+lineWeight[irow]+"<br/>"+
						"Border Opacity	 : "+lineOpacity[irow];

					
		// set up tooltip for BoxOver
		td1.title="header=[Symbology Rules] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+renderingRuleTip+"]'";

	// append first cell to table row
	parentObj.appendChild(td1);

	// Now generate the Text node in the second column of the table row
	//alert('building legend name cell at row = '+i)
	var td2 = document.createElement("td"); 
		if (RuleName[irow] == null || RuleName[irow] == 'undefined' || RuleName[irow] == '' )
		{	var textNode = document.createTextNode(' ');	}
		else
		{	var textNode = document.createTextNode(RuleName[irow]);}
		td2.appendChild(textNode);
		td2.style.color='black';
		//td2.style.border='1px solid gray';
		td2.className='unselectedItem';
		td2.style.width='160px';
		td2.style.height='16px';
		td2.style.fontSize='10px';
		td2.style.paddingLeft='2px';
		//td2.style.backgroundColor='transparent';
		td2.setAttribute("id",ruleId);
		td2.id=ruleId;
		var ruleTip='';
		// generate the tool tip for this cell
		if (sqlExp[irow] != null)
		{
			//alert('sqlExp when building the legend = '+sqlExp[irow])
			// switch any *plus* and *minus* back
			//sqlExp[irow] = sqlExp[irow].replace(/*plus*/g, "+");
			//sqlExp[irow] = sqlExp[irow].replace(/*minus*/g, "-");
			
			var sqlExpressions = sqlExp[irow].split(",");
			for (var n=0; n<sqlExpressions.length ; n++ )
			{
				var ruleContent = sqlExpressions[n];
				if (n == 0)	{ruleTip = ruleContent;}
				else {ruleTip += " <br/>"+ruleContent;}
			}
		}
		//td2.title=ruleTip; // need to do this as I use it later in rollover
		td2.title = "header=[Name = "+ RuleName[irow] +"] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+ruleTip+"]'";
		
		// bind the interactive events to this cell
		bindEvent(td2, 'click', populateEditor, 'false');
		//bindEvent(td2, 'mouseover', rollOver, 'false');
		//bindEvent(td2, 'mouseout', rollOut, 'false');

	// append second cell to table row
	parentObj.appendChild(td2);

}

//----------- build the Replace attributes Form elements in same location as menu ------------------//
function buildReplaceForm(sldBuilderDiv)
{
	
	oldAttribute = ''; newAttribute = '';
	var temp = getAttributesUsed(sqlExp);
	
	
		// create a hidden Replace attributes form
		var replaceForm = document.createElement('div');
		replaceForm.id='replaceIt';
		replaceForm.setAttribute('id','replaceIt');
		replaceForm.className="editLegend";
		replaceForm.style.position='absolute';
		replaceForm.style.top='85px';
		replaceForm.style.left='530px';
		replaceForm.style.width='200px';
		replaceForm.style.height='350px';
		replaceForm.style.overflowX='hidden'; 
		replaceForm.style.overflowY='auto';
		replaceForm.style.paddingBottom='10px';
		replaceForm.style.display='none';
		replaceForm.style.zIndex='5300';

			// write out the first attribute list title
			var replaceTitle = document.createElement('span');
			replaceTitle.style.position='absolute';
			replaceTitle.style.top='5px';
			replaceTitle.style.width='100%';
			replaceTitle.style.textAlign='center';
			var titleText = document.createTextNode('Replace Attributes');
			replaceTitle.appendChild(titleText);
			replaceTitle.className = "editTitle";
			replaceTitle.title='First select an existing attribute you wish to be globally replaced and then select the replacement attribute.';
			replaceForm.appendChild(replaceTitle);

			// write out the first widget title
			var replaceTitle = document.createElement('span');
			replaceTitle.style.position='absolute';
			replaceTitle.style.top='30px';
			replaceTitle.style.left='5px';
			replaceTitle.style.fontSize ='10px';
			replaceTitle.style.width='180px';
			replaceTitle.style.textAlign='left';
			var titleText = document.createTextNode('Pick an existing attribute:');
			replaceTitle.appendChild(titleText);
			replaceTitle.className = "editTitle";
			replaceForm.appendChild(replaceTitle);

			var selectHolder = document.createElement('div');
			selectHolder.id='selectHolder';
			selectHolder.setAttribute('id','selectHolder');
			selectHolder.style.position='absolute';
			selectHolder.style.top= '45px';
			selectHolder.style.left= '5px';
			selectHolder.style.width='200px';
				
				// create the Select object
				var tmp = temp.length;
				var select = document.createElement('select');
				select.className='selectBox';
				select.style.fontSize='9px';
				select.style.verticalAlign='middle';
				select.style.position='absolute';
				select.style.top= '0px';
				select.style.left= '0px';
				select.style.width='200px';
				select.setAttribute('size','8');
				select.setAttribute('width','100');
				select.id='attribsUsed';
				select.setAttribute('id','attribsUsed');
				select.multiple='multiple';
				select.setAttribute('multiple','multiple');

				// now create the Option rows for existing attributes
				//alert('temp = '+temp)
				for (var i=0; i<temp.length ; i++ )
				{		
					var opt = document.createElement('option');
					opt.value=temp[i];
					var optText = document.createTextNode(temp[i]);
					opt.appendChild(optText);
					opt.style.width="100%";
					opt.id='exist:'+i;
					opt.title=temp[i];
					opt.setAttribute('id','exist:'+i);
					select.appendChild(opt);
				}
				selectHolder.appendChild(select);
				replaceForm.appendChild(selectHolder);
						
			// write out the second widget title
			var replaceTitle = document.createElement('span');
			replaceTitle.style.position='absolute';
			replaceTitle.style.top='168px';
			replaceTitle.style.left='5px';
			replaceTitle.style.fontSize ='10px';
			replaceTitle.style.width='180px';
			replaceTitle.style.textAlign='left';
			var titleText = document.createTextNode('Pick a replacement attribute:');
			replaceTitle.appendChild(titleText);
			replaceTitle.className = "editTitle";
			replaceForm.appendChild(replaceTitle);
			
				// create the Select object
				var select2 = document.createElement('select');
				select2.className='selectBox';
				select2.style.fontSize='9px';
				select2.style.verticalAlign='middle';
				select2.style.position='absolute';
				select2.style.top= '182px';
				select2.style.left= '5px';
				select2.style.width='200px';
				select2.setAttribute('size','10');
				select2.setAttribute('width','100');
				select2.id='schemaUsed';
				select2.setAttribute('id','schemaUsed');

				// create the first opriuon as empty or space or nothing
				var opt = document.createElement('option');
				opt.value='';
				var optText = document.createTextNode('nothing');
				opt.appendChild(optText);
				opt.title='this will replace the attribute with nothing i.e. remove it from formula';
				opt.style.width="100%";
				opt.id='replace:'+i;
				opt.setAttribute('id','replace:'+i);
				select2.appendChild(opt);

				// now create the Option rows for existing attributes
				for (var i=0; i<attNames.length ; i++ )
				{		
					var opt = document.createElement('option');
					opt.value=attNames[i];
					var optText = document.createTextNode(attNames[i]);
					opt.appendChild(optText);
					opt.title=attNames[i];
					opt.style.width="100%";
					opt.id='replace:'+i;
					opt.setAttribute('id','replace:'+i);
					select2.appendChild(opt);
				}
				
			replaceForm.appendChild(select2);

			// add the cancel button
			var backButton = document.createElement('input')
			backButton.setAttribute('type','button');
			backButton.value='Cancel';
			backButton.className ='buttonUp';
			backButton.id='canButt';
			backButton.setAttribute('id','canButt')
			backButton.style.fontSize='10px';
			backButton.style.position='absolute';
			backButton.style.bottom='10px';
			backButton.style.right='60px';
			backButton.style.width='50px';
			backButton.style.height='18px';
			bindEvent(backButton, 'click', back, 'false');
			bindEvent(backButton, 'mousedown', buttonDepress, 'false')
		replaceForm.appendChild(backButton);

			// add the continue button
			var contButton = document.createElement('input')
			contButton.setAttribute('type','button');
			contButton.value='Replace';
			contButton.className ='buttonUp';
			contButton.id='repButt';
			contButton.setAttribute('id','repButt')
			contButton.style.fontSize='10px';
			contButton.style.position='absolute';
			contButton.style.bottom='10px';
			contButton.style.right='5px';
			contButton.style.width='50px';
			contButton.style.height='18px';
			bindEvent(contButton, 'click', replaceAtts, 'false');
			bindEvent(contButton, 'mousedown', buttonDepress, 'false')

		replaceForm.appendChild(contButton);
	sldBuilderDiv.appendChild(replaceForm);
}

	// this will generate a temp array of those attributes used in this SLDs rules
	function getAttributesUsed(sqlExp)
	{
	// get a list of the attributes used in the current Sld
		var temp = new Array(); var count = -1;
		for (var i=0; i<sqlExp.length ;i++ )
		{
			//alert(sqlExp[i]);
			// first break sql expression into its logical parts
			var ruleParts = sqlExp[i].split(',')
			for (var j=0; j<ruleParts.length ; j=j+2 )	// ignore the concatination parts
			{
				// break each rule into its three compnents
				var ruleElements = ruleParts[j].split('|')
				
				// strip out any brackets
				ruleElements[0] = ruleElements[0].replace(/\(/g, "");	// ignore right hand side of equations
				ruleElements[0] = ruleElements[0].replace(/\)/g, "");	

				// now replace all +, *, -, / with :
				ruleElements[0] = ruleElements[0].replace(/\*/g, ":");
				ruleElements[0] = ruleElements[0].replace(/\//g, ":");
				ruleElements[0] = ruleElements[0].replace(/\+/g, ":");
				ruleElements[0] = ruleElements[0].replace(/\-/g, ":");
				//alert(ruleElements[0]);

				// split up into individual Element Parts
				var uppercase = ruleElements[0].toUpperCase();
				var elementParts =uppercase.split(":");			
				//alert('num of parts = '+elementParts.length);
				//alert(attNames)
				
				for (var k=0; k<elementParts.length; k++ )
				{
					// check to see if this element is in the SLD schema array
					elementParts[k] = elementParts[k].replace(/\ /g, "");
					loop:
					for(var m=0; m < attNames.length ; m++)
					{
						testName = attNames[m].toUpperCase();
						//attNames[m] = attNames[m].toString();
						
						//alert('compare = >'+elementParts[k]+'<  with  >'+testName+'<');
						if (elementParts[k] == testName)
						{
							//alert(m+" ==== "+attNames[m]);
							// now check if already in the temp array 
							if(temp.length>0)
							{
								for(var n=0 ; n<temp.length; n++)
								{
									if(temp[n] == elementParts[k]) 
									{
										//alert('already caught'); 
										break loop;
									}
								}
								//alert('adding another to temp');
								count++;
								temp[count] = elementParts[k];
								//break loop;						
							}
							else
							{
								//alert('adding first to temp');
								count++;
								temp[count] = elementParts[k];
								//break loop;
							}
						}
					}
				}		
			}
			
		}
		//alert('number in FINAL temp array = '+temp.length)
		
		// lets see what we have decoded from sqlExp
		//for (var n = 0; n<temp.length ; n++){	alert(n+" >> "+temp[n]);}
		return temp;
	}

//-------------------------------------- Rules Editing Form -----------------------------------------------
//	Build the Rules Editing form
function buildEditorForm(sldBuilderDiv, row)
{
//----------------- now add the rules holder Div ---------------------
	checkRemoveObject('rulesDiv');
	// build the Rule header information Table
	var rules = document.createElement('div');
	rules.id='rulesDiv';
	rules.setAttribute('id','rulesDiv');
	rules.className='rules';
	rules.style.position='absolute';
	rules.style.top='110px'; 
	rules.style.left='20px';
	rules.style.width='500px'; 
	rules.style.height='340px';
	//rules.style.border='1px solid red';

// ------------------- build the Rule header information holding Table -------------
		checkRemoveObject('ruleTable');
		var ruleTable = document.createElement('table');
		ruleTable.id='ruleTable';
		ruleTable.style.position='absolute';
		ruleTable.style.top='5px'; 
		ruleTable.style.left='0px';
		ruleTable.style.width='500px'; 
		ruleTable.style.height='20px';
		ruleTable.setAttribute('id','ruleTable');
		//ruleTable.setAttribute('border','1');
		ruleTable.className='ruleTable';
		var ruleTableBody = document.createElement('tbody');

		// ---------------- now add the rule header information ---------------------
		var ruleHeadRow = document.createElement('tr');
			
			// create the Name editing fields
			var headCell1 = document.createElement('td');
			headCell1.className="headTitleCell";
			headCell1.style.width='45px';
			headCell1.style.height='15px';
			var cell1Text = document.createTextNode('Name: *');
			headCell1.appendChild(cell1Text);
			ruleHeadRow.appendChild(headCell1);

			var headCell2 = document.createElement('td');
			headCell2.className="ruleDataCell";
			headCell2.style.width='165px';
			headCell2.style.height='15px';
			var ruleCell2Edit1 = document.createElement('Input');
			ruleCell2Edit1.className='headDataCellEdit';
			ruleCell2Edit1.style.width='165px';
			ruleCell2Edit1.value = RuleName[row];		
			ruleCell2Edit1.id = 'nameNo'; 
			ruleCell2Edit1.setAttribute("id", 'nameNo');
			//ruleCell2Edit1.style.zIndex='202';
			ruleCell2Edit1.title='The Name is used in the Legend to label the Rule';
			bindEvent(ruleCell2Edit1, 'change', saveRuleName, 'false');
			headCell2.appendChild(ruleCell2Edit1);
			ruleHeadRow.appendChild(headCell2);
			
			// create the Title editing fields
			var headCell1 = document.createElement('td');
			headCell1.className="headTitleCell";
			headCell1.style.width='45px';
			var cell1Text = document.createTextNode('Title: ');
			headCell1.appendChild(cell1Text);
			ruleHeadRow.appendChild(headCell1);

			var headCell2 = document.createElement('td');
			headCell2.className="ruleDataCell";
			headCell2.style.width='165px';
			headCell2.style.height='15px'
			var ruleCell2Edit1 = document.createElement('Input');
			ruleCell2Edit1.className='headDataCellEdit';
			ruleCell2Edit1.style.width='165px';
			ruleCell2Edit1.value = RuleTitle[row];		
			ruleCell2Edit1.id = 'titleNo'; 
			ruleCell2Edit1.setAttribute("id", 'titleNo');
			//ruleCell2Edit1.style.zIndex='202';
			ruleCell2Edit1.title='The Title can contain anything and is not used in the Legend display'
			bindEvent(ruleCell2Edit1, 'change', saveRuleTitle, 'false');
			headCell2.appendChild(ruleCell2Edit1);
			ruleHeadRow.appendChild(headCell2);
			
			// append to table
			ruleTableBody.appendChild(ruleHeadRow);
			ruleTable.appendChild(ruleTableBody);
		
		// append to section
		rules.appendChild(ruleTable);

// ------------------ now add the Abstract as a sigle row --------------------
		checkRemoveObject('abstractTable')
		// build the Rule header information Table
		var ruleTable = document.createElement('table');
		ruleTable.id='abstractTable';
		ruleTable.setAttribute('id','abstractTable');
		ruleTable.setAttribute('border','0');
		ruleTable.style.position='absolute';
		ruleTable.style.top='30px'; 
		ruleTable.style.left='0px';
		ruleTable.style.width='500px' ;
		ruleTable.style.height='auto';
		//ruleTable.setAttribute('border','1');
		ruleTable.className='abstractTable';
		var ruleTableBody = document.createElement('tbody');
		
		var abstractRow = document.createElement('tr');
			var headCell1 = document.createElement('td');
			headCell1.className="ruleTitleCell";
			headCell1.style.width='62px';
			var cell1Text = document.createTextNode('Abstract:');
			headCell1.appendChild(cell1Text);
			abstractRow.appendChild(headCell1);

			var absCell = document.createElement('td');
			absCell.className="abstractDataCell";
			absCell.style.width='415px';
			var abstractCell2Edit1 = document.createElement('Input');
			abstractCell2Edit1.className='headDataCellEdit';
			//abstractCell2Edit1.className='abstractDataCellEditInput';
			abstractCell2Edit1.style.width='410px';
			if(RuleAbstract[row] != ''){	abstractCell2Edit1.value = RuleAbstract[row];}
			else {abstractCell2Edit1.value =''}
			//alert('>'+RuleAbstract[row]+'<');
	//'\n                                                                 '; // FF TextArea workaround
			abstractCell2Edit1.id = 'absNo'; 
			abstractCell2Edit1.setAttribute("id", 'absNo');
			//var rowsInTextBox = 3
			//if (browser == 'firefox' && version == '2')
			//{	rowsInTectBox = 2;	}		
			//abstractCell2Edit1.setAttribute("rows", rowsInTextBox);
			abstractCell2Edit1.title='The Abstract contains more detailed information about each Rule and is shown as a tooltip when mousing over the Name cell in the runtime legend';
			bindEvent(abstractCell2Edit1, 'change', saveAbstract, 'false');
			absCell.appendChild(abstractCell2Edit1);
			abstractRow.appendChild(absCell);



			// add the abstract editor button
			var innerRowCell = document.createElement('td');
				var popupButt = document.createElement('div');		
				popupButt.style.width='20px';
				popupButt.style.height='18px';
				popupButt.title='click here for the larger abstract editor form'
				popupButt.style.cursor='pointer';
					
					// add the internal image
					var symbolImg = document.createElement('img');
					symbolImg.src='images/world_edit.png';
					symbolImg.id= 'abstract:absNo';
					symbolImg.setAttribute('id','abstract:absNo');
					bindEvent(symbolImg, 'click', popupAbstractEditor, 'false');
					
				popupButt.appendChild(symbolImg);
			innerRowCell.appendChild(popupButt);
			abstractRow.appendChild(innerRowCell);
		//setOpacity(symbolImg, 50)

		//abstractRow.appendChild(abstractRow);
		//absTable.appendChild(absTableBody);
		//sldDiv.appendChild(absTable);

		ruleTableBody.appendChild(abstractRow);
		ruleTable.appendChild(ruleTableBody);
	
	rules.appendChild(ruleTable);
		
// ---------------- build the Rule Logic editing Table --------------
		checkRemoveObject('ruleLogic');
		var ruleLogic = document.createElement('table');
		ruleLogic.id='ruleLogic';
		//ruleLogic.setAttribute('border','1')
		ruleLogic.style.borderCollapse='collapse';
		ruleLogic.setAttribute('id','ruleLogic');
		ruleLogic.className='ruleLogic';
		ruleLogic.style.position='absolute';
		ruleLogic.style.top='60px'; 
		ruleLogic.style.left='5px';
		ruleLogic.style.height='30px'; 
		ruleLogic.style.width='485px';
		ruleLogic.setAttribute('border','0');
		var ruleLogicBody = document.createElement('tbody');

		// create the header row of titles abover the boxes
		var ruleLogicRow = document.createElement('tr');
		ruleLogicRow.style.height='15px';

			// Attribute Name
			var logicCell1 = document.createElement('td');
			logicCell1.className="ruleTitleCell";
			logicCell1.style.width='250px';
			logicCell1.style.height='12px';
			//logicCell1.style.border='1px solid blue';
			var cell1Text = document.createTextNode('Attribute Name: *');
			logicCell1.appendChild(cell1Text);
			logicCell1.style.verticalAlign='bottom';
			ruleLogicRow.appendChild(logicCell1);

			// Rule Elements Controls
			var logicCell1 = document.createElement('td');
			logicCell1.className="ruleTitleCell";
			logicCell1.style.width='200px';
			logicCell1.style.height='12px';
			//logicCell1.style.border='1px solid blue';
			var cell1Text = document.createTextNode('Rule Element Controls: ');
			logicCell1.appendChild(cell1Text);
			logicCell1.style.verticalAlign='bottom';
			ruleLogicRow.appendChild(logicCell1);
			
		ruleLogicBody.appendChild(ruleLogicRow);

		// ---------------- create the select box for Attribute Names -----------aaaa
		var ruleLogicRow = document.createElement('tr');
		ruleLogicRow.style.height='22px';

		// get the attribute metadata from drapelist controlfile  if supplied
		//if(drapes != 'nuservbeta' && drapes != 'numapsService' && drapes != 'numaps' && drapes != 'nuserv' && drapes != '')
		//{	getAttribsForDrape(currentSld);	}
		
		// get attribute names from WFS service
		ajaxRequest = getAttributeSchema(meshBlocksBase, layerName);
		//alert(ajaxRequest.status)	
		
		// get all attributes from XML file into arrays
		buildAttributeArrays(ajaxRequest);
		
		//alert(attNames.length)
		// create the attribute picklist
		createAttribPicker(ruleLogicRow);
	
		// ---------------- create the Buttons Table Cell ---------------------
		var logicCell1 = document.createElement('td');
			//logicCell1.style.border='1px solid red';
			var innerTable = document.createElement('table')
				var innerTableBody = document.createElement('tbody')
				var innerRow = document.createElement('tr')
			
					// ---------------- create the Insert button YYYY ---------------------
					var innerRowCell = document.createElement('td')
					innerRowCell.style.width='20%'
					//innerRowCell.style.height='100%';
					//innerRowCell.style.border='1px solid blue';
					var insertButt = document.createElement('input');
					insertButt.id='insert';
					insertButt.setAttribute('id','insert')
					insertButt.className ='buttonUp';
					insertButt.value='Insert';
					insertButt.style.width='100%';
					insertButt.title='Insert a new empty rule condition after the currently selected condition'
					bindEvent(insertButt, 'mousedown', buttonDepress, 'false')
					bindEvent(insertButt, 'click', insertCond, 'false')
					innerRowCell.appendChild(insertButt)
					innerRow.appendChild(innerRowCell);

					// ---------------- create the Delete button YYYY ---------------------
					var innerRowCell = document.createElement('td')
					innerRowCell.style.width='20%'
					//innerRowCell.style.height='100%';
					//innerRowCell.style.border='1px solid blue';
					var delButt = document.createElement('input');
					delButt.id='delete';
					delButt.setAttribute('id','delete')
					delButt.className ='buttonUp';
					delButt.value='Delete';
					delButt.style.width='100%';
					delButt.title='Delete the currently selected condition';
					bindEvent(delButt, 'mousedown', buttonDepress, 'false')
					bindEvent(delButt, 'click', deleteCond, 'false')
					innerRowCell.appendChild(delButt)
					innerRow.appendChild(innerRowCell);

					// ---------------- create the Clear button YYYY ---------------------
					var innerRowCell = document.createElement('td')
					innerRowCell.style.width='20%'
					//innerRowCell.style.height='100%';
					//innerRowCell.style.border='1px solid blue';
					var clearButt = document.createElement('input');
					clearButt.id='clear';
					clearButt.setAttribute('id','clear')
					clearButt.className ='buttonUp';
					clearButt.value='Clear';
					clearButt.style.width='100%';
					clearButt.title='Clear out all the components of this rule condition and leave this as the current condition';
					bindEvent(clearButt, 'mousedown', buttonDepress, 'false')
					bindEvent(clearButt, 'click', clearCond, 'false')
					innerRowCell.appendChild(clearButt)
					innerRow.appendChild(innerRowCell);

					// ---------------- create the Clone button YYYY ---------------------
					var innerRowCell = document.createElement('td')
					innerRowCell.style.width='20%'
					//innerRowCell.style.height='100%';
					//innerRowCell.style.border='1px solid blue';
					var clearButt = document.createElement('input');
					clearButt.id='clone';
					clearButt.setAttribute('id','clone')
					clearButt.className ='buttonUp';
					clearButt.value='Clone';
					clearButt.style.width='100%';
					clearButt.title='Create a duplicate copy of this rule condition and make it the current condition ';
					bindEvent(clearButt, 'mousedown', buttonDepress, 'false')
					bindEvent(clearButt, 'click', cloneCond, 'false')
					innerRowCell.appendChild(clearButt)
					innerRow.appendChild(innerRowCell);

					// ---------------- create the Save button YYYY ---------------------
					var innerRowCell = document.createElement('td')
					innerRowCell.style.width='20%'
					//innerRowCell.style.height='100%';
					//innerRowCell.style.border='1px solid blue';
					var saveButt = document.createElement('input');
					saveButt.id='save';
					saveButt.setAttribute('id','save')
					saveButt.className ='buttonUp';
					saveButt.value='Save';
					saveButt.style.color='#000000';
					saveButt.style.width='100%';
					saveButt.title='Save these rule conditions'
					bindEvent(saveButt, 'mousedown', buttonDepress, 'false')
					bindEvent(saveButt, 'click', saveCond, 'false')
					innerRowCell.appendChild(saveButt)
					innerRow.appendChild(innerRowCell);

				innerTableBody.appendChild(innerRow);
				innerTable.appendChild(innerTableBody)

			logicCell1.appendChild(innerTable)
			ruleLogicRow.appendChild(logicCell1)
	ruleLogicBody.appendChild(ruleLogicRow);
	ruleLogic.appendChild(ruleLogicBody);
	rules.appendChild(ruleLogic);

	// copy sqlExp into sqlExpTemp array
	//alert('num in sqlExp = '+sqlExp.length)
	for (var i=0; i<sqlExp.length; i++ )
	{		sqlExpTemp[i]=sqlExp[i]	}
	// alert(sqlExpTemp)
	// Load the filter editor
	buildFilterEditor(row, rules)

	// ------------- create the scale rules updating section -------------------
	var symbol = document.createElement('div');
	symbol.id='symbol';
	symbol.setAttribute('id','symbol');
	symbol.className="symbol";
	//symbol.style.border='1px solid cyan';
	symbol.style.height='20px';
	symbol.style.width='500px';
	
	// Set up the symbol editing header Table
	var symbolTab = document.createElement('table');
		symbolTab.className="symbolTableHeader";
		//symbolTab.setAttribute('border','1')
		symbolTab.style.position='absolute'; 
		symbolTab.style.top='220px'; 
		symbolTab.style.left='5px'
		symbolTab.style.height='20px'; 
		symbolTab.style.width='490px';
		//symbolTab.setAttribute('border','0');
		var symbolTableBody = document.createElement('tbody');
		//symbolTableBody.className='symbolTableBody'; 
		
		// build the Scale threshold row
		var symbolRow01 = document.createElement('tr');
			
			// create the MinScale editing fields
			var headCell1 = document.createElement('td');
			headCell1.className="symbolTitleCell";
			headCell1.style.width='60px';
			headCell1.style.height='15px';
			var cell1Text = document.createTextNode('MinScale 1:');
			headCell1.appendChild(cell1Text)
			symbolRow01.appendChild(headCell1)

			var headCell2 = document.createElement('td');
			headCell2.className="symbolTitleCell";
			headCell2.style.width='100px';
			headCell2.style.height='15px'
				var ruleCell2Edit1 = document.createElement('Input');
				ruleCell2Edit1.className='symbolCellInput';
				ruleCell2Edit1.value = ruleMinScale[row];		
				ruleCell2Edit1.id = 'minScale'; 
				ruleCell2Edit1.setAttribute("id", 'minScale');
				ruleCell2Edit1.style.width='100px';
				ruleCell2Edit1.title='Enter/Update the Minimum display scale denominator for this Rule';
				bindEvent(ruleCell2Edit1, 'change', saveScale, 'false');
				bindEvent(ruleCell2Edit1, 'click', clearInput, 'false');
				headCell2.appendChild(ruleCell2Edit1)
			symbolRow01.appendChild(headCell2)
			
			// add the apply to all checkbox
			showApplyAll(symbolRow01, 'minScale');

			// create the MaxScale editing fields
			var headCell1 = document.createElement('td');
			headCell1.className="symbolTitleCell";
			headCell1.style.width='60px';
			var cell1Text = document.createTextNode('MaxScale 1:');
			headCell1.appendChild(cell1Text)
			symbolRow01.appendChild(headCell1)

			var headCell2 = document.createElement('td');
			headCell2.className="symbolTitleCell";
			headCell2.style.width='100px';
			headCell2.style.height='15px';
				var ruleCell2Edit1 = document.createElement('Input');
				ruleCell2Edit1.className='symbolCellInput'
				ruleCell2Edit1.value = ruleMaxScale[row];		
				ruleCell2Edit1.id = 'maxScale'; 
				ruleCell2Edit1.setAttribute("id", 'maxScale');
				ruleCell2Edit1.style.width='100px';
				ruleCell2Edit1.title='Enter/Update the Maximum display scale denominator for this Rule'
				bindEvent(ruleCell2Edit1, 'change', saveScale, 'false');
				bindEvent(ruleCell2Edit1, 'click', clearInput, 'false');
				headCell2.appendChild(ruleCell2Edit1)
				symbolRow01.appendChild(headCell2)
			
			// add the apply to all checkbox
			showApplyAll(symbolRow01, 'maxScale');

		symbolTableBody.appendChild(symbolRow01);
	symbolTab.appendChild(symbolTableBody)
	symbol.appendChild(symbolTab);
rules.appendChild(symbol);

	// ------------- create the polygon symbolisation rendering rules section ---------------
	var symbol = document.createElement('div');
	symbol.id='symbol';
	symbol.setAttribute('id','symbol');
	symbol.className="symbol";
	//symbol.style.border='1px solid cyan';
	//symbol.style.height='100%';
	
	// Set up the symbol editing header Table
	var symbolTab = document.createElement('table');
		symbolTab.className="symbolTableHeader";
		//symbolTab.setAttribute('border','1')
		symbolTab.style.position='absolute'; 
		symbolTab.style.top='245px'; 
		symbolTab.style.left='5px'
		symbolTab.style.height='15px'; 
		symbolTab.style.width='470px';
		//symbolTab.setAttribute('border','0');
		//symbolTab.style.borderTop = '1px groove gray';
		var symbolTableBody = document.createElement('tbody');
		//symbolTableBody.className='symbolTableBody'; 
		var symbolRow01 = document.createElement('tr')
		
		// add the table heading cell
		var symbolTabHead01 = document.createElement('td')
		symbolTabHead01.className = 'symbolTitleCell';
		symbolTabHead01.style.width='245px';
		symbolTabHead01.style.height='15px';
		symbolTabHead01.style.textAlign='center';
		var cell1Text = document.createTextNode('Area Infill');
		symbolTabHead01.appendChild(cell1Text)
		symbolRow01.appendChild(symbolTabHead01);
		symbolTableBody.appendChild(symbolRow01);

		// add the table heading cell
		var symbolTabHead01 = document.createElement('td')
		symbolTabHead01.className = 'symbolTitleCell';
		symbolTabHead01.style.width='245px';
		symbolTabHead01.style.height='15px';
		symbolTabHead01.style.textAlign='center';
		var cell1Text = document.createTextNode('Area Border');
		symbolTabHead01.appendChild(cell1Text)
		symbolRow01.appendChild(symbolTabHead01);
		symbolTableBody.appendChild(symbolRow01);
	
		symbolTab.appendChild(symbolTableBody);

	symbol.appendChild(symbolTab);


	//----------------- Set up the symbol editing Table --------------
	var symbolTab = document.createElement('table');
		symbolTab.className="symbolTable";
		symbolTab.style.position='absolute'; 
		symbolTab.style.top='260px'; 
		symbolTab.style.left='5px';
		symbolTab.style.width='450px';
		symbolTab.style.height='15px';
		var symbolTableBody = document.createElement('tbody');

		// add a table row
		var symbolRow01 = document.createElement('tr')
		
		// add COLOR title cell for Colour Fill
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
			symbolCell.style.width='20%';
			symbolCell.style.height='15px';
			var symbolText = document.createTextNode("Colour: ");
			symbolCell.appendChild(symbolText);
			symbolRow01.appendChild(symbolCell);
			
		// add polygon cell for Filling
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolCellInput';
			symbolCell.style.width='15%';
			symbolCell.style.height='15px';
				
			// insert an internal Div for rendering	
				var divCell = document.createElement('input')
				divCell.className='symbolCell';
				divCell.style.height='13px';
				divCell.style.width='95%';
				divCell.id='editFill';
				divCell.style.fontSize='10px';
				divCell.style.textAlign='center';
				divCell.setAttribute('id','editFill');
				//alert('fill color in SLD = '+fillColor[row])
				divCell.style.backgroundColor=fillColor[row];
				
				// enter the color hex code into Input box
				divCell.value = '';
				if(fillColor[row] && fillColor[row] != 'transparent')
				{
					var code = fillColor[row].split('#');
					divCell.value = code[1];
				}
				
				bindEvent(divCell, 'change', getHexCode, 'false');
				symbolCell.appendChild(divCell);
			symbolRow01.appendChild(symbolCell);
			
			// add the pick tool cell for Fill
			var symbolTool = document.createElement('td')
			symbolTool.className = 'symbolTitleCell';
			symbolTool.style.width='3%';
				var symbolImg = document.createElement('img');
				symbolImg.src='images/palette.png';
				symbolImg.id='fillPalette';
				symbolImg.setAttribute('id','fillPalette');
				symbolImg.style.cursor='pointer';
				fillTargetId = 'fillPalette';
				// onclick launch the colour palette
				bindEvent(symbolImg, 'click', colourPicker, 'false');
				symbolTool.appendChild(symbolImg);
			symbolRow01.appendChild(symbolTool);
			
		
			// add the apply to all checkbox
			showApplyAll(symbolRow01, 'editFill');
		
		
		// add a color cell for Lines
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
			symbolCell.style.width='20%';
			var symbolText = document.createTextNode("Colour: ");
			symbolCell.appendChild(symbolText);
			symbolRow01.appendChild(symbolCell);

		// add polygon cell for Lines
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolCellInput';
			symbolCell.style.width='15%';
			symbolCell.style.height='15px';
				// insert an internal Div for rendering
				var divCell = document.createElement('input')
				divCell.className='symbolCell';
				divCell.style.height='13px';
				divCell.style.width='95%';
				divCell.id='editLine';
				divCell.style.fontSize='10px';
				divCell.style.textAlign='center';
				divCell.setAttribute('id','editLine');
				divCell.style.backgroundColor=lineColor[row];
				
				// enter the color hex code into Input box
				divCell.value = '';
				if(lineColor[row] && lineColor[row] != 'transparent')
				{
					var code = lineColor[row].split('#');
					divCell.value = code[1];
				}
				
				bindEvent(divCell, 'change', getHexCode, 'false');
				symbolCell.appendChild(divCell);
			symbolRow01.appendChild(symbolCell);
			
		// add the pick tool cell
			var symbolTool = document.createElement('td')
			symbolTool.className = 'symbolTitleCell';
			symbolTool.style.width='3%';
			symbolTool.style.height='15px';
				var symbolImg = document.createElement('img');
				symbolImg.src='images/palette.png';
				symbolImg.id='linePalette';
				symbolImg.setAttribute('id','linePalette');
				symbolImg.style.cursor='pointer';
				fillTargetId = 'linePalette';
				// onclick launch the colour palette
				bindEvent(symbolImg, 'click', colourPicker, 'false');
				symbolTool.appendChild(symbolImg);
			symbolRow01.appendChild(symbolTool);

			// add the apply to all checkbox
			showApplyAll(symbolRow01, 'editLine');

		symbolTableBody.appendChild(symbolRow01)

// ---------------------- add the next table row -------------------------
		var symbolRow01 = document.createElement('tr')
		
		// add PATTERN cell for Fill
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
			symbolCell.style.height='15px';
			symbolCell.style.width='20%';
			//symbolCell.style.width='50px';
			var symbolText = document.createTextNode("Pattern: ");
			symbolCell.appendChild(symbolText);
			symbolRow01.appendChild(symbolCell);
			
		// add a polygon pattern cell
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolCellInput';
			symbolCell.style.width='15%';
			symbolCell.style.height='15px';
				// insert an internal Div for rendering
				var divCell = document.createElement('div')
				divCell.className='symbolCell';
				divCell.style.height='13px';
				divCell.style.width='100%';
				divCell.id='editPattern';
				divCell.setAttribute('id','editPattern');
				//alert('fill color in SLD = '+fillColor[row])
				divCell.style.backgroundImage = "url("+fillPattern[row]+")";
				symbolCell.appendChild(divCell);
			symbolRow01.appendChild(symbolCell);

		// add pattern select tool for Fill
			var symbolTool = document.createElement('td')
			symbolTool.className = 'symbolTitleCell';
			symbolCell.style.width='10%';
			symbolCell.style.height='15px';
			//symbolTool.style.height='18px';
			//symbolTool.style.width='100px';
			// create a select box here for all fill patterns
			symbolTool.id='patternSel'
			symbolTool.setAttribute('id','patternSel')
				
				var symbolImg = document.createElement('img');
				symbolImg.src='images/shading.png';
				symbolImg.id='fillPat';
				symbolImg.setAttribute('id','fillPat');
				symbolImg.style.cursor='pointer';
				// onclick launch the pattern picker
				bindEvent(symbolImg, 'click', imagePicka, 'false');
				symbolTool.appendChild(symbolImg);
			symbolRow01.appendChild(symbolTool);

			// add the apply to all checkbox
			showApplyAll(symbolRow01, 'editPattern');
			
			// add Thickness title cell for Lines
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
			var symbolText = document.createTextNode("Thickness: ");
			symbolCell.appendChild(symbolText);
			symbolRow01.appendChild(symbolCell);

			// add thickness input cell for Lines
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
				var select = document.createElement('select');
				select.className='symbolSelectBox';
				select.style.width='100%';
				select.style.height='18px';	
				select.id='bordThick';
				select.setAttribute('id','bordThick');
				
				// now create the Option rows
				var num = lineWeights.length;
				for (var i=0; i<num ; i++ )
				{
					var opt = document.createElement('option');
					opt.value=lineWeights[i];
					var optText = document.createTextNode(lineWeights[i]);
					opt.appendChild(optText);
					opt.title = optionTitle[i];
					select.appendChild(opt)
				}
				select.selectedIndex = lineWeight[row];
				bindEvent(select, 'change', getNewValue, 'false')
				symbolCell.appendChild(select);

			symbolRow01.appendChild(symbolCell);
			
			var symbolTool = document.createElement('td')
			symbolTool.className = 'symbolTitleCell';
			symbolRow01.appendChild(symbolTool);
			
			// add the apply to all checkbox
			showApplyAll(symbolRow01, 'bordThick');
		
		symbolTableBody.appendChild(symbolRow01)

	// ------------------- add a table row
		var symbolRow01 = document.createElement('tr')
		
			// add Title cell for Opacity for Fill
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
			//symbolCell.style.width='30px';
			var symbolText = document.createTextNode("Opacity: ");
			symbolCell.appendChild(symbolText);
			symbolRow01.appendChild(symbolCell);
			
			// add input cell for Fill Opacity
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
			symbolCell.style.height='15px';
			//symbolCell.style.width='96px';
				// create the Select object
				var select = document.createElement('select');
				select.className='symbolSelectBox';
				select.style.width='100%';
				select.style.height='18px';
				select.id='fillOp';
				select.setAttribute('id','fillOp');
				// now create the Option rows
				var num = opacityOps.length;
				for (var i=0; i<num ; i++ )
				{
					var opt = document.createElement('option');
					opt.value=opacityOps[i];
					var optText = document.createTextNode(opacityOps[i]);
					opt.appendChild(optText);
					opt.title = optionTitle[i];
					select.appendChild(opt)
				}
				// calculate rwo element as 10 times the opacity number
				select.selectedIndex = 10 - (fillOpacity[row] * 10);
				bindEvent(select, 'change', getNewValue, 'false')
				symbolCell.appendChild(select);
			symbolRow01.appendChild(symbolCell);
			
			// add select box for Fill opacity
			var symbolTool = document.createElement('td')
			symbolTool.className = 'symbolTitleCell';
			//symbolTool.style.width='80px';
			symbolRow01.appendChild(symbolTool);

			// add the apply to all checkbox
			showApplyAll(symbolRow01, 'fillOp');
			
			// add title cell for Line Opacity
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
			//symbolCell.style.width='30px';
			var symbolText = document.createTextNode("Opacity: ");
			symbolCell.appendChild(symbolText);
			symbolRow01.appendChild(symbolCell);

			// add Opacity input cell for Lines
			var symbolCell = document.createElement('td')
			symbolCell.className = 'symbolTitleCell';
				// insert an internal Input Cell for entering a Line opacity
				var select = document.createElement('select');
				select.className='symbolSelectBox';
				select.style.width='100%';
				select.style.height='18px';	
				select.id='bordOp';
				select.setAttribute('id','bordOp');
				// now create the Option rows
				var num = opacityOps.length;
				for (var i=0; i<num ; i++ )
				{
					var opt = document.createElement('option');
					opt.value = opacityOps[i];
					var optText = document.createTextNode(opacityOps[i]);
					opt.appendChild(optText);
					opt.title = optionTitle[i];
					select.appendChild(opt)
				}
				// calculate rwo element as 10 times the opacity number
				select.selectedIndex = 10 - (lineOpacity[row] * 10);
				bindEvent(select, 'change', getNewValue, 'false')
				symbolCell.appendChild(select);
			symbolRow01.appendChild(symbolCell);
			
			// add an empty table cell
			var symbolTool = document.createElement('td')
			symbolTool.className = 'symbolTitleCell';	
			symbolRow01.appendChild(symbolTool);
		symbolTableBody.appendChild(symbolRow01)
		
		symbolTab.appendChild(symbolTableBody);

		// add the apply to all checkbox
		showApplyAll(symbolRow01, 'bordOp');

	symbol.appendChild(symbolTab);
	rules.appendChild(symbol);

sldBuilderDiv.appendChild(rules);
// now set the first row as active
lastCell =  "sql1:0";
document.getElementById('sql1:0').className='selectedItem';
document.getElementById('sql2:0').className='selectedItem';
document.getElementById('sql3:0').className='selectedItem';
document.getElementById('sql4:0').className='selectedItem';
//document.getElementById('sql1:0').style.border='3px solid red';
//document.getElementById('sql2:0').style.border='3px solid red';
//document.getElementById('sql3:0').style.border='3px solid red';
//document.getElementById('sql4:0').style.border='3px solid red';
setOpacity(	document.getElementById('sql5:0'), 100);

ruleLogic.focus();
}


function showApplyAll(parentObj, target)
{
	// parentObj is the object that this control will be added to
	// target is the id of the this control
	
	// ---------------- create the applyAll button  ---------------------
	var innerRowCell = document.createElement('td');
	innerRowCell.style.height='16px';
	var saveButt = document.createElement('div');
	saveButt.className ='buttonUp';
		var titleText = document.createTextNode('All');
		saveButt.appendChild(titleText);
	saveButt.style.width='20px';
	saveButt.id = target+'All'
	saveButt.setAttribute('id', target+'All');
	saveButt.className ='buttonUp';
	//saveButt.style.fontSize='9px';
	//saveButt.value='Up';
	saveButt.title='Click here to apply this to all Rules';
	bindEvent(saveButt, 'mousedown', buttonDepress, 'false');
	bindEvent(saveButt, 'click', applyAllRules, 'false');
	innerRowCell.appendChild(saveButt);
	parentObj.appendChild(innerRowCell);
}

// --------------- build the Rule Logic editing Table -----------------
function buildFilterEditor(row, rules)
{
	//alert ("row number = "+row)
	//alert("sqlExp input to buildFilterEditor ************** = \n"+sqlExp[row])
	
	checkRemoveObject('ruleCompositeDiv')
	
	rulesDiv = document.createElement('form')
	rulesDiv.id='ruleCompositeDiv';
	rulesDiv.setAttribute('id','ruleCompositeDiv');
	rulesDiv.className='ruleCompBody';
	rulesDiv.style.position='absolute'; 
	rulesDiv.style.top='105px'; 
	rulesDiv.style.left='5px'; 
	rulesDiv.style.width='490px';
	rulesDiv.style.height='110px';

	ruleLogic = document.createElement('table');
	ruleLogic.id='ruleComposite';
	ruleLogic.style.height = '50px';
	ruleLogic.setAttribute('id','ruleComposite');
	//ruleLogic.setAttribute('border','0')
	ruleLogic.style.borderCollapse='collapse';
	ruleLogic.className='ruleComposite';
	ruleLogic.style.maxHeight='90px';
	ruleLogic.style.width='490px';
	var ruleLogicBody = document.createElement('tbody')
	
	// find out how many filter parts we have
	sqlExpressions = sqlExpTemp[row].split(",");
	// make sure that the last concatination element is set to semicolon
	sqlExpressions[sqlExpressions.length]=' ';
	var no = sqlExpressions.length;
	
	//alert("number of comma sep parts = "+no)
	// debug report
	//for (var z=0; z<no ; z++ )
	//{
	//	alert(sqlExpressions[z])
	//}
	//alert ('done')

	// create a row for each part of the Filter
	for (var n=0; n < no ; n++ )
	{		
		var ruleLogicRow = document.createElement('tr');
		//ruleLogicRow.id='ruleRow:'+n;
		//ruleLogicRow.setAttribute('id','ruleRow:'+n);
		
			// escape any + or - sign is sqlExp
			//sqlExpressions[n] = sqlExpressions[n].replace(/*plus*/g, "+");
			//sqlExpressions[n] = sqlExpressions[n].replace(/*minus*/g, "-");

			// for any array element that holds the concatination part of expressions
			if (n>0 && !evenCheck(n))
			{	
				// selectEle already exists this just sets the appropriate option
				for (var z=0; z < optionAlias3.length; z++ )
				{	
					//alert(optionAlias3[z]+" compared with "+sqlExpressions[n])
					if (optionAlias3[z] == sqlExpressions[n])	
					{	selectEle.selectedIndex = z; break;}
					else 
					{	selectEle.selectedIndex=0}
				}
				//emptyCell1.value = sqlExpressions[n];	
			}
			else
			// build and populate the condition table
			{
				// break up condition into its parts using the space char as delimiter
				var sqlParts = []; var np = 0;
				if(no > 0)
				{	sqlParts = sqlExpressions[n].split("|"); 
					np = sqlParts.length;
				}
				//alert(" 0 = "+sqlParts[0])
				//alert("operator = "+sqlParts[1])
				//alert("value = "+sqlParts[2])
			
			// --------------------- create the attributes cell	----------------------			xxxxxxx
			var logicCell = document.createElement('td');
				logicCell.style.width = '215px';
				logicCell.style.height = '15px';
				//logicCell.style.border='1px solid gray'
					var logicCell1 = document.createElement('input');
					logicCell1.style.width = '215px';
					logicCell1.style.height = '15px';
					logicCell1.id = 'sql1:'+n;
					logicCell1.setAttribute('id','sql1:'+n)
					//logicCell1.className='ruleCompositeCell';
					logicCell1.className='unselectedItem';
					logicCell1.style.width='215px';
					//logicCell1.style.height='14px';
					logicCell1.value = sqlParts[0];
					logicCell1.title = 'This is a free text input field. You can drop attributes into this field by picking off the list above. Place any attribute-based formula inside round brackets.'
					bindEvent(logicCell1, 'focus', editCell, 'false')
					bindEvent(logicCell1, 'change', updateArray, 'false')
				logicCell.appendChild(logicCell1);
			ruleLogicRow.appendChild(logicCell);

			// --------------------- create an expand-popup cell ---------------zzzzzzz-
			var innerRowCell = document.createElement('td');
				var popupButt = document.createElement('div');		
				popupButt.style.width='20px';
				popupButt.style.height='18px';
				popupButt.title='click here for the larger rule editor form'
				popupButt.style.cursor='pointer';
				
					// add the internal image
					var symbolImg = document.createElement('img');
					symbolImg.src='images/world_edit.png';
					symbolImg.id= 'sql5:'+n;
					symbolImg.setAttribute('id','sql5:'+n);
					bindEvent(symbolImg, 'click', popupRulesEditor, 'false');
				
				popupButt.appendChild(symbolImg);
			innerRowCell.appendChild(popupButt);
		  ruleLogicRow.appendChild(innerRowCell);
		  setOpacity(symbolImg, 50)

			// ------------------ create the Logical operators picklist ------------------
			var logicCell1 = document.createElement('td');
				logicCell1.style.width  = '55px';
				logicCell1.style.height = '15px';
				
				// create the Select object
					var select = document.createElement('select');
					select.className='selectBox';
					select.id = 'sql2:'+n;
					select.setAttribute('id','sql2:'+n)
					select.style.width='100%';
					
					// now create the Option rows
					var num = optionDesc.length;
					for (var i=0; i<num ; i++ )
					{
						var opt = document.createElement('option');
						opt.value=optionAlias[i];
						var optText = document.createTextNode(optionDesc[i]);
						opt.appendChild(optText);
						opt.title = optionTitle[i];
						select.appendChild(opt)
					}

					// set select list option to the current value
					for (var z=0; z < optionAlias.length; z++ )
					{	if (optionAlias[z] == sqlParts[1] || optionValues[z] == sqlParts[1])	{select.selectedIndex = z; break;}
						else {select.selectedIndex=0}
					}
					select.title = 'select the logical operator from this picklist';
					bindEvent(select, 'change', updateArray, 'false')
					bindEvent(select, 'focus', editCell, 'false')
				logicCell1.appendChild(select);
			ruleLogicRow.appendChild(logicCell1)

					
			// ------------------- create the value data entry cell ------------------
			var logicCell = document.createElement('td');
				logicCell.style.width = '65px';
				logicCell.style.height = '15px';
				//logicCell.style.border='1px solid gray'
					var logicCell1 = document.createElement('input')
					logicCell1.id = 'sql3:'+n;
					logicCell1.setAttribute('id','sql3:'+n)
					logicCell1.className='ruleCompositeCell';
					logicCell1.style.width='130px';
					var fullString='';
					
					// re-concatinate condition value that has embedded spaces
					if (np > 0)
					{
						for (var z=2 ; z<np ; z++ )
						{	fullString += sqlParts[z];	}
					}
					logicCell1.value = fullString;
					bindEvent(logicCell1, 'focus', editCell, 'false')
					bindEvent(logicCell1, 'change', updateArray, 'false')
				logicCell.appendChild(logicCell1);
			ruleLogicRow.appendChild(logicCell);

			// --------------------- create an empty concatinate cell ---------------vvvv-
			var logicCell1 = document.createElement('td');
				logicCell1.style.width  = '55px';
				logicCell1.style.height = '15px';
				
				
				// create the Select object
					var selectEle = document.createElement('select');
					selectEle.className='selectBox';
					//alert("box created = sql4:"+n)
					selectEle.id = 'sql4:'+n;
					selectEle.setAttribute('id','sql4:'+n)
					selectEle.style.width='100%';
					
					// now create the Option rows
					var num = optionValues3.length;
					for (var i=0; i<num ; i++ )
					{
						var opt = document.createElement('option');
						opt.value=optionValues3[i];
						var optText = document.createTextNode(optionValues3[i]);
						opt.appendChild(optText);
						opt.title = optionTitle3[i];
						selectEle.appendChild(opt)
					}

					// set select list option to select as this is an empty cell as it were
					selectEle.selectedIndex=0;
					//alert('done')
					selectEle.title = 'select the concatination operator from this picklist. Note that only the last one can be set to None';
					bindEvent(selectEle, 'change', updateArray, 'false');
					bindEvent(selectEle, 'focus', editCell, 'false');
				logicCell1.appendChild(selectEle);
			ruleLogicRow.appendChild(logicCell1);
			
			
		}
		
	ruleLogicBody.appendChild(ruleLogicRow);	
	}

	ruleLogic.appendChild(ruleLogicBody);
	rulesDiv.appendChild(ruleLogic)
	rules.appendChild(rulesDiv);	
	
	// now set the first row as active
	//editCell('primeit')
}
function popupAbstractEditor(evt)
{
	// check to see if the image is half opaque
	//var thisObj = document.getElementById(getThisId(evt));
	//if(getOpacity(thisObj) != 100) {Event.stop(evt); return;}
	
	// get the source data object for updating
	var parts = getThisId(evt).split(':');
	var targetId = parts[1];
	//var tempValue = document.getElementById(targetId).value;

	// now build the popup editor and store the updated value
	tempValue = buildTextEditor(sldBuilderDiv, 'editor', targetId, '', 'Abstract Editor');
	Event.stop(evt);

}

function popupRulesEditor(evt)
{
	// check to see if the image is half opaque
	var thisObj = document.getElementById(getThisId(evt));
	//alert('op = '+getOpacity(thisObj))
	if(getOpacity(thisObj) != 100) {Event.stop(evt); return;}
	
	// get the source data object for updating
	var parts = getThisId(evt).split(':');
	var targetId = 'sql1:'+parts[1];
	//var tempValue = document.getElementById(targetId).value;

	// now build the popup editor and store the updated value
	tempValue = buildTextEditor(sldBuilderDiv, 'editor', targetId, '', 'Rules Editor');
	Event.stop(evt);

}
function popupTextEditor(evt)
{
	// check to see if the image is half opaque
	//var thisObj = document.getElementById(getThisId(evt));
	//if(getOpacity(thisObj) != 100) {Event.stop(evt); return;}
	
	// get the source data filename for viewing
	var targetId = getThisId(evt);
	var xmlFile = document.getElementById(targetId).value;
	
	// this just launches a new window to look at SLD
	var ht = 600;
	var wt = 760;
	//alert(xml)
	makePopup(xmlFile, wt, ht, 'both');

	// now build the popup editor and store the updated value
	//tempValue = buildTextEditor(sldBuilderDiv, 'editor', targetId ,xmlFile, 'SLD Text Editor');
	Event.stop(evt);

}
function buildTextEditor(sldBuilderDiv, editorId, cellId, filename, headerText)
{
	// remove any existing editor
	checkRemoveObject(editorId);
	var ht = '250px'; 
	var wt = '300px';
	var wtin = '296px';
	var htin = '228px';
	var wtinta = '280px';
	var htinta = '190px';
	//var headerText = 'Attribute Editor';
	var headerImage = 'url(images/banner_300.gif)';
	if(filename != '')
	{	ht = '600px';
		wt = '760px'; 
		wtin = '756px';
		htin = '568px';
		wtinta = '740px';
		htinta = '535px';
	//	headerText = 'SLD Text Editor';
		headerImage = 'url(images/banner_760.gif)';
		existingSld = filename;

		// convert file into an editable string
		var ajaxRequest = fetchXml(filename, '', false, 'GET');
		var content = make_string_from_xml(ajaxRequest.responseXML);
	}
	else
	{	var content = document.getElementById(cellId).value;}

	// create a new floating editor
	var attribEditor = document.createElement('div');
	attribEditor.style.position ='absolute';
	attribEditor.style.top ='50px';
	attribEditor.style.left ='50px';
	attribEditor.style.width = wt; 
	attribEditor.style.height = ht; 
	attribEditor.style.zIndex ='6000'; 
	attribEditor.style.cursor ='move';
	attribEditor.id = editorId;
	//attribEditor.style.border='1px solid red';
	attribEditor.setAttribute("id", editorId);
	
	// create the banner div
	var editorBanner = document.createElement('div');
	editorBanner.className = 'popupDDrapeHeader'; 
	editorBanner.style.backgroundImage = headerImage;
	editorBanner.style.zIndex='5220';
	editorBanner.id = 'attribBanner';
	editorBanner.setAttribute("id", 'attribBanner');
	
	// create the numaps logo symbol image tag
		var symbolImg = document.createElement('img');
		symbolImg.src='images/logo_symbol_small.gif';
		symbolImg.style.position='absolute';
		symbolImg.style.top='7px'; 
		symbolImg.style.left='8px';
		editorBanner.appendChild(symbolImg);
		
		// now add the title in the Banner
		var spanTag = document.createElement('span');
		spanTag.style.position='absolute';
		spanTag.style.top='4px';
		spanTag.style.left='34px';
		var bannerText = document.createTextNode(headerText);	
		spanTag.appendChild(bannerText);
		editorBanner.appendChild(spanTag);
		
		// add the close button
		var symbolImg = document.createElement('img');
		symbolImg.src='images/close.gif';
		symbolImg.style.width='15px';
		symbolImg.style.cursor='pointer';
		symbolImg.style.position='absolute';
		symbolImg.style.top='4px'; 
		symbolImg.style.right='8px';
		symbolImg.id = 'kill:'+editorId;
		symbolImg.setAttribute('id','kill:'+editorId);
		bindEvent(symbolImg, 'click', dropMe, 'false');
		editorBanner.appendChild(symbolImg);
	attribEditor.appendChild(editorBanner);
	
	// create the body of the Panel
	var editorBody = document.createElement('form');
	editorBody.style.backgroundColor='#ECE9D8'; 
	editorBody.style.border='2px solid #0000D6';
	editorBody.style.position='absolute';
	editorBody.style.top='22px';
	editorBody.style.width = wtin;
	editorBody.style.height = htin; 
	//editorBody.className='textarea';
	editorBody.id='tal';
	editorBody.setAttribute('id','tal');
	attribEditor.appendChild(editorBody);
	
	// create the inner textarea
	var textarea = document.createElement('textarea');
	//textarea.type='textarea';
	textarea.style.position = 'absolute';
	textarea.style.top='30px';
	textarea.style.left='10px';
	textarea.style.width = wtinta;
	textarea.cols = '100';
	textarea.rows = '10';
	textarea.style.height = htinta;
	textarea.overflowX ='hidden';
	textarea.overflowY ='auto';
	textarea.className ='ruleCompBody';
	textarea.style.backgroundColor='#FFFFFF';
	textarea.value = content; 
	var parts = cellId.split(':');
	
	// create the appropriate id
	if(filename != '')
	{
		textarea.id='textArea';
		textarea.setAttribute('id','textArea');
	}
	else
	{	textarea.id='source>'+cellId;
		textarea.setAttribute('id','source>'+cellId)
	}
	attribEditor.appendChild(textarea);
	//sldBuilderDiv.appendChild(attribEditor);

	// now add the save button
	var saveButt = document.createElement('input')
	saveButt.type='button';
	saveButt.value='Save'; 
	saveButt.style.width='50px';
	saveButt.style.height='20px';
	saveButt.className = 'buttup';
	saveButt.style.position='absolute';
	saveButt.style.right='10px';
	saveButt.style.bottom='10px';
	saveButt.id='target>'+cellId;
	saveButt.setAttribute('id','target>'+cellId)
	
	if(filename != '')	{ bindEvent(saveButt, 'click', saveSldFile, 'false');}
	else				{ bindEvent(saveButt, 'click', saveRulesData, 'false');}
	attribEditor.appendChild(saveButt);
	
	// close off the tool
	sldBuilderDiv.appendChild(attribEditor);
	Drag.init(editorBanner, attribEditor);
}
function dropMe(evt)
{
	var id = getThisId(evt).split(':')
	document.getElementById(id[1]).style.display="none";
	Event.stop(evt);
}
function saveSldFile(evt)
{
	// get the source data and filename
	var content = document.getElementById('textArea').value;
		
	// get the new temp sld filename and path
	var parts = existingSld.split(applicationBase);
	if(parts.length > 1){  getNewSldName(parts[1]);		}
	else				{  getNewSldName(existingSld);	}						// this outputs newTempSldPath and newTempSldFile
	sldOffset = newTempSldPath + newTempSldFile;

	// make a new temporary SLD file
	var url = applicationBase+"inc/createSldFile.php";
	var query = '?file='+sldOffset+'&content='+content;
	alert(url+query)
	//proxyRequest('', url+query, '','POST') // not working!
	fetchXml(url, query, false, 'POST');
	
	//load the newly edited SLD string into editor
	alert(sldOffset)
	swapSld(sldOffset, currentDrapeStyle, "apply", currentDrapeId, nuCache, true );
	
	// turn off the popup editor and update rule
	document.getElementById('editor').style.display='none';
	
	Event.stop(evt);

}

function saveRulesData(evt)
{
	// get the source and target IDs
	var target = getThisId(evt).split('>');
	var sourceId = 'source>'+target[1];
	//var targetNum = getThisid(evt).split':');
	var targetId = target[1];
	
	// update the target object
	document.getElementById(targetId).value = document.getElementById(sourceId).value;
	
	// turn off the popup editor and update rule
	document.getElementById('editor').style.display='none';
	updateRuleCriteria();
	saveTitle(evt);
	Event.stop(evt);

}

//------------------- create checklist ---------------

function createChecklist(optionValue, optionDesc, targetId)
{
	var num = optionValue.length;
	// create the Select object
	var select = document.createElement('select')
	select.className='selectBox';
	select.id='condition'
	select.setAttribute('id','condition');
	select.style.width='auto';
	
	// now create the Options
	for (var i=0; i<num ; i++ )
	{
		var opt = document.createElement('option');
		opt.value=optionValue[i];
		var optText = document.createTextNode(optionDesc[i]);
		opt.appendChild(optText);
		select.appendChild(opt)
	}
	var target=document.getElementById(targetId);
	target.appendChild(select);

}

// -------------------- function to bind an event to an object ------------------------
	function bindEvent(object, event, fnct, status)
	{
		if (status) status=false;
		if (object.addEventListener)
		{	object.addEventListener(event, fnct, status);  }// for FF 
		else 
		{	object.attachEvent("on"+event, fnct); }// for IE
	} 
	//------------------------------------------------------------------------------------	


function getThisId(evt)
{
	// cross browser tool to determine objects ID from an event trigger
	var e_out;
	var ie_var = "srcElement";
	var moz_var = "target";
	var prop_id = "id";
	// "target" for Mozilla, Netscape, Firefox et al. ; "srcElement" for IE
	evt[moz_var] ? e_out = evt[moz_var][prop_id] : e_out = evt[ie_var][prop_id];
	return e_out;
}
function closeBuilder(evt)
{
	normalDiv('editDDIn');
	document.getElementById('drapeBuilder').style.display="none";
	document.getElementById('editDDIn').title='SHOW StyleBuilder';
	//document.getElementById('editDDIn').className='buttonDiv';
	Event.stop(evt);
}

function buttonDepress(evt)
{
	// depress the button
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonDn';
	Event.stop(evt);
}
function buttonPop(evt)
{
	// depress the button
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	Event.stop(evt);
}

function getHexCode(evt)
{
	// first find out which cell is triggering this event
	var e_out = getThisId(evt);
	//alert(e_out)
	var hexCode = document.getElementById(e_out).value;
	//alert('hexcode = '+hexCode)
	targetId = e_out;
		
/*	// set the appropriate id for that being updated
	var targetId=null;
	if (fillTargetId == 'fillPalette')
	{ var targetId = 'editFill'}
	else if (fillTargetId == 'linePalette')
	{var targetId = 'editLine'}
*/	
	// set the new color as supplied from user
	if (hexCode != 'null' && hexCode != 'transparent' && hexCode !='')
	{	var newHexColor = "#"+hexCode;	}
	else
	{	var newHexColor = 'transparent';	}
	//alert ('selected color = '+newHexColor)
	
	// update the Editing legend cell for fill color
	if (fillColor[currentRow] != newHexColor && targetId == 'editFill')
	{	
		fillColor[currentRow] = newHexColor;	
		document.getElementById(targetId).style.backgroundColor = newHexColor;
		document.getElementById(targetId).value = hexCode;
		if (newHexColor != 'transparent' )
		{	
			// if fill colour selected and no opacity, force opacity to 1
			if(fillOpacity[currentRow] == 'null' || fillOpacity[currentRow] == ' ' || fillOpacity[currentRow] == '' || fillOpacity[currentRow] == null)
			{	fillOpacity[currentRow] = 1;	
				document.getElementById('fillOp').selectedIndex = 0;
			}
		}
		else // if line color and pattern are null then make sure line weight is set to 0
		{
			fillOpacity[currentRow] = 0
			document.getElementById('filldOp').selectedIndex = 9;
			document.getElementById(targetId).style.backgroundColor='transparent';
		}
	}

	// update the Editing legend cell for line colour
	if (lineColor[currentRow] != newHexColor && targetId == 'editLine')
	{	
		document.getElementById(targetId).style.backgroundColor=newHexColor;
		document.getElementById(targetId).value = hexCode;
		lineColor[currentRow] = newHexColor;
		if (newHexColor != 'transparent')
		{	
			// if line colour selected and no line weight, force line weight to 1
			if(lineWeight[currentRow] == 'null' || lineWeight[currentRow] == ' ' || lineWeight[currentRow] == '' || lineWeight[currentRow] == null)
			{	lineWeight[currentRow] = 1;
				lineOpacity[currentRow] = 1;	
				document.getElementById('bordThick').selectedIndex = 1;
				document.getElementById('bordOp').selectedIndex = 0;
			}
		}
		else // if line color null then make sure line weight is set to 0
		{
			lineWeight[currentRow] = 0;
			lineOpacity[currentRow] = 0
			document.getElementById('bordThick').selectedIndex = 0;
			document.getElementById('bordOp').selectedIndex = 10;
			document.getElementById(targetId).style.backgroundColor='transparent';
		}
	}
	
	// build the new edit legend symbol and rule name cells	
	var Cell = "tdBox:"+currentRow;
	var Div = "div:"+currentRow;
	var Rule = "rule:"+currentRow;
	var Bord = "outDivId:"+currentRow;
	checkRemoveObject(Cell);
	checkRemoveObject(Rule);
	var parentObj = document.getElementById("row:"+currentRow);
	buildSymbolBox(parentObj, Cell, Div, Bord, Rule, currentRow)
	document.getElementById(Cell).className='selectedItem';
	document.getElementById(Rule).className='selectedItem';
	//document.getElementById(Cell).style.border='3px solid #FF0000';
	//document.getElementById(Rule).style.border='3px solid #FF0000';
	
	Event.stop(evt);
}


function insertRule(evt)
{
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	
	// insert a slot into the arrays
	var newRow = parseInt(currentRow)+1;
	insertIt(newRow);
	
	// set to the new rule 
	currentRow = newRow
	previousRow = newRow
	
	// build a new edit legend
	buildEditLegend(sldBuilderDiv)
	
	// set to the newly inserted rule
	var id1="tdBox:"+currentRow;
	var id2="rule:"+currentRow;
	document.getElementById(id1).className='selectedItem';
	document.getElementById(id2).className='selectedItem';
	//document.getElementById(id1).style.border='3px solid red';
	//document.getElementById(id2).style.border='3px solid red';

	// build the new editing form
	buildEditorForm(sldBuilderDiv, currentRow)
	
	Event.stop(evt);
}
function insertIt(newRow)
{
	//if the last row just add a row do not split the array
	if (newRow == sqlExp.length)
	{
		//alert('inserting array at row = '+newRow)
		sqlExp[newRow] = '';
		sqlExpTemp[newRow] = '';
		RuleName[newRow] = ''; 
		RuleTitle[newRow] = '';
		RuleAbstract[newRow] = '';
		ruleMinScale[newRow] = '';
		ruleMaxScale[newRow] = '';
		fillColor[newRow] = '';
		fillOpacity[newRow] = ''; 
		fillPattern[newRow] = '';
		lineWeight[newRow] = '';
		lineColor[newRow] = '';
		lineOpacity[newRow] = '';
		lineDash[newRow] = '';
	}
	else
	{
		//alert ('splitting array at row = '+newRow)
		sqlExp.splice(newRow,0,'');
		sqlExpTemp.splice(newRow,0,'');
		RuleName.splice(newRow,0,''); 
		RuleTitle.splice(newRow,0,'');
		RuleAbstract.splice(newRow,0,'');
		ruleMinScale.splice(newRow,0,'');
		ruleMaxScale.splice(newRow,0,'');
		fillColor.splice(newRow,0,'');
		fillOpacity.splice(newRow,0,''); 
		fillPattern.splice(newRow,0,'');
		lineWeight.splice(newRow,0,'');
		lineColor.splice(newRow,0,'');
		lineOpacity.splice(newRow,0,'');
		lineDash.splice(newRow,0,'');
	}
	
}
function cloneCond(evt)
{
	// pop up the button
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';

	var parts = lastCell.split(':');
	var ruleRow = parseInt(parts[1]);
	
	//alert ('sqlExpressions len before splice = '+sqlExpressions.length)
	var newRuleRow = ruleRow + 2;
	var copyRuleRow = ruleRow + 1;
	//var blank_rule = "enter-attribute ex 'enter-value'";
	var newRule = sqlExpressions[ruleRow];
	var conRule = sqlExpressions[ruleRow+1];
	sqlExpressions.splice(newRuleRow,0, newRule, conRule);			// after RuleRow insert two blank elements
	//alert('inserted rule condition = '+sqlExpressions[newRuleRow] +" : "+sqlExpressions[newRuleRow+1]);

	// now copy all elements of previous rule into this new rule
	
	
	// rebuild the sqlExp array 
	buildRuleConditions(currentRow)
	
	// refresh the rule conditions table
	var rules=document.getElementById('rulesDiv')
	buildFilterEditor(currentRow, rules)
	
	// set to the new inserted row
	document.getElementById('sql1:'+newRuleRow).value = document.getElementById('sql1:'+ruleRow).value; document.getElementById('sql1:'+newRuleRow).focus();
	document.getElementById('sql2:'+newRuleRow).value = document.getElementById('sql2:'+ruleRow).value;
	document.getElementById('sql3:'+newRuleRow).value = document.getElementById('sql3:'+ruleRow).value;
	document.getElementById('sql4:'+newRuleRow).value = document.getElementById('sql4:'+ruleRow).value;

	// set the save button to Red
	document.getElementById('save').style.color = "#FF0000";

	Event.stop(evt);
}

function insertCond(evt)
{
	// pop up the button
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';

	var parts = lastCell.split(':');
	var ruleRow = parseInt(parts[1]);
	
	//alert ('sqlExpressions len before splice = '+sqlExpressions.length)
	var newRuleRow = ruleRow+2
	var blank_rule = "enter-attribute ex 'enter-value'";
	sqlExpressions.splice(newRuleRow,0, blank_rule,"con");			// after RuleRow insert two blank elements
	
	// rebuild the sqlExp array 
	buildRuleConditions(currentRow)
	
	// refresh the rule conditions table
	var rules=document.getElementById('rulesDiv')
	buildFilterEditor(currentRow, rules)
	
	// set to the new inserted row
	document.getElementById('sql1:'+newRuleRow).value=''; document.getElementById('sql1:'+newRuleRow).focus();
	document.getElementById('sql2:'+newRuleRow).value='';
	document.getElementById('sql3:'+newRuleRow).value='';
	document.getElementById('sql4:'+newRuleRow).value='';

	// set the save button to Red
	document.getElementById('save').style.color = "#FF0000";
	
	Event.stop(evt);
}

function deleteRule(evt)
{
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	//alert(e_out)
	//alert('current Row = '+currentRow)
	
	if(sqlExp.length == 1)
	{
		sqlExp[currentRow] = '';
		sqlExpTemp[currentRow] = '';
		RuleName[currentRow] = '';
		RuleTitle[currentRow] = '';
		RuleAbstract[currentRow] = '';
		ruleMinScale[currentRow] = '';
		ruleMaxScale[currentRow] = '';
		fillColor[currentRow] = '';
		fillOpacity[currentRow] = ''; 
		fillPattern[currentRow] = '';
		lineWeight[currentRow] = '';
		lineColor[currentRow] = '';
		lineOpacity[currentRow] = '';
		lineDash[currentRow] = '';
	}
	else
	{
		//alert("before splice = "+sqlExp[currentRow])
		sqlExp.splice(currentRow,1);
		sqlExpTemp.splice(currentRow,1);
		RuleName.splice(currentRow,1); 
		RuleTitle.splice(currentRow,1);
		RuleAbstract.splice(currentRow,1);
		ruleMinScale.splice(currentRow,1);
		ruleMaxScale.splice(currentRow,1);
		fillColor.splice(currentRow,1);
		fillOpacity.splice(currentRow,1); 
		fillPattern.splice(currentRow,1);
		lineWeight.splice(currentRow,1);
		lineColor.splice(currentRow,1);
		lineOpacity .splice(currentRow,1);
		lineDash.splice(currentRow,1);
	}
	// build a new edit legend
	buildEditLegend(sldBuilderDiv)

	// check to see if the deleted row was last row
	if (sqlExp.length == currentRow)
	{	
		currentRow = parseInt(currentRow)-1
		previousRow = currentRow
	}
	
	// load the first rule into rules editor
	//alert('currentRow = '+currentRow+' previousRow = '+previousRow)
	var id1="tdBox:"+currentRow;
	var id2="rule:"+currentRow;
	document.getElementById(id1).className='selectedItem';
	document.getElementById(id2).className='selectedItem';
	//document.getElementById(id1).style.border='3px solid red';
	//document.getElementById(id2).style.border='3px solid red';
	buildEditorForm(sldBuilderDiv, currentRow)
	
	Event.stop(evt);
}

function deleteCond(evt)
{
	// pop up the button
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	if (lastCell == null)
	{	alert('Please select a condition row for editing by clicking anywhere on a row'); Event.stop(evt); return;	}

	// delete the current row from the table and the array
	var ruleRow = parseInt(lastCell.split(':')[1]);
	sqlExpressions.splice(ruleRow,2);										// at ruleRow remove two array elements
	
	// treat the deletion of the last rule as a clear rule
	if(sqlExpressions.length == 0) 
	{
		sqlExpressions[0] = '';
		sqlExpressions[1] = '';
		document.getElementById('sql1:'+ruleRow).value='';
		document.getElementById('sql2:'+ruleRow).value='';
		document.getElementById('sql3:'+ruleRow).value='';
		document.getElementById('sql4:'+ruleRow).value='';
		setOpacity(document.getElementById('sql5:'+ruleRow),50);
		sqlExpTemp[currentRow] = '';
	}
	else
	{
		// rebuild the sqlExpTemp array 
		buildRuleConditions(currentRow)
		//alert('status = '+sqlExpTemp[currentRow])

		// refresh the rule conditions table
		var rules=document.getElementById('rulesDiv')
		buildFilterEditor(currentRow, rules)
		lastCell = 'sql1:0';
		document.getElementById('sql1:0').className='selectedItem';
		document.getElementById('sql2:0').className='selectedItem';
		document.getElementById('sql3:0').className='selectedItem';
		document.getElementById('sql4:0').className='selectedItem';
		//document.getElementById('sql1:0').style.border='3px solid red';
		//document.getElementById('sql2:0').style.border='3px solid red';
		//document.getElementById('sql3:0').style.border='3px solid red';
		//document.getElementById('sql4:0').style.border='3px solid red';
		setOpacity(document.getElementById('sql5:0'),100);
	}
	// set the save button to Red
	document.getElementById('save').style.color = "#FF0000";

	Event.stop(evt);
}


function buildRuleConditions(ruleRow)
{
	// check for even number in array and adjust array length to drop off last concat rule
	if (sqlExpressions.length > 0)
	{
		if(evenCheck(sqlExpressions.length))
		{	var numb = sqlExpressions.length-1; 
			sqlExpressions[numb]='';
		}
		else 
		{	var numb = sqlExpressions.length}

		// now reconstitute the sqlExp array from sqlExpressions 
		for (var i=0; i<numb ; i=i+2 )
		{
			if (i == 0)
			{	
				if(!sqlExpressions[i+1] || sqlExpressions[i+1] == 'undefined' )
				{	sqlExpTemp[ruleRow] = sqlExpressions[i]	}
				else
				{	sqlExpTemp[ruleRow] = sqlExpressions[i]+','+sqlExpressions[i+1]	}
			}
			else if (i == numb-1)
			{	sqlExpTemp[ruleRow] += ','+sqlExpressions[i];			}
			else if (i>0 && i<numb-1)
			{	
				if (!sqlExpressions[i+1] || sqlExpressions[i+1] == 'undefined' )
				{	sqlExpTemp[ruleRow] += ','+sqlExpressions[i];}	
				else
				{	sqlExpTemp[ruleRow] += ','+sqlExpressions[i]+','+sqlExpressions[i+1]}
			}
			//alert ('interim concatinated = '+sqlExp[ruleRow])
		}
		//alert ('at the end = '+sqlExp[ruleRow])
	}
	else
	{
		sqlExpTemp[ruleRow]='';
	}
}

function addCond(evt)
{
	//determine which select box was being operated on
	var e_out = getThisId(evt)
	
	// determine which option was selected
	var select = document.getElementById(e_out)
	var rowNum = lastCell.split(':');
	var row = rowNum[1]
	
	// break up existing sqlExpression into its parts
	var parts = sqlExpressions[row].split('|')
	
	// add the element to the appropriate row cell
	if(e_out == 'attribs')
	{	
		var newValue = select.options[select.selectedIndex].value;
		var cell = 'sql1:'+row;
		var spaces='';
		if (document.getElementById(cell).value){	var spaces =' '		}
		document.getElementById(cell).value = document.getElementById(cell).value + newValue;
		parts[0] = document.getElementById(cell).value
		sqlExpressions[row] = parts[0]+'|'+parts[1]+'|'+parts[2];
		//alert(sqlExpressions[row])
	}
	
	//alert('concat = '+sqlExpressions[row+1])
	
	// rebuild the sqlExpTemp array 
	buildRuleConditions(currentRow)
	//alert('status = '+sqlExpTemp[currentRow])

	// refresh the rule conditions table
	var rules=document.getElementById('rulesDiv')
	buildFilterEditor(currentRow, rules)
	document.getElementById('sql1:'+row).className='selectedItem';
	document.getElementById('sql2:'+row).className='selectedItem';
	document.getElementById('sql3:'+row).className='selectedItem';
	document.getElementById('sql4:'+row).className='selectedItem';
	//document.getElementById('sql1:'+row).style.border='3px solid red';
	//document.getElementById('sql2:'+row).style.border='3px solid red';
	//document.getElementById('sql3:'+row).style.border='3px solid red';
	//document.getElementById('sql4:'+row).style.border='3px solid red';
	setOpacity(document.getElementById('sql5:0'),100);
	
	
	select.selectedIndex=0;
	document.getElementById(cell).focus();
	Event.stop(evt);
}
function ruleUp(evt)
{
	//determine which select box was being operated on
	var e_out = getThisId(evt);
	document.getElementById(e_out).className='buttonUp';
	//alert('currentRow = '+currentRow);
	var targetRow = parseInt(currentRow)-1;

	// first check to see if the currentRow is at the top
	if(currentRow != 0) 
	{
		// save current into temp variables
		var tempExp01 = sqlExp[currentRow] ;
		var tempExp02 = sqlExpTemp[currentRow];
		var tempName = RuleName[currentRow] ;
		var tempTitle = RuleTitle[currentRow];
		var tempAbstract = RuleAbstract[currentRow];
		var tempMinScale = ruleMinScale[currentRow];
		var tempMaxScale = ruleMaxScale[currentRow];
		var tempFillColor = fillColor[currentRow];
		var tempFillOpacity = fillOpacity[currentRow]; 
		var tempFillPattern = fillPattern[currentRow];
		var tempLineWeight = lineWeight[currentRow];
		var tempLineColor = lineColor[currentRow];
		var tempLineOpacity = lineOpacity[currentRow];
		var tempLineDash = lineDash[currentRow];
		
		// copy row above current row into current row
		sqlExp[currentRow] = sqlExp[targetRow];
		sqlExpTemp[currentRow] = sqlExpTemp[targetRow];
		RuleName[currentRow] = RuleName[targetRow];
		RuleTitle[currentRow] = RuleTitle[targetRow];
		RuleAbstract[currentRow] = RuleAbstract[targetRow];
		ruleMinScale[currentRow] = ruleMinScale[targetRow];
		ruleMaxScale[currentRow] = ruleMaxScale[targetRow];
		fillColor[currentRow] = fillColor[targetRow];
		fillOpacity[currentRow] = fillOpacity[targetRow]; 
		fillPattern[currentRow] = fillPattern[targetRow];
		lineWeight[currentRow] = lineWeight[targetRow];
		lineColor[currentRow] = lineColor[targetRow];
		lineOpacity[currentRow] = lineOpacity[targetRow];
		lineDash[currentRow] = lineDash[targetRow];

		// copy temp into row above current row
		sqlExp[targetRow] = tempExp01;
		sqlExpTemp[targetRow] = tempExp02;
		RuleName[targetRow] = tempName;
		RuleTitle[targetRow] = tempTitle;
		RuleAbstract[targetRow] = tempAbstract;
		ruleMinScale[targetRow] = tempMinScale;
		ruleMaxScale[targetRow] = tempMaxScale;
		fillColor[targetRow] = tempFillColor;
		fillOpacity[targetRow] = tempFillOpacity; 
		fillPattern[targetRow] = tempFillPattern;
		lineWeight[targetRow] = tempLineWeight;
		lineColor[targetRow] = tempLineColor;
		lineOpacity[targetRow] = tempLineOpacity;
		lineDash[targetRow] = tempLineDash;

		currentRow	=	targetRow;
		previousRow	=	currentRow;
		
		// build a new edit legend
		buildEditLegend(sldBuilderDiv)
		
		// set to the newly inserted rule
		var id1="tdBox:"+currentRow;
		var id2="rule:"+currentRow;
		document.getElementById(id1).className='selectedItem';
		document.getElementById(id2).className='selectedItem';
		//document.getElementById(id1).style.border='3px solid red';
		//document.getElementById(id2).style.border='3px solid red';

		// build the new editing form
		buildEditorForm(sldBuilderDiv, currentRow)

	}
	Event.stop(evt);
}
function ruleDown(evt)
{
	//determine which select box was being operated on
	var e_out = getThisId(evt);
	document.getElementById(e_out).className='buttonUp';
	//alert('currentRow = '+currentRow);
	var lastPos = sqlExp.length - 1
	var targetRow = parseInt(currentRow)+1;

	// first check to see if the currentRow is at the top
	if(currentRow != lastPos) 
	{
		// save current into temp variables
		var tempExp01 = sqlExp[currentRow] ;
		var tempExp02 = sqlExpTemp[currentRow];
		var tempName = RuleName[currentRow] ;
		var tempTitle = RuleTitle[currentRow];
		var tempAbstract = RuleAbstract[currentRow];
		var tempMinScale = ruleMinScale[currentRow];
		var tempMaxScale = ruleMaxScale[currentRow];
		var tempFillColor = fillColor[currentRow];
		var tempFillOpacity = fillOpacity[currentRow]; 
		var tempFillPattern = fillPattern[currentRow];
		var tempLineWeight = lineWeight[currentRow];
		var tempLineColor = lineColor[currentRow];
		var tempLineOpacity = lineOpacity[currentRow];
		var tempLineDash = lineDash[currentRow];
		
		// copy row above current row into current row
		sqlExp[currentRow] = sqlExp[targetRow];
		sqlExpTemp[currentRow] = sqlExpTemp[targetRow];
		RuleName[currentRow] = RuleName[targetRow];
		RuleTitle[currentRow] = RuleTitle[targetRow];
		RuleAbstract[currentRow] = RuleAbstract[targetRow];
		ruleMinScale[currentRow] = ruleMinScale[targetRow];
		ruleMaxScale[currentRow] = ruleMaxScale[targetRow];
		fillColor[currentRow] = fillColor[targetRow];
		fillOpacity[currentRow] = fillOpacity[targetRow]; 
		fillPattern[currentRow] = fillPattern[targetRow];
		lineWeight[currentRow] = lineWeight[targetRow];
		lineColor[currentRow] = lineColor[targetRow];
		lineOpacity[currentRow] = lineOpacity[targetRow];
		lineDash[currentRow] = lineDash[targetRow];

		// copy temp into row above current row
		sqlExp[targetRow] = tempExp01;
		sqlExpTemp[targetRow] = tempExp02;
		RuleName[targetRow] = tempName;
		RuleTitle[targetRow] = tempTitle;
		RuleAbstract[targetRow] = tempAbstract;
		ruleMinScale[targetRow] = tempMinScale;
		ruleMaxScale[targetRow] = tempMaxScale;
		fillColor[targetRow] = tempFillColor;
		fillOpacity[targetRow] = tempFillOpacity; 
		fillPattern[targetRow] = tempFillPattern;
		lineWeight[targetRow] = tempLineWeight;
		lineColor[targetRow] = tempLineColor;
		lineOpacity[targetRow] = tempLineOpacity;
		lineDash[targetRow] = tempLineDash;

		currentRow	=	targetRow;
		previousRow	=	currentRow;
		
		// build a new edit legend
		buildEditLegend(sldBuilderDiv)
		
		// set to the newly inserted rule
		var id1="tdBox:"+currentRow;
		var id2="rule:"+currentRow;
		document.getElementById(id1).className='selectedItem';
		document.getElementById(id2).className='selectedItem';
		//document.getElementById(id1).style.border='3px solid red';
		//document.getElementById(id2).style.border='3px solid red';

		// build the new editing form
		buildEditorForm(sldBuilderDiv, currentRow);
	}
	Event.stop(evt);
}

function cloneRule(evt)
{
	var e_out = getThisId(evt);
	document.getElementById(e_out).className='buttonUp';
	//alert(e_out);

	// insert a new Rule
	var newRow = parseInt(currentRow)+1;
	insertIt(newRow);

	// get data from current rule and load into new Rule
	sqlExp[newRow] = sqlExp[currentRow];
	sqlExpTemp[newRow] = sqlExpTemp[currentRow];
	RuleName[newRow] = RuleName[currentRow];
	RuleTitle[newRow] = RuleTitle[currentRow];
	RuleAbstract[newRow] = RuleAbstract[currentRow];
	ruleMinScale[newRow] = ruleMinScale[currentRow];
	ruleMaxScale[newRow] = ruleMaxScale[currentRow];
	fillColor[newRow] = fillColor[currentRow];
	fillOpacity[newRow] = fillOpacity[currentRow]; 
	fillPattern[newRow] = fillPattern[currentRow];
	lineWeight[newRow] = lineWeight[currentRow];
	lineColor[newRow] = lineColor[currentRow];
	lineOpacity[newRow] = lineOpacity[currentRow];
	lineDash[newRow] = lineDash[currentRow];

// set to the new rule 
	currentRow = newRow
	previousRow = newRow
	
	// build a new edit legend
	buildEditLegend(sldBuilderDiv)
	
	// set to the newly inserted rule
	var id1="tdBox:"+currentRow;
	var id2="rule:"+currentRow;
	document.getElementById(id1).className='selectedItem';
	document.getElementById(id2).className='selectedItem';
	//document.getElementById(id1).style.border='3px solid red';
	//document.getElementById(id2).style.border='3px solid red';

	// build the new editing form
	buildEditorForm(sldBuilderDiv, currentRow)

	Event.stop(evt);
}
function themeSld(evt)
{
	// toggle button back to off and display the forms
	var e_out = getThisId(evt);
	document.getElementById(e_out).className='buttonUp';
	fillTargetId = e_out;
	colourPicker(evt);
	Event.stop(evt);
}
function replaceSld(evt)
{
	// first make sure that no options are selected
	document.getElementById('attribsUsed').selectedIndex=-1;
	document.getElementById('schemaUsed').selectedIndex=-1;

	// toggle button back to off and display the forms
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	document.getElementById('replaceIt').style.display='block';
	Event.stop(evt);
}
function back(evt)
{
	// toggle button back to off and display the forms
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	document.getElementById('replaceIt').style.display='none';
	Event.stop(evt);
}

function replaceAtts(evt)
{
	var e_out = getThisId(evt)
	var existingAtt = document.getElementById('attribsUsed');
	//alert('selected index = '+existingAtt.selectedIndex);
	if(document.getElementById('attribsUsed').selectedIndex == -1 || document.getElementById('schemaUsed').selectedIndex == -1)
	{	
		document.getElementById(e_out).className='buttonUp'; 
		//document.getElementById('replaceIt').style.display='none';
		return;
	}
	oldAttributes = new Array();
	//if(existingAtt.Multiple == 'Multiple')
	//{
	// loop through all options to get those selected by user
	var k=0;
	for(var i=0; i<existingAtt.options.length; i++)
	{
		if(existingAtt.options[i].selected)
		{ 
			oldAttributes[k] = existingAtt.options[i].value;
			k++;
		}
	}
	//alert('old atts to be replaced  = '+oldAttributes)
	

	var replaceAtt = document.getElementById('schemaUsed');
	var newAttribute = replaceAtt.options[replaceAtt.selectedIndex].value;
	//alert('new= '+newAttribute);
	//alert(sqlExp)
	
	// make the replacement for each attribute in the oldAttributes array
	for (var j=0; j<oldAttributes.length ; j++)
	{
		//alert('old = '+oldAttributes[j]+ " new = "+ newAttribute)
		// loop through the sqlExp array and replace the attribute requested
		for(var i=0; i<sqlExp.length; i++)
		{
			sqlExp[i] = sqlExp[i].replaceAll(oldAttributes[j], newAttribute ) // replaceAll in miscUtils
		}
	}
	//alert(sqlExp)

	// if an attribute was deleted then clean up any math signs etc
	sqlExp = cleanUpSqlExpString(sqlExp);
	//alert(sqlExp)
	
	// refresh the Edit legend
	buildEditLegend(sldBuilderDiv)

	// refresh the Replace lists
	var temp = getAttributesUsed(sqlExp);
	var selectHolder = document.getElementById('selectHolder');
	checkRemoveObject('attribsUsed');
	
		// create the new Select object
		var tmp = temp.length;
		var select = document.createElement('select');
		select.className='selectBox';
		select.style.fontSize='9px';
		select.style.verticalAlign='middle';
		select.style.position='absolute';
		select.style.top= '0px';
		select.style.left= '0px';
		select.style.width='200px';
		select.setAttribute('size','8');
		select.setAttribute('width','100');
		select.id='attribsUsed';
		select.setAttribute('id','attribsUsed');
		select.multiple='multiple';
		select.setAttribute('multiple','multiple');

		// now create the Option rows for existing attributes
		for (var i=0; i<temp.length ; i++ )
		{		
			var opt = document.createElement('option');
			opt.value=temp[i];
			var optText = document.createTextNode(temp[i]);
			opt.appendChild(optText);
			opt.style.width="100%";
			opt.id='exist:'+i;
			opt.title=temp[i];
			opt.setAttribute('id','exist:'+i);
			select.appendChild(opt);
		}
		selectHolder.appendChild(select);

	// load the current rule into rules editor
	var id1="tdBox:0";
	var id2="rule:0";
	document.getElementById(id1).className='selectedItem';
	document.getElementById(id2).className='selectedItem';
	//document.getElementById(id1).style.border='3px solid red';
	//document.getElementById(id2).style.border='3px solid red';
	buildEditorForm(sldBuilderDiv, currentRow)
	
	// close down the replace forms
	document.getElementById(e_out).className='buttonUp';
	document.getElementById('replaceIt').style.display='none';	
	Event.stop(evt);
}

function cleanUpSqlExpString(sqlExp)
{
	 for (var i=0; i<sqlExp.length; i++ )
	 {		 
		sqlExp[i] = sqlExp[i].replaceAll( "  ", " " );

		// bleed out the redundant double +es
		sqlExp[i] = sqlExp[i].replaceAll( "+ +", "+" );
		sqlExp[i] = sqlExp[i].replaceAll( "+ )", ")" );
		sqlExp[i] = sqlExp[i].replaceAll( "( +", "(" );
		sqlExp[i] = sqlExp[i].replaceAll( "+ |", "|" );

		// bleed out the redundant double -es
		sqlExp[i] = sqlExp[i].replaceAll( "- -", "-" );
		sqlExp[i] = sqlExp[i].replaceAll( "- )", ")" );
		sqlExp[i] = sqlExp[i].replaceAll( "( -", "(" );
		sqlExp[i] = sqlExp[i].replaceAll( "- |", "|" );

		// bleed out the redundant double *es
		sqlExp[i] = sqlExp[i].replaceAll( "* *", "*" );
		sqlExp[i] = sqlExp[i].replaceAll( "* )", ")" );
		sqlExp[i] = sqlExp[i].replaceAll( "( *", "(" );
		sqlExp[i] = sqlExp[i].replaceAll( "* |", "|" );
		// bleed out the redundant double -es
		sqlExp[i] = sqlExp[i].replaceAll( "/ /", "/" );
		sqlExp[i] = sqlExp[i].replaceAll( "/ )", ")" );
		sqlExp[i] = sqlExp[i].replaceAll( "( /", "(" );
		sqlExp[i] = sqlExp[i].replaceAll( "/ |", "|" );


	 }
	 return sqlExp;
}


function clearSld(evt)
{
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	
	// clear out all values for the curtrent row
	sqlExp = [];
	sqlExpTemp = [];
	RuleName = [];
	RuleTitle = [];
	RuleAbstract = [];
	ruleMinScale = [];
	ruleMaxScale = [];
	fillColor = [];
	fillOpacity = []; 
	fillPattern = [];
	lineWeight = [];
	lineColor = [];
	lineOpacity = [];
	lineDash = [];

	sqlExp[0] = '';
	sqlExpTemp[0] = '';
	RuleName[0] = '';
	RuleTitle[0] = '';
	RuleAbstract[0] = '';
	ruleMinScale[0] = '';
	ruleMaxScale[0] = '';
	fillColor[0] = '';
	fillOpacity[0] = ''; 
	fillPattern[0] = '';
	lineWeight[0] = '';
	lineColor[0] = '';
	lineOpacity[0] = '';
	lineDash[0] = '';
	
	currentRow = 0;
	previousRow = 0;

	// build a new edit legend
	buildEditLegend(sldBuilderDiv)

	// load the current rule into rules editor
	//alert('currentRow = '+currentRow+' previousRow = '+previousRow)
	var id1="tdBox:0";
	var id2="rule:0";
	document.getElementById(id1).className='selectedItem';
	document.getElementById(id2).className='selectedItem';
	//document.getElementById(id1).style.border='3px solid red';
	//document.getElementById(id2).style.border='3px solid red';
	buildEditorForm(sldBuilderDiv, currentRow)
	Event.stop(evt);
}

function clearRule(evt)
{
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	
	// clear out all values for the curtrent row
	sqlExp[currentRow] = '';
	sqlExpTemp[currentRow] = '';
	RuleName[currentRow] = '';
	RuleTitle[currentRow] = '';
	RuleAbstract[currentRow] = '';
	ruleMinScale[currentRow] = '';
	ruleMaxScale[currentRow] = '';
	fillColor[currentRow] = '';
	fillOpacity[currentRow] = ''; 
	fillPattern[currentRow] = '';
	lineWeight[currentRow] = '';
	lineColor[currentRow] = '';
	lineOpacity[currentRow] = '';
	lineDash[currentRow] = '';

	// build a new edit legend
	buildEditLegend(sldBuilderDiv)

	// load the current rule into rules editor
	//alert('currentRow = '+currentRow+' previousRow = '+previousRow)
	var id1="tdBox:"+currentRow;
	var id2="rule:"+currentRow;
	document.getElementById(id1).className='selectedItem';
	document.getElementById(id2).className='selectedItem';
	//document.getElementById(id1).style.border='3px solid red';
	//document.getElementById(id2).style.border='3px solid red';
	buildEditorForm(sldBuilderDiv, currentRow)
	Event.stop(evt);
}

function clearCond(evt)
{
	// pop up the button
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	if (lastCell == null)
	{	alert('Please select a condition row for editing by clicking anywhere on a row'); Event.stop(evt); return;	}

	// clear out the current condition row for this rule row
	var ruleRow = parseInt(lastCell.split(':')[1]);
	//alert (sqlExpressions[row]);
	//alert (sqlExpressions[row+1]);
	sqlExpressions[ruleRow] = '';
	sqlExpressions[ruleRow+1] = '';
	document.getElementById('sql1:'+ruleRow).value='';
	document.getElementById('sql2:'+ruleRow).selectedIndex=0;
	document.getElementById('sql3:'+ruleRow).value='';
	document.getElementById('sql4:'+ruleRow).selectedIndex=0;
	sqlExpTemp[ruleRow] = '';

	// set the save button to Red
	document.getElementById('save').style.color = "#FF0000";

	Event.stop(evt);
}

function clearInput(evt)
{
	var e_out = getThisId(evt)
	//alert (e_out)
	document.getElementById(e_out).value='';
	document.getElementById(e_out).focus();
	Event.stop(evt);
}
function applyAllRules(evt)
{
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';

	// apply rule to array elements
	var ele = e_out.split('All');
	if(ele[0] == 'editPattern'){ var newpat = fillPattern[currentRow]; }
	for (var z=0; z<sqlExp.length ; z++ )
	{
		if (ele[0] == 'minScale')
		{	ruleMinScale[z] = document.getElementById(ele[0]).value	;}
		else if	(ele[0] == 'maxScale')
		{	ruleMaxScale[z] = document.getElementById(ele[0]).value	;}
		else if(ele[0] == 'editFill'	)
		{	fillColor[z] = "#"+document.getElementById(ele[0]).value;}	
		else if(ele[0] == 'editLine'	)
		{	lineColor[z] = "#"+document.getElementById(ele[0]).value;}
		else if(ele[0] == 'editPattern'	)
		{	fillPattern[z] = newpat;}
		else if(ele[0] == 'bordThick'	)
		{	lineWeight[z] = document.getElementById(ele[0]).value;}
		else if(ele[0] == 'fillOp'	)
		{	fillOpacity[z] = document.getElementById(ele[0]).value;}
		else if(ele[0] == 'bordOp'	)
		{	lineOpacity[z] = document.getElementById(ele[0]).value;}
		
		//alert(ruleMinScale[z]+" : "+ruleMaxScale[z]+" : "+fillColor[z]+" : " +lineColor[z]+" \n "+fillPattern[z]+" \n "+lineWeight[z]+" : "+fillOpacity[z]+" : "+lineOpacity[z])
		
		// build the new edit legend symbol and rule name cells	
		var Cell = "tdBox:"+z;
		var Div = "div:"+z;
		var Rule = "rule:"+z;
		var Bord = "outDivId:"+z;
		checkRemoveObject(Cell);
		checkRemoveObject(Rule);
		var parentObj = document.getElementById("row:"+z);
		buildSymbolBox(parentObj, Cell, Div, Bord, Rule, z)
	}
	Event.stop(evt);
}

function saveScale(evt)
{
	var e_out = getThisId(evt)
		//alert (e_out)
		if (e_out == 'minScale')
		{
			ruleMinScale[currentRow] = document.getElementById(e_out).value
		}
		else if (e_out == 'maxScale')
		{
			ruleMaxScale[currentRow] = document.getElementById(e_out).value
		}
		// now check that minscale and maxscale make sense
		//alert(ruleMinScale[currentRow])
		if(ruleMinScale[currentRow] != 'undefined' &&  ruleMaxScale[currentRow] != 'undefined')
		{	
			var lowScale = parseInt(ruleMinScale[currentRow]);
			var hiScale = parseInt(ruleMaxScale[currentRow]);
			if (lowScale > hiScale )
			{	
				alert( 'MaxScale cannot be less than MinScale in rule ');
				document.getElementById(e_out).value = '';
				document.getElementById(e_out).focus();
				return;
			}
		}
		var Cell = "tdBox:"+currentRow;
		var Div = "div:"+currentRow;
		var Rule = "rule:"+currentRow;
		var Bord = "outDivId:"+currentRow;
		var parentObj = document.getElementById("row:"+currentRow);
		checkRemoveObject(Cell);
		checkRemoveObject(Rule);
		buildSymbolBox(parentObj, Cell, Div, Bord, Rule, currentRow)
		document.getElementById(Cell).className='selectedItem';
		document.getElementById(Rule).className='selectedItem';
		//document.getElementById(Cell).style.border='3px solid #FF0000';
		//document.getElementById(Rule).style.border='3px solid #FF0000';

		Event.stop(evt);
}
function saveSld(evt)
{
	//alert('saveSld drapeId = '+drapeId);
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	
	// first just force an update of the current rule incase the user forgot to
	updateRuleCriteria()
	
	// validate SLD Rules
	validateRule();
	if(error != '')
	{
		if(confirm(error+'\n\n Do you wish to continue the Save process anyway?')) 
		{}
		else{return;}
	}
	
	// all is well so now go ahead and build the new SLD
	//alert('current Drape Style = '+currentDrapeStyle);
	makeNewSld();
	swapSld(newFileName, currentDrapeStyle, "apply", currentDrapeId, nuCache, true );
	Event.stop(evt);
}
	//--------------- function to validate the numeric values ---------------------
	function validateRule()
	{
		var from = new Array();
		var to = new Array();
		var k = 0;

		//alert(sqlExp.length) // how many rules

		// step thru all parts of the Rule
		for (var i=0 ; i<sqlExp.length ; i++ )
		{
			//alert(sqlExp[i]);
			var parts = sqlExp[i].split(',');
			//alert('number of rule parts = '+parts.length)
			if(parts.length > 3) {error = ''; return error;}
			// process start or end of range
			if (parts.length == 1)
			{	
				// bust up rule into its components
				var ruleParts = parts[0].split('|');
				var value = ruleParts[2].replace(/\'/g, "");
				//alert(value)
				if(checkNumeric(value))
				{
					var number = parseInt(value);
					if(ruleParts[1] == '<') {number = number -1;}
					if(ruleParts[1] == '>') {number = number +1;}
					from[k] = number;
					to[k] = -1;
				}
				else{	return '';	}
			}
			else	// process a concatinated rule pair
			{
				// bust up first part of rule into its components
				var ruleParts = parts[0].split('|');
				var value = ruleParts[2].replace(/\'/g, "");
				if(checkNumeric(value))
				{
					var number = parseInt(value);
					if(ruleParts[1] == '<') {number = number -1;}
					if(ruleParts[1] == '>') {number = number +1;}
					from[k] = number;
					//alert(tofrom[k]);

				}
				// bust up second part of rule into its components
				var ruleParts = parts[2].split('|');
				var value = ruleParts[2].replace(/\'/g, "");
				if(checkNumeric(value))
				{
					var number = parseInt(value);
					if(ruleParts[1] == '<') {number = number -1;}
					if(ruleParts[1] == '>') {number = number +1;}
					to[k] = number;
					//alert(tofrom[k]);
				}
				else{	return '';	}
			}
			k++
			//alert (tofrom)
		}
		//for(var i=0; i<to.length ; i++){alert(' from = '+from[i]+' to = '+to[i]);} 
		error='';
		// now scan through array looking for any gaps in criteria
		for (var i=0; i < to.length ; i++)
		{
			//alert('TO = '+ to[i])
			var	tovalue = parseInt(to[i])
			if(tovalue != -1 )
			{	
				//alert(from[i]+' and '+to[i]);
				//alert(to[i]+' compared with '+from[i+1])
				var delta = from[i+1] - to[i]
				//alert ('delta = '+delta+ ' to = '+to[i]+ ' from = '+from[i+1])
				if (delta > 1)
				{
					var next = i+2;
					var last = i+1
					//alert(i+ ' Gap' +delta+ ' '+to[i]+" : "+from[i+1]);
					error = 'Numeric Gap between value in rule '+last+' and rule '+next;
					return error;
				}
				else if(delta < 1)
				{
					var next = i+2;
					var last = i+1
					//alert(i+ ' Overlap' +delta+ ' '+to[i]+" : "+from[i+1]);
					error = 'Numeric Overlap between value in rule '+last+' and rule '+next;
					return error;
				}

			}
			else{	}
		}

		//alert('validation error = '+error)
		return error;
	}

	function checkNumeric(value)
	{		
		//alert(value)
		var anum=/(^\d+$)|(^\d+\.\d+$)/		
		if (anum.test(value))			return true;		return false;  
	}
	
	//--------------- function to create a new SLD from arrays ----------------------
	function makeNewSld()
	{
		//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 saveCond(evt)
{
	//alert('save event = '+evt)
	// pop up the button
	var e_out = getThisId(evt)
	document.getElementById(e_out).className='buttonUp';
	
	// to be sure just pick up the Rule Condition header info
	updateRuleCriteria();
	Event.stop(evt);
}

function updateRuleCriteria()
{
	// this forces a rule update
	RuleName[currentRow] = document.getElementById('nameNo').value;
	RuleAbstract[currentRow] = document.getElementById('absNo').value;
	RuleTitle[currentRow] = document.getElementById('titleNo').value;
	
	// validate the updated Rule
	var error = validate()
	if(error == '')
	{
		// update sqlExpressions array from input cells
		updateSqlExpressions(lastCell)
		
		// update sqlExp current row
		sqlExp[currentRow]=sqlExpTemp[currentRow]	
		
		// rebuild the editing legend row
		var Cell = "tdBox:"+currentRow;
		var Div = "div:"+currentRow;
		var Rule = "rule:"+currentRow;
		var Bord = "outDivId:"+currentRow;
		checkRemoveObject(Cell);
		checkRemoveObject(Rule);
		var parentObj = document.getElementById("row:"+currentRow);
		buildSymbolBox(parentObj, Cell, Div, Bord, Rule, currentRow)
		document.getElementById(Cell).className='selectedItem';
		document.getElementById(Rule).className='selectedItem';
		//document.getElementById(Cell).style.border='3px solid #FF0000';
		//document.getElementById(Rule).style.border='3px solid #FF0000';
	}
	else
	{
		alert('****** '+error+' ****** \nPlease make sure all the mandatory fields (*) have been correctly entered')
	}
	// set the button back to Black
	document.getElementById('save').style.color='#000000';

}

function validate()
{
	var error = '';
	var sqlParts = sqlExpTemp[currentRow].split(',');
	
	// step through all the separate parts of the submitted Rule
	for (var j=0; j<sqlParts.length-1 ; j=j+2)
	{
		// bust up each rule element into its parts
		var parts = sqlParts[j].split('|');
		var concat = sqlParts[j+1];

		// validate each rule segement attribute(s)-cond-value
		if (parts.length == 3)
		{
			// check for no attributes submitted
			if(parts[0] == '' || parts[0] == null || parts[0] == 'undefined') 
			{ var error = 'No Attribute Entered (element '+j+') = '+parts[0]; return error;}
			
			// This is where we should validate any mathematical formula against attribute list
			
			// check that cond is in the standard list
			for (var i=0; i<optionAlias.length ; i++)
			{	
				if(optionAlias[i] == parts[1] || optionValues[i] == parts[1] && optionValues[i] != 'select') {var error = '';  break;}
				else {var error = 'Invalid Comparison Condition (element '+j+') = '+parts[1]; }
			}
			if(error != ''){return error;}

			// check for value submitted
			if(parts[2] == '' || parts[2] == null || parts[2] == 'undefined') 
				{ var error = 'No Attribute Value Entered (element '+j+') = '+parts[2]; return error;}
			
			// check for no concatination submitted between parts - exception on last rule
			if((concat == '' || concat == null || concat == 'undefined' || concat == 'None') && (sqlParts[j+2] > ''))
				{var error = 'No Concatination Entered by one expected (element '+j+') = '+concat; return error;}
			
			// Check concatination rule against standard list
			if(concat != '' && concat != null && concat != 'undefined' && concat != 'None')
			{
				for (var i=0; i<optionValues3.length ; i++)
				{	
					//alert(optionValues3[i])
					//alert(concat)
					if(optionValues3[i] == concat) {var error = ''; break;}
					else {var error = 'Invalid Concatination Entered (element '+j+') = '+concat; }
				}
			}
			// if error encountered exit
			if(error != ''){return error;}	
		}
		else
		{
			// syntax fails as there are not exactly 3 parts to this rule
			var error = 'Corrupt Rule Components (element '+j+') = '+parts;
		}
	}
	// check that mandatory item ruleName has been submitted
	if(RuleName[currentRow] == ' ' || RuleName[currentRow] == '' || RuleName[currentRow] == null || RuleName[currentRow] == 'undefined' )
	{	var error = 'Mandatory Rule Name not Present - please enter and re-save'	}

	return error;
}


/*function exit(evt)
{
	var e_out = getThisId(evt)
	document.getElementById("sldBuilderArea").style.display="none";
	Event.stop(evt);
}*/
function colourPicker(evt)
{
	var e_out = getThisId(evt);
	fillTargetId = e_out;
	buildColorPalette(sldBuilderDiv);
	Event.stop(evt);
}

function imagePicka(evt)
{
	var e_out = getThisId(evt)
	buildImagePicker(sldBuilderDiv);
	Event.stop(evt);

}
function getNewValue(evt)
{
	var e_out = getThisId(evt)
	var areaObj = document.getElementById(e_out);	
	var newValue = areaObj.options[areaObj.selectedIndex].value;
	var Cell = "tdBox:"+currentRow;
	var Div = "div:"+currentRow;
	var Rule = "rule:"+currentRow;
	var Bord = "outDivId:"+currentRow;
	var parentObj = document.getElementById("row:"+currentRow);
	checkRemoveObject(Cell);
	checkRemoveObject(Rule);
	
	// update Line Thickness 
	if (e_out == 'bordThick')
	{	
		// update editing form and array
		lineWeight[currentRow]=newValue;
		if(newValue == 0) 
		{	
			document.getElementById('editLine').style.backgroundColor = 'transparent';
			document.getElementById('bordOp').selectedIndex = 10; // set to 0
			lineColor[currentRow]=null;
			lineOpacity[currentRow]=0;
		}
	}
	// now same for Fill Opacity
	else if (e_out == 'fillOp')
	{	
		fillOpacity[currentRow]=newValue;
		//document.getElementById('editOpacity').value = newValue;
	}
	
	// now same for Fill Opacity
	else if (e_out == 'bordOp')
	{	
		lineOpacity[currentRow]=newValue;
		//document.getElementById('editLineOpac').value = newValue;
	}
	// build the new edit legend symbol and rule name cells
	buildSymbolBox(parentObj, Cell, Div, Bord, Rule, currentRow)
	document.getElementById(Cell).className='selectedItem';
	document.getElementById(Rule).className='selectedItem';
	//document.getElementById(Cell).style.border='3px solid #FF0000';
	//document.getElementById(Rule).style.border='3px solid #FF0000';

	Event.stop(evt);
}


function rollOver(evt)
{
	var e_out = getThisId(evt)
	var elNo = e_out.split(":");
	if(elNo[0] == 'rule')
	{
		//var rowId = "row:"+elNo[1];
		var id1="tdBox:"+elNo[1];
		var id2="rule:"+elNo[1];
		
		// change colour of both cells
		document.getElementById(id1).style.backgroundColor='#AAFFFF'; // cyan background
		document.getElementById(id2).style.backgroundColor='#AAFFFF'; // cyan background
	}
	else if(elNo[0] == 'ruleRow')
	{
		document.getElementById(e_out).style.backgroundColor='#AAFFFF'; // cyan background
	}
	Event.stop(evt);
}
function rollOut(evt)
{
	var e_out = getThisId(evt)
	var elNo = e_out.split(":");
	if(elNo[0] == 'rule')
	{
		//var rowId = "row:"+elNo[1];
		var id1="tdBox:"+elNo[1];
		var id2="rule:"+elNo[1];
		
		// change colour of both cells
		document.getElementById(id1).className='unselectedItem';
		document.getElementById(id2).className='unselectedItem';
		//document.getElementById(id1).style.backgroundColor='transparent'; // cyan background
		//document.getElementById(id2).style.backgroundColor='transparent'; // cyan background
	}
	else if(elNo[0] == 'ruleRow')
	{
		document.getElementById(id1).className='unselectedItem';
		//document.getElementById(e_out).style.backgroundColor='transparent'; // cyan background
	}
	Event.stop(evt);

}
function tabToCell(evt)
{		//alert(evt.keyCode)
	if (evt.keyCode == 9) // this is the TAB key
	{
		//alert("cuttentCell = "+lastCell)
		var parts = lastCell.split(":")
		if (parts[0] == 'sql4')
		{
			var nextId = 'sql1:'+parts[1];
		}
		else
		{
			var e_out = getThisId(evt)
			var parts = e_out.split("sql")
			var cellNo = parts[1].split(":");
			var nextCellNo = parseInt(cellNo[0])+1;
			var nextId = "sql"+nextCellNo+":"+cellNo[1];
		}
		
		if (lastCell !=null)
		{
			//alert ("lastCell = "+lastCell)
			document.getElementById(lastCell).className='unselectedItem';
			//document.getElementById(lastCell).style.borderLeft='1px solid gray';
			//document.getElementById(lastCell).style.borderTop='1px solid gray';
			//document.getElementById(lastCell).style.borderRight='1px solid #E1E1E1';
			//document.getElementById(lastCell).style.borderBottom='1px solid #E1E1E1';
			setOpacity(document.getElementById('sql5:'+parts[1]),50);
		}
		//alert('nextId = '+nextId)
		document.getElementById(nextId).className='selectedItem';
		//document.getElementById(nextId).style.border='3px solid red';
		lastCell = nextId;
		document.getElementById(nextId).focus();
		//alert("currentCell = "+lastCell)
	}

	Event.stop(evt);
}
function editCell(evt)
{
	var e_out = getThisId(evt)
	var rowNo = e_out.split(":");
	var newrow = parseInt(rowNo[1]);
	
	//alert(sqlExpressions[rowNo[1]])
	var next = newrow + 1				// this is the concat cell
	//alert(sqlExpressions[next])
		
	var cell1 = 'sql1:'+newrow;
	var cell2 = 'sql2:'+newrow;
	var cell3 = 'sql3:'+newrow;
	var cell4 = 'sql4:'+newrow;
	var cell5 = 'sql5:'+newrow;
	
	// toggle the previous rows cells to normal
		var rowNo = lastCell.split(':')
		var oldrow = parseInt(rowNo[1]);
		var lastCell1 = 'sql1:'+oldrow;
		var lastCell2 = 'sql2:'+oldrow;
		var lastCell3 = 'sql3:'+oldrow;
		var lastCell4 = 'sql4:'+oldrow;
		var lastCell5 = 'sql5:'+oldrow;
		
		// now switch all old boxes back to normal
		document.getElementById(lastCell1).className='unselectedItem';
		//document.getElementById(lastCell1).style.borderLeft='1px solid gray';
		//document.getElementById(lastCell1).style.borderTop='1px solid gray';
		//document.getElementById(lastCell1).style.borderRight='1px solid #E1E1E1';
		//document.getElementById(lastCell1).style.borderBottom='1px solid #E1E1E1';

		document.getElementById(lastCell2).className='unselectedItem';
		//document.getElementById(lastCell2).style.borderLeft='1px solid gray';
		//document.getElementById(lastCell2).style.borderTop='1px solid gray';
		//document.getElementById(lastCell2).style.borderRight='1px solid #E1E1E1';
		//document.getElementById(lastCell2).style.borderBottom='1px solid #E1E1E1';

		document.getElementById(lastCell3).className='unselectedItem';
		//document.getElementById(lastCell3).style.borderLeft='1px solid gray';
		//document.getElementById(lastCell3).style.borderTop='1px solid gray';
		//document.getElementById(lastCell3).style.borderRight='1px solid #E1E1E1';
		//document.getElementById(lastCell3).style.borderBottom='1px solid #E1E1E1';

		document.getElementById(lastCell4).className='unselectedItem';
		//document.getElementById(lastCell4).style.borderLeft='1px solid gray';
		//document.getElementById(lastCell4).style.borderTop='1px solid gray';
		//document.getElementById(lastCell4).style.borderRight='1px solid #E1E1E1';
		//document.getElementById(lastCell4).style.borderBottom='1px solid #E1E1E1';
		setOpacity(document.getElementById(lastCell5),50);
	

	// highlight the picked row in any case
	document.getElementById(cell1).className='selectedItem';
	document.getElementById(cell2).className='selectedItem';
	document.getElementById(cell3).className='selectedItem';
	document.getElementById(cell4).className='selectedItem';
	//document.getElementById(cell1).style.border='3px solid red';
	//document.getElementById(cell2).style.border='3px solid red';
	//document.getElementById(cell3).style.border='3px solid red';
	//document.getElementById(cell4).style.border='3px solid red';
	setOpacity(document.getElementById(cell5),100);

	lastCell = e_out;
	//alert("currentCell = "+lastCell)
	document.getElementById(e_out).focus();
	Event.stop(evt);
}

function updateArray(evt)
{
	// any change to any of the fields will trigger a reconstruction of ther SQL Expression arrays
	var e_out = getThisId(evt)
		
	// update the sqlExpression arrays with form data
	updateSqlExpressions(e_out)
	
	var rowNo = e_out.split(':')
		//alert('element being updated = '+rowNo[0]);
	if(rowNo[0] == 'sql4')
	{
		var row = parseInt(rowNo[1]);

		// if this was the conmcatination options change check for adding a new rule
		var ruleRow = parseInt(row);
		if(sqlExpressions.length == ruleRow+2)
		{
			//alert ('sqlExpressions len before splice = '+sqlExpressions.length)
			var newRuleRow = ruleRow+2
			var blank_rule = "enter-attribute ex 'enter-value'";
			sqlExpressions.splice(newRuleRow,0, blank_rule,"con");			// after RuleRow insert two blank elements
			
			// rebuild the sqlExp array 
			buildRuleConditions(currentRow)
			
			// refresh the rule conditions table
			var rules=document.getElementById('rulesDiv')
			buildFilterEditor(currentRow, rules)
			
			// set to the new inserted row
			document.getElementById('sql1:'+newRuleRow).value=''; 
			document.getElementById('sql2:'+newRuleRow).value='';
			document.getElementById('sql3:'+newRuleRow).value='';
			document.getElementById('sql4:'+newRuleRow).value='';
			e_out = rowNo[0]+":"+newRuleRow;
		}
	}
	document.getElementById(e_out).focus();
	
	// set the save button to Red
	document.getElementById('save').style.color = "#FF0000";
	
	Event.stop(evt);
}
function updateSqlExpressions(e_out)
{
	var rowNo = e_out.split(':')
	var row = parseInt(rowNo[1]);
	var lastCell1 = 'sql1:'+row;
	var lastCell2 = 'sql2:'+row;
	var lastCell3 = 'sql3:'+row;
	var lastCell4 = 'sql4:'+row;
	
	// fetch the data from the data entry fields
	var cell1Value = document.getElementById(lastCell1).value		// attributes
	
	// Make sure the mathematic symbols have spaces either side
	cell1Value = cell1Value.replace(/\+/g, " + ");
	cell1Value = cell1Value.replace(/\-/g, " - ");
	cell1Value = cell1Value.replace(/\//g, " / ");
	cell1Value = cell1Value.replace(/\*/g, " * ");
	cell1Value = cell1Value.replace(/  /g, " ");
	//alert("attributes = "+cell1Value)
	document.getElementById(lastCell1).value = cell1Value ;
	
	var obj1 = document.getElementById(lastCell2)
	var cell2Value = obj1.options[obj1.selectedIndex].value;		// logical operator
	//alert("operator = "+cell2Value)

	var cell3Value = document.getElementById(lastCell3).value		// user input value
	//alert(cell3Value);
	
	if (cell3Value != 'undefined' )
	{
		// make sure that the submitted value is quoted
		//alert('OK here we go = '+cell3Value)
		cell3Value = cell3Value.replace(/\'/g, "");
		cell3Value = cell3Value.replace(/\"/g, "");
		cell3Value = "'"+cell3Value+"'";
		document.getElementById(lastCell3).value = cell3Value;
		//alert("input value = "+cell3Value);
	}
	
	
	var obj2 = document.getElementById(lastCell4)
	var cell4Value = obj2.options[obj2.selectedIndex].value;		// concatibation selection
	
	// now update all data in the last editable row into array	
	sqlExpressions[row] = cell1Value+"|"+cell2Value+"|"+cell3Value;
	//alert(sqlExpressions[row]);
	sqlExpressions[row+1] = cell4Value;	
	
	// update the sqlExpTemp array
	var num = sqlExpressions.length
	sqlExpTemp[currentRow] = '';
	for (var i=0; i<num-1 ; i=i+2)
	{	
		if(i==0)
		{	
			//alert(">"+sqlExpressions[i+1]+"<")
			if(sqlExpressions[i+1] == ' ' || sqlExpressions[i+1] == null || sqlExpressions[i+1] == 'None'){var end = '';}
			else {var end = ","+sqlExpressions[i+1];}
			//alert ('end = '+end)
			sqlExpTemp[currentRow] = sqlExpressions[i]+end;	
		}
		else	
		{	
			//alert(">"+sqlExpressions[i+1]+"<")
			if(sqlExpressions[i+1] == ' ' || sqlExpressions[i+1] == null || sqlExpressions[i+1] == 'None'){var end = '';}
			else {var end = ","+sqlExpressions[i+1];}
			//alert ('end = '+end)
			sqlExpTemp[currentRow] += ","+sqlExpressions[i]+end;	
		}
		//alert('new sqlExpTemp row = '+sqlExpTemp[currentRow]);
	}
	//alert('new sqlExpTemp row = '+sqlExpTemp[currentRow]);

}
function saveTitle(evt)
{
	// check that nameData is less than 30 chars
	nameData = document.getElementById('sldName').value;
	if(nameData.length >60)
	{	
		alert ('Only 60 characters allowed for the Name field'); 	
		document.getElementById('sldName').value='';
		document.getElementById('sldName').focus();	
		Event.stop(evt);
		return;
	}
	
	// update the edit legend title
	titleData = document.getElementById('sldTitle').value;
	sldAbstract = document.getElementById('sldAbsNo').value;
	var editor = document.getElementById('legendt');
	checkRemoveObject('editLegendTitle');
	var editTitle = document.createElement('div');
	var titleText = document.createTextNode(nameData);
	editTitle.id = 'editLegendTitle';
	editTitle.setAttribute('id','editLegendTitle')
	editTitle.appendChild(titleText);
	editTitle.className="editTitle";
	
	// reset the title for Title's the boxover
	//var title = document.getElementById('editLegendTitle')
	editTitle.setAttribute("title", "header=[DemographicDrape Description] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+sldAbstract+"]");
	editTitle.title="header=[DemographicDrape Description] cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+sldAbstract+"]";
	editor.appendChild(editTitle);
	Event.stop(evt);
}
function saveAbstract(evt)
{
	var e_out = getThisId(evt)
	var elNo = e_out.split(":");
	var testAbs = document.getElementById(e_out).value;
	
	// squeeze out all the spaces and if nothing left we know its empty
	testAbs = testAbs.replace(/ /g, "");
	//alert(testAbs.indexOf('.'))
	//testAbs = testAbs.replace(/	/g, "");
	//alert ('testAbs = >'+testAbs+'<');
	if (testAbs == '')
	{	RuleAbstract[currentRow] = ''}
	else
	{	RuleAbstract[currentRow] = document.getElementById(e_out).value; }
	//alert('cleaned abstract = >'+RuleAbstract[currentRow]+'<');
	Event.stop(evt);
}

function saveRuleName(evt)
{
	var e_out = getThisId(evt)
	var elNo = e_out.split(":");
	RuleName[currentRow] = document.getElementById(e_out).value;
	var ruleId = "rule:"+currentRow;
	document.getElementById(ruleId).firstChild.nodeValue = RuleName[currentRow];
	var titleCell = document.getElementById('titleNo').value;
	if(titleCell == '')
	{	
		document.getElementById('titleNo').value = document.getElementById(e_out).value;
	}
	document.getElementById('titleNo').focus();
	Event.stop(evt);
}
function saveRuleTitle(evt)
{
	var e_out = getThisId(evt)
	var elNo = e_out.split(":");
	RuleTitle[currentRow] = document.getElementById(e_out).value;
	document.getElementById('absNo').focus();
	//alert('nrew rule title = '+RuleTitle[currentRow]);
	Event.stop(evt);
}

//-------------------------------------------------------------------------------------------------//
// this moves the rule data selected by clicking a rule on the editing legend into the editing form
	function populateEditor(evt)
	{
		// alert('on entry CurrentRow = '+currentRow+' PreviousRow = '+previousRow)
		
		// switch previous selection highlights back to normal
		//update=true;
		// alert ("previousrow = "+previousRow)
		if (previousRow >= 0)
		{
			var prevId1 = "rule:"+previousRow;
			var prevId2 = "tdBox:"+previousRow;
			document.getElementById(prevId1).className='unselectedItem';
			document.getElementById(prevId2).className='unselectedItem';
			//document.getElementById(prevId1).style.border='1px solid gray';
			//document.getElementById(prevId2).style.border='1px solid gray';
		}
		// highlight this row now being selected to be edited
		var e_out = getThisId(evt)
		var numb = e_out.split(":");
		var no = numb[1];			// editor array number
		var id1="tdBox:"+no;
		var id2="rule:"+no;
		document.getElementById(id1).className='selectedItem';
		document.getElementById(id2).className='selectedItem';
		//document.getElementById(id1).style.border='3px solid red';
		//document.getElementById(id2).style.border='3px solid red';
		
		// Update the Rule Name input box from arrays
		var Cell = "nameNo";
		document.getElementById(Cell).value = RuleName[no];
		
		// Update the Rule Title Name
		var Cell = "titleNo";
		document.getElementById(Cell).value = RuleTitle[no];
		
		// Update the Rule Abstract
		var Cell = "absNo";
		document.getElementById(Cell).value = RuleAbstract[no];

		// copy sqlExp into sqlExpTemp array
		for (var i=0; i<sqlExp.length; i++ )
		{		sqlExpTemp[i]=sqlExp[i]	}
		var rules=document.getElementById('rulesDiv')
		
		// now build the filter editor
		buildFilterEditor(no, rules);

		// update Rendering Rules 
		updateRenderRules(no);
		
		// set the current row to the selected row
		currentRow=no
		previousRow=no;
		lastCell =  "sql1:0";
		document.getElementById('sql1:0').className='selectedItem';
		document.getElementById('sql2:0').className='selectedItem';
		document.getElementById('sql3:0').className='selectedItem';
		document.getElementById('sql4:0').className='selectedItem';
		//document.getElementById('sql1:0').style.border='3px solid red';
		//document.getElementById('sql2:0').style.border='3px solid red';
		//document.getElementById('sql3:0').style.border='3px solid red';
		//document.getElementById('sql4:0').style.border='3px solid red';
		setOpacity(document.getElementById('sql5:0'),100);

		// make sure the colour of the save button is set to black 
		document.getElementById('save').style.color = "#000000";

		Event.stop(evt);
		return;
	}

//------- this function will populate the render rules area from arrays for the currentRow in the array -----//
	function updateRenderRules(currentRow)	
	{	
		// Update the minSacle factor 
		var Cell = 'minScale';
		document.getElementById(Cell).value = ruleMinScale[currentRow];
		if(document.getElementById('minScaleAll')){document.getElementById('minScaleAll').checked=false;}
		
		// Update the maxScale factor
		var Cell = 'maxScale';
		document.getElementById(Cell).value = ruleMaxScale[currentRow];
		if(document.getElementById('maxScaleAll')){document.getElementById('maxScaleAll').checked=false; }

		// Update the rendering rules area for area fill color
		var Cell = "editFill";
		if (fillColor[currentRow] != null)
		{	document.getElementById(Cell).style.backgroundColor = fillColor[currentRow];
			document.getElementById(Cell).value = '';
			if(fillColor[currentRow] && fillColor[currentRow] != 'transparent')
			{
				var code = fillColor[currentRow].split('#');
				document.getElementById(Cell).value = code[1];
			}
		}
		else
		{	document.getElementById(Cell).style.backgroundColor = "transparent";}
		if(document.getElementById('editFillAll')){document.getElementById('editFillAll').checked=false; }
		
		// Update the redering rules area for area fill pattern
		var Cell = "editPattern";
		if(fillPattern[currentRow] != null)
		{	document.getElementById(Cell).style.backgroundImage = "url("+fillPattern[currentRow]+")";}
		else
		{	document.getElementById(Cell).style.backgroundImage = "none";}
		if(document.getElementById('editPatternAll')){document.getElementById('editPatternAll').checked=false; }

		// Update the rendering rules for line color
		var Cell = "editLine";
		if(lineColor[currentRow] != null)
		{	document.getElementById(Cell).style.backgroundColor = lineColor[currentRow];
			document.getElementById(Cell).value = '';
			if(lineColor[currentRow] && lineColor[currentRow] != 'transparent')
			{
				var code = lineColor[currentRow].split('#');
				document.getElementById(Cell).value = code[1];
			}
		}
		else
		{	document.getElementById(Cell).style.backgroundColor = 'transparent';}
		if(document.getElementById('editLineAll')){document.getElementById('editLineAll').checked=false; }

		// Update the rendering rules for line Thickness
		var Cell = "bordThick";
		var select = document.getElementById(Cell);
		if(lineWeight[currentRow] != null)
		{	select.selectedIndex = lineWeight[currentRow]; }
		else
		{	select.selectedIndex = 0	}
		if(document.getElementById('bordThickAll')){document.getElementById('bordThickAll').checked=false; }

		// Update the rendering rules for Fill Opacity
		var Cell = "fillOp";
		var optRow = 10 - (fillOpacity[currentRow] * 10);
		var select = document.getElementById(Cell);
		if(fillOpacity[currentRow] != null)
		{	select.selectedIndex = optRow; }
		else
		{	select.selectedIndex = 0	}
		if(document.getElementById('fillOpAll')){document.getElementById('fillOpAll').checked=false; }

		// Update the rendering rules for line Opacity
		var Cell = "bordOp";
		var optRow = 10 - (lineOpacity[currentRow] * 10);
		var select = document.getElementById(Cell);
		if(lineOpacity[currentRow] != null)
		{	select.selectedIndex = optRow; }
		else
		{	select.selectedIndex = 0	}
		if(document.getElementById('bordOpAll')){document.getElementById('bordOpAll').checked=false; }

	}
// this function will add the pick list of Attributes to the target object (holding Div)
function createAttribPicker(holderDivObj)
{	
	// create the attribute picklist
	var logicCell1 = document.createElement('td');
	logicCell1.style.width='200px';
	logicCell1.style.height='20px';
	//logicCell1.style.border="1px solid red";
	logicCell1.id='attsTd';
	logicCell1.setAttribute('id','attsTd');
	var num = attNames.length;
	
	// create the Select object
		var select = document.createElement('select');
		select.className='selectBox';
		select.style.verticalAlign='middle';
		select.style.width='250px';
		select.setAttribute('size','1');
		select.setAttribute('width','70');
		select.id='attribs';
		select.setAttribute('id','attribs');

			// put a -- Select -- row in first option
			var opt = document.createElement('option');
			opt.style.zIndex='5400';
			opt.value='select';
			var optText = document.createTextNode("--- select from list ---");
			opt.appendChild(optText);
			opt.style.width="100%";
			opt.title = ('select from the available list of attributes below');
			select.appendChild(opt)				

			// now create the Option rows
			for (var i=0; i<num ; i++ )
			{		
				var opt = document.createElement('option');
				opt.value=attNames[i];
				var optText = document.createTextNode(attNames[i]);
				opt.appendChild(optText);
				opt.style.width="100%";
				opt.title= tooltip[i];
				opt.setAttribute("title", tooltip[i]);
				//var boxover = "header=[Attribute Information] cssbody=[dvbdy12] cssheader=[dvhdr12] body=["+tooltip[i]+"]"
				//opt.title= boxover;
				//opt.setAttribute("title", boxover);
				select.appendChild(opt)
			}
		bindEvent(select, 'change', addCond, 'false');
		//form.appendChild(select);
	logicCell1.appendChild(select);
	holderDivObj.appendChild(logicCell1)
}

// this function will add the pick list of Themes to the target object (holding Div)
function createThemePicker(holderDivObj, currentTheme)
{	
	// create the attribute picklist
	var logicCell1 = document.createElement('td');
	logicCell1.style.width='165px';
	logicCell1.style.height='20px';
	//logicCell1.style.border="1px solid red";
	logicCell1.id='themesTd';
	logicCell1.setAttribute('id','themesTd');
	
	// create the Select object
		var select = document.createElement('select');
		select.className='selectBox';
		select.style.verticalAlign='middle';
		select.style.width='165px';
		select.setAttribute('size','1');
		select.setAttribute('width','102');
		select.id='drapeTheme';
		select.setAttribute('id','drapeTheme');

			// get a list of themes and populate the pick list
			var themesObj = getThemeList();

			// now create the Option rows
			selIndex=0;
			for (var i=0; i<themesObj.length ; i++ )
			{		
				var opt = document.createElement('option');
				opt.value = themesObj[i].getAttribute('Name');
				var optText = document.createTextNode(themesObj[i].getAttribute('Name'));
				opt.appendChild(optText);
				opt.style.width="100%";
				opt.title= themesObj[i].getAttribute('Abstract');
				opt.setAttribute("title", themesObj[i].getAttribute('Name')+" : \n"+themesObj[i].getAttribute('Abstract'));
				//var boxover = "header=[Attribute Information] cssbody=[dvbdy12] cssheader=[dvhdr12] body=["+tooltip[i]+"]"
				//opt.title= boxover;
				//opt.setAttribute("title", boxover);
				select.appendChild(opt);
				if(themesObj[i].getAttribute('Name') == currentTheme){selIndex = i;}
			}
			// now set the currentTheme in the select box
			select.selectedIndex = selIndex;
			bindEvent(select, 'change', saveTheme, 'false');
		//form.appendChild(select);
	logicCell1.appendChild(select);
	holderDivObj.appendChild(logicCell1)
}
function saveTheme(evt)
{
	var selObj = document.getElementById(getThisId(evt))
	sldTheme = selObj.options[selObj.selectedIndex].value;
	//alert('new Current Theme = ' +sldTheme);
	removeOldDrape = true;
}

function getThemeList()
{
	//alert('layer name = '+layerName)
	// do a DescribeFeatureType request to get attribute schema
	// initialise the request
	ajaxRequest = null;
	var appsUrl = applicationBase+'cf/proxycall.cfm?'			// coldfusion version proxycall
	
	// set up the drapelist server request and get drapelist
	drapeService  = "url="+ meshBlocksBase.split("?")[0]+"&request=numaGetThemes";
	//alert(appsUrl+drapeService)
	ajaxRequest = fetchXml(appsUrl, drapeService, false, 'POST');
	var themeList = ajaxRequest.responseXML;
	var themeList = ajaxRequest.responseXML.getElementsByTagName("Themes"); // should only be one of these!
	var themes = themeList[0].getElementsByTagName("Theme");	
	//alert('themes = '+themes.length);

	// get the themes into arrays
	//for (var i=0; i<themes.length ; i++)
	//{
	//	alert(themes[i].getAttribute('Name')+" : "+themes[i].getAttribute('Abstract') )
	//}

	return themes;
}

