// ------------------------ function to get layer data from XML file into arrays -----------------
function getDrapeData(drapes)
{
	//alert('drapes = '+drapes)
	Datts= new Array();
	var query='';
	var fileForDelete = '';

	// Get the Drapelist XML file
	if(drapes == 'nuservbeta' || drapes == 'numapsService' || drapes == 'numaps' || drapes == 'nuserv')
	{
		// set up the proxy call
		var appsUrl = applicationRoot+'cf/proxycall.cfm?'			// coldfusion version proxycall
	 			
		// set up the drapelist server request and get drapelist
		drapeService  = 'url='+ meshBlocksBase.split('?')[0]+'&request=getnumadrapelist&accCode='+account+'&drapeclass=STANDARD';
		//alert(appsUrl+drapeService)
		ajaxRequest = fetchXml(appsUrl, drapeService, false, 'POST');
		
		// Find out how many Themes
		var drapesObj = ajaxRequest.responseXML.getElementsByTagName("Drapes"); // should only be one of these!
		var themes = drapesObj[0].getElementsByTagName("Theme");		
		//alert('number of themes available via DB = '+themes.length)
	}		
	else
	{
		// load the drapelist xml file into DOM from user specified file
		var query="?bruid="+new Date().getTime();		// this is to avoid browser cache issues
		//alert(applicationBase + drapes + query);
		ajaxRequest = loadXml(applicationRoot + drapes, query);
		
		// Find out how many Themes
		var drapesObj = ajaxRequest.responseXML.getElementsByTagName("Drapes"); // should only be one of these!
		var themes = drapesObj[0].getElementsByTagName("Theme");		
		//alert('number of themes available via XML = '+themes.length)
	}

	if (themes.length == 0) {return false;}
	var k=0;
	
	// now loop through each Theme collecting theme level data 
	for (l=0; l<themes.length; l++)
	{
		Theme= '';	Title= '';	Dir= ''; Layer='';	

		// get Theme level attributes
		Theme = themes[l].getAttribute ("name");	// name is the only mandatory attribute
		if (themes[l].getAttribute("title"))	{Title = themes[l].getAttribute("title"); }
		if (themes[l].getAttribute("abstract"))	{Title = themes[l].getAttribute("abstract");}// abstract will always overwrite Title
		if (themes[l].getAttribute("dir"))		{Dir = themes[l].getAttribute("dir"); }
		if (themes[l].getAttribute("layer"))	{Layer = themes[l].getAttribute("layer");}
		if (themes[l].getAttribute("wmslayer"))	{WmsLayer = themes[l].getAttribute("wmslayer");}
		
		// get each set of Drape Attributes
		var drapeObj = themes[l].getElementsByTagName("Drape");		
		if (drapeObj.length > 0)
		{
			// step through each Layer tag getting all the attribute elements
			for (i=0; i<drapeObj.length; i++)
			{
				// If a type attribute is present process this DDrape
				Dtype = ''; Dstyle = ''; Dname = '';  Dtitle = ''; WmsLayer= ''; Dfile = ''; DDrapeId = ''; Sldflag = '' ; Dopac = 1; SldLoc = ''; cacheLocation = ''; DDeditable=false;
				if(drapeObj[i].getAttribute('name'))	{Dname = drapeObj[i].getAttribute('name');}
				
				// process the Drape
				if(drapeObj[i].getAttribute('type') != '')	
				{	
					// get all attributes from xml file 
					Dtype = drapeObj[i].getAttribute('type');
												
					// get optional attributes
					if(drapeObj[i].getAttribute('name'))	{Dname = drapeObj[i].getAttribute('name');}
					if(Dname == 'NO NAME') {break;}
					
					if(drapeObj[i].getAttribute('title'))	{Dtitle = drapeObj[i].getAttribute('title');}
					if(drapeObj[i].getAttribute('layer'))	{WmsLayer = drapeObj[i].getAttribute('layer');}
					if(drapeObj[i].getAttribute('file'))	{Dfile = drapeObj[i].getAttribute('file');}
					
					// for database generated drapelist attributes
					if(drapeObj[i].getAttribute('canuseSLD'))	{Sldflag = drapeObj[i].getAttribute('canuseSLD');}
					if(drapeObj[i].getAttribute('drapeEditable'))	{DDeditable = drapeObj[i].getAttribute('drapeEditable');}
					if(drapeObj[i].getAttribute('sldfile'))		
					{	
						//turn SLD location into a file URL for editing purposes
						SldLoc = drapeObj[i].getAttribute('sldfile');
						SldLoc = SldLoc.replace(/\\/g, "/");
						Dfile = SldLoc.split('sld/')[1];
						cacheLocation = Dfile;
					}

					// this is when a style is specified rather than a SLD
					if(drapeObj[i].getAttribute('style'))	
					{	
						if(drapeObj[i].getAttribute('style') != 'default') // skip past default styles
						{	Dstyle = drapeObj[i].getAttribute('style');	}
					}

					if(drapeObj[i].getAttribute('numapsDrapeID'))	
					{	
						// Insert the DID: string to signify a DrapeID
						DDrapeId = "DID:"+drapeObj[i].getAttribute('numapsDrapeID'); 
					}
					//alert('layer Sld = '+WmsLayer+'   style = '+Dstyle)
					//alert('sld = '+SldLoc+ '  Drape Id = '+DDrapeId)
					//alert ('Dfile = '+Dfile)

					// now just get the SLD details if available and if needed
					if(Dfile != 'coming' && Dfile != '' && (Dtitle == '' || WmsLayer == '' || Dname == '' || Dopac == ''))
					{
						//alert('opening sld = '+applicationBase + njsSldDir + Dfile)
						getSldInfo(applicationBase + njsSldDir + Dfile)
						if (sldAbstract != '')	{Dtitle = sldAbstract;}
						if (layerName != '')	{WmsLayer = layerName;}
						if (nameData != '')		{Dname = nameData;}
						if (opValue != '')		{Dopac = opValue;}
					}
					if(Dfile == '')
					{
						Dfile = 'getLegendGraphic';
						//if(Dname == '') {	Dname = Dstyle;	} 
					}
					
					// now stuff into the multidimension array string
					//alert('DDrapeId = '+DDrapeId)
					Datts[k] = WmsLayer+'|'+Theme+"|"+Title+"|"+Dir+'|'+Layer+'|'+Dname+"|"+Dfile+"|"+Dstyle+"|"+Dtype+"|"+Dtitle+'|'+Dopac+'|'+SldLoc+'|'+DDrapeId+'|'+DDeditable;
					//alert(Dname+"\n"+Datts[k])
					k=k+1;
				}
				else
				{ 
					alert('DDrape does not have a type set - skipping '+Dname+' DDrape')	
				}
			}
		}
	}
/*
	for (var i=0; i<Datts.length; i++)
	{		
		alert('attribute = '+Datts[i]);	
	}
*/
	//alert (numDrapes);
	return true;
}

// -------------------- function to get list of drapes and build a user Select List ---------------------//
function buildDrapeList(kill)
{
	//alert('kill Highlight = '+ kill)
	//if(!getDrapeData(drapes)){alert('error in '+drapes+' file'); return false;}
	
	// now loop through all the themes/DDrape elements in DDrape Arrays
	var k=-1;
	var kk=0;
	Tree= new Array();
	var themeName = ''; var themeAvail = '';

	// please note that every row in the Datts array contains Theme and DDrape information
	// you need to recognise when a DDrape's theme changes to create a Theme level in tree
	//alert(Datts.length)
	for (var ii=0; ii<Datts.length; ii++)
	{
		// bust up the attributes into atts array
		var atts = Datts[ii].split("|")

		// If this is a new Theme then create the tree branch
		if(atts[1] != themeName) 
		{	
			k=k+1;
			kk=kk+1;
			themeName = atts[1]
			var themeTitle = atts[2];
			
			// look ahead to see if there are no valid DDrapes for this theme
			themeAvail = checkForDdrapes(ii, themeName);
			
			// save the layer name for swapSLD
			var back = kk;
			var themeUrl = "#";
				
			// if the buundle is not available to this user grey out the Theme level
			if (atts[8] != 'free' && atts[8] != 'FreeDrapes'  && atts[8] != 'subscribed' && atts[8] != 'DrapeStd') 
			{
				themeUrl = 'javascript:swapSld("", "", "coming", "", "", false);'
			}

			// Now build the Theme level in Tree
			Tree[k] = kk+"|0|"+themeName+"|"+themeUrl+"|"+themeTitle+"|"+themeAvail;
		}

		// conntinue on to build subordinate tree branches within a Theme
		k=k+1;
		kk=kk+1;
		var filename = atts[6];
		var dname = atts[5];
		var type = atts[8];
		var title = atts[9]; // this is the abstract
		var style = atts[7];
		var drapeid = atts[12];
		var editable = atts[13];
		//alert(dname+" : "+editable)
		//alert('Abstract for '+dname+'\n'+title) ;
		//alert(style)
		//alert('style = '+ style+ " type = "+type+ " file = "+filename+" drapeid = "+drapeid)

		// for typical free/subscribed SLD defined DDrape
		if ((type == 'subscribed' || type == 'free' || type == 'DrapeStd' || type == 'FreeDrapes' ) && (style == 'default' || style == '') && (filename != '' ) && editable) 
		{	
			//alert('available = '+drapeid+' and style = '+style)
			var highlight = true; 
			if(kill) 
			{	
				var swapper = 'javascript:if(DrapeHighlight){DrapeHighlight.destroy();	} resetSearchSelections(); swapSld("'+filename+'", "'+style+'",  "'+type+'", "'+drapeid+'", '+highlight+', '+gfiDoubleClick+');';
			}
			else 
			{	
				var swapper = 'javascript: resetSearchSelections(); swapSld("'+filename+'", "'+style+'", "'+type+'", "'+drapeid+'", '+highlight+', '+gfiDoubleClick+'); if(collectLayer){/*map.setLayerZIndex(collectLayer, 1500);*/ collectLayer.setZIndex(map.Z_INDEX_BASE[\"Popup"\] -8000);}';
			}
		}
		
		// for unsubscribed DDrape or one with not enough information
		else if (type == 'unsubscribed' || type == 'coming' || filename == '' || (style != 'default' && style != '') || !editable)
		{
			//alert('unavailable = '+drapeid+' and style = '+style)
			//k=k+1;
			//kk=kk+1;
			var highlight = false;
			if(kill) 
			{	
				var swapper = "javascript:if(DrapeHighlight){DrapeHighlight.destroy(); } resetSearchSelections(); swapSld('"+filename+"', '"+style+"', '"+type+"', '"+drapeid+"', "+highlight+", "+gfiDoubleClick+");";
			}
			else 
			{	
				var swapper = "javascript:resetSearchSelections(); swapSld('"+filename+"', '"+style+"', '"+type+"', '"+drapeid+"', "+highlight+", "+gfiDoubleClick+"); if(collectLayer){/*map.setLayerZIndex(collectLayer, 1500);*/ collectLayer.setZIndex(map.Z_INDEX_BASE['Popup'] -8000);}";
			}
		}

		// Now write out the DDrape tree level
		Tree[k] = kk+"|"+back+"|"+dname+"|"+swapper+"|"+title+"|"+highlight;
		//alert(Tree[k])
		
	totalTreeLength = kk
	}
/*	
	//------ Debugging -----
	
	for (var z = 0; z< kk; z++)
	{
		alert(Tree[z]);
	}
*/
}

// this fiunction just looks ahead in the array to make sure there are available DDrapes in a theme
function checkForDdrapes(ii, tName)
{
	var goodDrapes = 0
	// look at all DDrape rows from here until Theme changes
	for (var j=ii; j<Datts.length; j++ )
	{
		var jatts = Datts[j].split("|");
		if (jatts [1] == tName)
		{
			if (jatts[8] == 'subscribed' || jatts[8] == 'free' || jatts[8] == 'DrapeStd' || jatts[8] == 'FreeDrapes')
			{
				goodDrapes++;
			}
		}
		else
		{	break;	}
	}
	// now return true if there is more than zero available Ddrapes
	if(goodDrapes > 0) {return true;}
	else {return false;}
}


//---------------------- Update the database with the new DDrape definition  ---------------------
function saveNewDrapeFile(newFileName)
{
	//alert('new file in saveNewDrapeFile= '+newFileName)
	
	if(newFileName == '' || newFileName == null) {return;}
	// get file info from filename
	var fileParts = newFileName.split('/');
	var path = fileParts[1]
	var drapePath = fileParts[0]+'/'+path+'/';
	var drapeFile = fileParts[2];
	var fileParts = newFileName.split('.');
	var drapeExt = fileParts[1];
	var newDrapeId = ''
	
	// get the entered name from the user form
	var handle = document.getElementById('collName').value;
	var saveFileName = drapePath+handle.replace(/ /g, "_")+'.'+drapeExt;
	var newDrapeFileName = path+'/'+handle.replace(/ /g, "_")+'.'+drapeExt;
	var fullDrapeFileName = applicationBase+njsResourceDir+saveFileName;

	// check if already exists on server here;
	//alert('checking for new DDrape name = '+saveFileName)
	if (filePresent(saveFileName))
	{ 
		if(!confirm ('"'+handle+'" already exists.\nIf you continue you will overwrite this the existing DemographicDrape.\n\n Do you wish to continue?'))
		{
			document.getElementById("collName").focus();
			document.getElementById("collName").value='';
			return;
		}
	}
	// strip off the leading newSld and the trailing date stamp
	var parts = newFileName.split('_');
	var oldDrapeName='';

	// get and reconstruct the embedded source Ddrape SLD name
	if(parts.length > 1)
	{
		for(var i = 0;	i < parts.length-1 ; i++)
		{
			if(i == 1){oldDrapeName = parts[i];}
			else if(i > 1 ){oldDrapeName = oldDrapeName+'_'+parts[i];}
		}
	}
	
	oldDrapeName = drapePath + oldDrapeName + "." + drapeExt;
	oldDrapeFileName = oldDrapeName.replace(/sld\//, '');
	//alert('old DDrape Filename = '+oldDrapeFileName);
	
		
	// replace the new SLD file name with the destination filename on the server
	var source = '/' + njsResourceDir + newFileName; 
	var destination = '/' + njsResourceDir + saveFileName;

	if(!replaceFileCF(source, destination) ){alert('error replacing existing file');}

	// now make the form invisible
	document.getElementById('formHolder').style.display='none';
	
	// if drapelist from data base then update the database
	if(drapes == 'nuservbeta' || drapes == 'numapsService' || drapes == 'numaps' || drapes == 'nuserv')
	{	
		// set putstyles to false so that they can't write a new style
		putStyles=false;
		//alert('updating Numa Drapes DB')
		updateNumaDrapes(oldDrapeFileName, newDrapeFileName);	
	}

	// this will go back to the source and recreate the DrapeTree
	buildTheDrapePickaTree();
		
	// get data for searching
	prepareSearch();
	genLoadStatus('', false);
	loaded=true;
}

function updateNumaDrapes(oldDrapeFileName, newDrapeFileName)
{
	//alert(oldDrapeFileName)
	//alert(newDrapeFileName)
	
	// set up the parameters needed to create a database Drape record xxx
	var appsUrl = applicationBase+'cf/proxycall.cfm?'			// coldfusion version proxycall

	// switch file and path to location syntax
	var sldLocationFormat = newDrapeFileName.replace(/\//g, '\\');

	//if old and new files & namedata of both SLDs are the same assume an overwrite of exiting DDrape
	var overwriteSwitch = 'false';
	if(oldDrapeFileName == newDrapeFileName && checkForSameNamedata(oldDrapeFileName, newDrapeFileName))
	{		overwriteSwitch = 'true'; }
	
	var accnt = '';
	if(account!=''){accnt = "&accCode="+account;}

	// set up the drapelist server request and get drapelist
	drapeService  = "url="+ meshBlocksBase.split("?")[0] +
		"&request=numaPostSld&sld="+sldLocationFormat+
		accnt +
		"&Overwrite="+overwriteSwitch +
		"&putstyle="+putStyles;
	
	// run the update transaction
	//alert(appsUrl+drapeService)
	ajaxRequest = fetchXml(appsUrl, drapeService, false, 'POST');
	var result = ajaxRequest.responseText;
	//alert('result = '+result);
}

function checkForSameNamedata(oldDrapeFileName, newDrapeFileName)
{	
	// get the DDrape name from the original DDrape
	getSldInfo(applicationBase+njsSldDir+oldDrapeFileName);
	var oldName = nameData;
	getSldInfo(applicationBase+njsSldDir+newDrapeFileName);
	var newName = nameData;	
	//alert(newName +", "+oldName);

	if(newName == oldName) {return true;}
	else {return false;}
}

// This will update the xml control file with the new DDrape
function updateDrapeListFile(drapename, newDrape, position)
{
	// set up the php url
	var parts = drapename.split('/');
	var Url = njsResourceDir + 'insertNewDrape.php';
	
	// set up the parameters
	var params = '?file='+parts[1];
	params += '&datts='+newDrape;
	params += '&pos='+position;

	// do the work
	makeFile(applicationBase+Url, params, false, 'GET');
}

// ----------- update the Datts array -----------
function updateDatts (oldDrapeFileName, newDrapeFileName, oldName, newName, newDrapeId, oldTheme, newTheme)
{	
	// make sure you have a DDrape name to locate in Datts array
	if (newName == '' || newName == null)
	{	getSldInfo(applicationBase+njsSldDir+oldDrapeFileName); 
		newName=nameData;
	}

	// now get the new Abstract and old drape name from the new SLD
	if (oldName =='' || oldName == null && oldDrapeFileName != newDrapeFileName)
	{	getSldInfo(applicationBase+njsSldDir+newDrapeFileName);
		var newAbstract = sldAbstract;
		oldName=nameData;
	}
	
	// Update the old Datts Array with the new DDrapes data 
	var newDrapeDatts = []; var found=false;
	//alert('old Theme = '+oldTheme+' -- old Drape = '+oldName);
	//alert('new Theme = '+newTheme+' -- new Drape = '+newName);

	loop:
	for (var i=0; i<Datts.length; i++ )
	{
		var DattsParts = Datts[i].split('|')

		// If the same DDrape being updated
		if(DattsParts[5] == oldName )
		{
			// take a copy of the Datts array of this old Ddrape 
			newDrapeDatts = DattsParts;
			newDrapeDatts[1] = newTheme;
			newDrapeDatts[5] = newName;
			newDrapeDatts[6] = newDrapeFileName;
			newDrapeDatts[9] = newAbstract;
			var parts = newDrapeDatts[11].split('/sld/');
			newDrapeDatts[11] = parts[0]+"/sld/"+newDrapeFileName;
			newDrapeDatts[12] = newDrapeId;
			//alert(newDrapeDatts);

			// encode into a string element 
			for (k=0; k<DattsParts.length ; k++)
			{
				if(k == 0) {var newDrapeString = DattsParts[0];}
				else {newDrapeString = newDrapeString+'|'+DattsParts[k];}
			}

			// update existing Ddrape or insert the new one
			if(oldDrapeFileName != newDrapeFileName)	// if filenames are not the same the same assume an insert
			{	Datts.splice(i+1, 0, newDrapeString); 		}
			else										// else filenames are the same so this is an update 	
			{	Datts[i] = newDrapeString;		}
			found = true;
			break loop;	// we're done
		}
	}

	// set up the return string
	if (found)
	{
		//alert('position = '+position)
		//alert(i+"::"+newDrapeString)
		return i+"::"+newDrapeString;	// this returns the location of the old DDrape element in Datts
	}
	else
	{
		alert('no matching DDrape name');
		return 'error';
	}
}
//------ function to do as Save or replace old with new ----------//
function swapNewSld(newFileName,  currentSld)
{
	//alert('DrapeId = '+drapeId)
	//alert('currentDrapeId = '+currentDrapeId)
	//alert('currentDrapeStyle = '+currentDrapeStyle)
	//alert('currentDrapeLayer = '+currentDrapeLayer)
	oldFileName = currentSld;
	//alert(oldFileName+' >> '+newFileName)

	// if old file name and new file name are not blank the proceed
	if(oldFileName == '' || newFileName == '') 
	{	return;	}
	else
	{	
		getSldInfo(applicationBase+njsSldDir+oldFileName);
		oldName = nameData;
		oldTheme = themeData.toString();
		getSldInfo(applicationBase+njsResourceDir+newFileName);
		newTheme = themeData.toString();
		newName = nameData;
	}
	//alert  ('old theme = '+oldTheme+"   new theme = "+newTheme)
	//alert  ('old name = '+oldName+"   new name = "+newName)
		//alert(newFileName)
	// make sure that a new file exists on disk
	if ( filePresent(newFileName) )
	{
		// check for attempts to change the Theme or Drape Name on a replace for a style based DDrape
		if(putStyles || !isEditable)  
		{
			if (confirm('Cannot Overwrite the existing DemographicDrape stored as a Style in the database.\nNor can you edit a DDrape that is owned by another user.\nBy proceeding you will create a brand new DemographicDrape. \n\nDo you wish to proceed?'))
			{
				// undertake a new DDrape create
				saveAs(newFileName);
				return;
			}
		}

		// check if user is changing the theme
		else if (newTheme != oldTheme || oldName != newName)
		{
			//alert  ("old theme = <"+oldTheme+">   new theme = <"+newTheme+">")
			if (confirm('Cannot Overwrite the existing DemographicDrape Theme/Name in the database.\nBy proceeding you will create a brand new DemographicDrape. \n\nDo you wish to proceed?'))
			{
				// undertake a new DDrape create
				saveAs(newFileName);
				return;
			}
		}

		// for a legitimate SLD file replace only
		else 
		{
			// make sure user agrees to do this because oldFileName file will get stamped on
			if (confirm('By proceeding you will PERMANENTLY replace the existing DDrape with the newly edited DDrape. \n\nAre you sure you wish to proceed ?'))
			{
				// Clear the cache for the temporary new file
				//alert(oldFileName+' >> '+newFileName)
				getAndPurgeDrapeCache()

				// remove any DDrape from then screen
				swapSld("", "", "", "", "", false);
				
				// rename the new filename to the old name
				newname = 'sld/'+oldFileName;
				existingFile = 	newFileName;
				if(!replaceFileCF('/' + njsResourceDir + existingFile, '/' + njsResourceDir + newname)){alert('could not rename the file');}
				
				// this will go back to the source and recreate the DrapeTree
				buildTheDrapePickaTree();
			
				// get data for searching
				prepareSearch();
				genLoadStatus('', false);
				loaded=true;

				return;
			
			}
		}
		
		
	}
}
function redraw(currentSld)
{
	// this will purge any Cache for the target DDrape	
	if(currentDrapeLayer == '' || currentDrapeLayer == 'undefined' || currentDrapeLayer == null)
	{	
		getSldInfo(applicationBase+njsSldDir+currentSld);
		currentDrapeLayer = layerName ;
	}
	oldFileName = currentSld;
	getAndPurgeDrapeCache();
	//purgeDrapeCache(currentSld); 
	DemoDrape.redraw(true); 
	document.getElementById("search").focus();
}

// this will go to the source defined in 'drapes' ,and build a new replacement DrapeTree	
function buildTheDrapePickaTree()
{
	
	// build the Drape tree
	//genLoadStatus('DDrapes Loading XML File ....', true);
	getDrapeData(drapes)
	
	//genLoadStatus('DDrapes Building Control ....', true);
	buildDrapeList(true);
	
	//genLoadStatus('DDrapes Building Tree ....', true);
	treeTitle = "DemographicDrapes Library";
	//alert(Tree)
	createTree('treeContainer',  Tree,  0,  0,  treeTitle,  false);

}

function getAndPurgeDrapeCache()
{
	// get the drape number from the ID
	var drapeNumber = currentDrapeId.split(":");
	var drapeNo = drapeNumber[1];
	
	// Clear the cache for the temporary new file
	if(newFileName != '')
	{
		var tempCache = newFileName.replace(/sld\//, '');	// trim off leading sld/
		tempCache = tempCache.replace(/.xml/, '');		// trim off trailing .xml
		purgeDrapeCache(tempCache, drapeNo);
		//alert('temp cache gone')
	}
	// save the name of the name of the new SLDs cache group
	//oldTempCache = cacheGroup[0];

	// if this is a style-based DDrape then kill off the Style Cache
	//alert('style = '+currentDrapeStyle)
	//alert('drape layer = '+currentDrapeLayer)
	if(currentDrapeStyle != '' && currentDrapeLayer != '')
	{
		//alert(currentDrapeLayer)
		//alert(currentDrapeStyle)
		var cacheLayer = currentDrapeLayer.replace(/:/g, '');
		cacheLayer = cacheLayer.replace(/_/g, '');
		var cacheStyle = currentDrapeStyle.replace(/ /g, '');
		cacheStyle = cacheStyle.replace(/_/g, '');
		cacheStyle = cacheStyle.replace(/-/g, '');
		var styleCache = cacheLayer+"/"+cacheStyle;
		purgeDrapeCache(styleCache, drapeNo);
		//alert('style cache gone');
	}
		else
	{
		// clear existing cache for the old SLD file
		var oldCache = oldFileName.replace(/.xml/, '')	// trim off trailing .xml
		//alert('oldCache = '+oldCache)
		purgeDrapeCache(oldCache, drapeNo);
		//alert('non style cache gone')	
	}
}



/*
function dropCache(cacheLocation, drapeIdKill) 
{ 
	// set up the request to drop the cache for this sld
	var cUrl = meshBlocksBase+"request=dropNumaCache&cacheItem="+cacheLocation+"&drapeid="+drapeIdKill;
	var ldr = new Image(); 
	ldr.onError = function() {alert('NUMAPS ERROR: Failed to connect');}
	ldr.src = cUrl;
	ldr = "";
}
*/

function purgeDrapeCache(cacheName, drapeNo)
{
	// clear existing cache for the old SLD
	cacheGroup = cacheName.split('.')[0];
	clearCache(cacheGroup, drapeNo);
}
function clearCache(cacheLocation, drapeIdKill)
{
	if(drapeIdKill)
	{	var request = 'request=dropNumaCache&cacheItem='+cacheLocation+'&drapeid='+drapeIdKill;	}
	else
	{	var request = 'request=dropNumaCache&cacheItem='+cacheLocation;	}

	// set up the request to clear out the cache for this sld via the coldfusion proxy server
	var appsUrl = applicationBase+'cf/proxycall.cfm?';					
	var query  = 'url='+meshBlocksBase.split('?')[0]+"&"+request;
	//alert('before the purge \n' +appsUrl+query)
	fetchXml(appsUrl, query, false);
}

// this is called in initialising function 
function prepareSearch()
{
	atts = [];
	attsStr = [];
	infoStr = [];

	// loop through all DDrapes and build a searchable array
	//alert(Datts.length)
	for(var i=0; i< Datts.length; i++)
	{
		// if a style then make it not accessible like the DDrape tree
		var accessible = true;
		atts = Datts[i].split("|");
		if(atts[7] != 'default' && atts[7] != '') 
		{	accessible = false;		}

		// build the search string for this DDrape
		var searchString = 	atts[5]+" :: "+atts[7]+" :: "+atts[9] ;
		attsStr[i] = searchString.toString(); 
		infoStr[i] = atts[5]+" :: "+atts[6]+" :: "+atts[9]+" :: "+atts[12]+" :: "+accessible+" :: "+atts[7];
	}
	
}

function doSearch(searchArray, keywordArray, caseSensitive)
{
	for (var n=0; n<keywordArray.length; n++)
	{
		// do the search here building up a list array elements of matched items
		for (var i=0; i<searchArray.length ; i++)
		{
			if(!caseSensitive) 
			{
				//alert(keywords[n])
				source = searchArray[i].toLowerCase();
				keyWd = keywordArray[n].toLowerCase();
			}
			else
			{
				source=	searchArray[i];
				keyWd = keywordArray[n];
			}
		
			if(source.search(keyWd) >= 0)
			{	
				//alert(keyWd+ ' found in element '+i)
				// check to see if this match is already in list
				var included = false;
				for(var m=0; m<list.length; m++)
				{	
					if(list[m] == i) {included = true; break;}
				}
				// if not included already then add it
				if(!included) {list.push(i); }
				//included = false;
			}
		}
	}
	return list;
}
function resetSearchSelections()
{
	if(currentSearchRowId != null)
	{	if(document.getElementById(currentSearchRowId))	
		{	document.getElementById(currentSearchRowId).className='noStylingOnItem';}	
		currentSearchRowId = null;
	}
}

// search the searchable arrays to find any DDrape/Territory with matching keyword
function findIt(keyword, holdingDivId, searchOriginator)
{
	//set up the searching and reporting arrays from the two different sources
	searchArray = []; 
	infoArray = [];
	resetSearchSelections();
	

	// for DDrape searching
	if(searchOriginator == 'ddSearchEngine') 
	{
		searchArray = attsStr;
		infoArray = infoStr;
	}
	// for Territory searching
	else if(searchOriginator == 'searchTerr') 
	{	
		searchArray = searchTarget; 
		infoArray = infoTarget;
	}
	// create a regular expression for highlighting
	var keywords = keyword.split('-');
	//alert(keywords)
	//alert(searchArray)
	
	// check for multiple keywords separated by hyphan and get caseSensitivity indicator
	var caseSensitive = document.getElementById('caseSens').checked;
	list = [];
	if(keywords.length > 0)
	{
		// do the search here building up a list array of matched DDrapes
		list = doSearch(searchArray, keywords, caseSensitive)
		//alert(list)

		// ------- write out number of matches line
		var row = document.getElementById('resultsSummary');
		checkRemoveObject('searchResultsSummary');
			var results = document.createElement('div');
			var textNode = document.createTextNode('--- There were '+list.length+' DDrapes found ---');
			results.appendChild(textNode);
			results.id='searchResultsSummary';
			results.setAttribute('id','searchResultsSummary');
			results.style.textAlign='center';
			results.style.fontWeight='bold';
		row.appendChild(results);
		row.style.display='block';
		
		// build the internal reporting div
		checkRemoveObject('searchResultsHolder');
		var searchTable = document.createElement('table');
		searchTable.id='searchResultsHolder'; 
		searchTable.setAttribute('id','searchResultsHolder');
		searchTable.style.marginLeft='5px';
		searchTable.style.marginRight='25px';
		searchTable.style.marginTop='5px';
		searchTable.style.marginBottom='5px';
		searchTable.style.width='100%';
		searchTable.style.height='100%';
		//searchTable.border='1';


			// build the table body
			var searchTableBody = document.createElement('tbody');
			searchTableBody.style.width='100%';
			searchTableBody.style.backgroundColor="#f8f8f8";
						
				// ------- write out spacer row
				var row = document.createElement('tr');
					var cell = document.createElement('td');
					cell.style.width='100%';
					row.appendChild(cell);
				searchTableBody.appendChild(row);
					
				// now list all the Object Names plus Abstracts
				for (var i=0; i<list.length ; i++)
				{
					// 
					var row = document.createElement('tr');
						var cell = document.createElement('td');
						//cell.style.width='100%';
						var DDparts = infoArray[list[i]].split(" :: ");
						//cell.className='unselectedItem';
						
						// highlight the keywords in text
						//DDparts[0] = showKeyword(DDparts[0], keywords);
						
						// ------- write out the Object Name
						//DDparts[0] = DDparts[0].replace(matchExp, "<b>$1</b>");
						//alert(DDparts[0])
						var textNode = document.createTextNode(DDparts[0]); // assumes first in array is its name
						cell.appendChild(textNode);
						cell.style.fontSize = '12px';
						cell.style.fontWeight='bold';
						cell.style.color='#840404';
						cell.style.paddingLeft='5px';
						cell.style.marginLeft='5px';
						
						// set interaction for DDrape searching
						if(searchOriginator == 'ddSearchEngine')  
						{
							cell.id='drapeName:'+i;
							cell.setAttribute('id','drapeName:'+i);
							var ddtype='Editable';
							if(!DDparts[4] || DDparts[4] == 'false'){cell.style.color='#3B52EB'; ddtype='Read Only';}
						
							// set the onclick event
							cell.style.textDecoration = 'underline';
							cell.style.cursor='pointer';
							cell.title='Click here to load this '+ddtype+' DDrape';
							bindEvent(cell, 'click', loadDrape, 'false');
							//bindEvent(cell, 'mouseover', highlightDdrape, 'false');
							//bindEvent(cell, 'mouseout', unhighlightDdrape, 'false');
						}
						else if(searchOriginator == 'searchTerr') 
						{
							cell.id='territoryName:'+i;
							cell.setAttribute('id','territoryName:'+i);
							cell.style.color='#3B52EB'
							
							// set the onclick event
							cell.title='Click here to load this Territory';
							bindEvent(cell, 'click', loadTerritory, 'false');
						}
						//cell.innerHTML = cell.innerHTML.replace(matchExp, "<b>$1</b>");
						row.appendChild(cell);
					searchTableBody.appendChild(row);

					// Optional Style row
					if(DDparts[5] > '' && searchOriginator == 'ddSearchEngine')
					{	
						var row = document.createElement('tr');
							var cell = document.createElement('td');
							var textNode = document.createTextNode("("+DDparts[5]+")");
							cell.appendChild(textNode);
							cell.style.color='#3B52EB';
							cell.style.width='100%';
							row.appendChild(cell);
						searchTableBody.appendChild(row);
					}
						
					// write out spacer row
					var row = document.createElement('tr');
						var cell = document.createElement('td');
						cell.style.width='100%';
						row.appendChild(cell);
					searchTableBody.appendChild(row);

					// highlight the keywords in text
					//DDparts[2] = showKeyword(DDparts[2], keywords);

					// write out the DDrape Abstract
					//DDparts[2] = DDparts[2].replace(matchExp,"<b>$1</b>");
					//alert(DDparts[2]);
					var textNode = document.createTextNode(DDparts[2]);
					cell.appendChild(textNode);
					cell.style.fontSize = '10px';
					cell.style.fontWeight = 'normal';
					cell.style.color='#3C3C3C';
					if(searchOriginator == 'searchDD')
					{
						cell.id='drapeAbs:'+i;
						cell.setAttribute('id','drapeAbs:'+i);
					}
					else
					{
						cell.id='territoryAbs:'+i;
						cell.setAttribute('id','territoryAbs:'+i);
					}
					//if(!DDparts[4] || DDparts[4] == 'false'){cell.style.color='#A3A3A3';}
					cell.style.whiteSpace='normal';
					//cell.innerHTML = cell.innerHTML.replace(matchExp, "<b>$1</b>");
					row.appendChild(cell);
				searchTableBody.appendChild(row);
				
				// write out spacer row
				var row = document.createElement('tr');
					var cell = document.createElement('td');
					cell.style.width='100%';
					row.appendChild(cell);
				searchTableBody.appendChild(row);
			}
			searchTable.appendChild(searchTableBody);
		document.getElementById(holdingDivId).appendChild(searchTable);
		document.getElementById('searchDetails').style.display = 'block';	
	}	
		
	
	/*
	var resultsContent = document.getElementById('searchResultsHolder').innerHTML;
	alert ('before \n'+resultsContent)
	for (var i=0; i<keywords.length; i++)
	{
		alert('highlighting keyword = '+keywords[i]);
		var target = '/'+keywords[i].toString()+'/ig';
		var substitute = "<span class='spanClass'>"+keywords[i].toString()+"</span>";
		
		alert(target +" >> "+substitute)
		//var targetObj = new RegExp(target)
		resultsContent = resultsContent.replace(target, substitute);
		//resultsContent = resultsContent.replace(/Mesh/g, substitute );
	}
	alert('after \n'+resultsContent);
	document.getElementById('searchResultsHolder').innerHTML = resultsContent;
	document.getElementById('searchDetails').style.display = 'block'
*/	
}
/*
//function showKeyword(data, keys)
//{
//	<p id="sometext">so, prasanth, what do you think of Webmasterworld? best place on the web?</p>
//<a href="#" onClick="highlight('sometext'); return false;">highlight</a>
//<script type="text/javascript">
function highlightString(el, keys) 
{
	strInput = document.getElementById(el).innerHTML;
	strInputClass = document.getElementById(el).className;
	// now concatinate the match strings
	match='';
	for (var i=0; i<keys.length; i++)
	{
		if (i==0)	{	match = match + keys[i];	}
		else { match = match+'|'+keys[i];}
	}
	alert('concatinated match = '+match)
	
	// now build the regular expression
	var matchExp = new RegExp("/\b("+match+")\b",'g');
	strInput.replace(matchExp,"<b>$1</b>")

	document.getElementById(el).innerHTML = "<pre class='"+strInputClass+"'>" + 
    strInput.replace(matchExp,"<b>$1</b>") + 
    "</pre>";
}


function highlightText(container, what, spanClass) 
{
	var content = container.innerHTML,
        pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'),
        replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
        highlighted = content.replace(pattern,replaceWith);
    return (container.innerHTML = highlighted) !== content;
}
*/
function loadDrape(evt)
{
	var e_out = getThisId(evt)
	var elNo = e_out.split(":");
	var parts = infoStr[list[elNo[1]]].split(" :: ");
	currentDrape = parts[1];
	
	// set the seleceted styles to this element
	if(currentSearchRowId != null)
	{	if(document.getElementById(currentSearchRowId))
		{document.getElementById(currentSearchRowId).className='noStylingOnItem';	}
	}
	currentSearchRowId = e_out;
	document.getElementById(e_out).className = 'selectedItem';
	
	// change the DDrape here
	swapSld('sld/'+parts[1], parts[5], '', parts[3], parts[4], gfiDoubleClick);
	
	// rebuild the DDrape tree here
	buildTheDrapePickaTree();
	//new Event.stop(evt);
}

function highlightDdrape(evt)
{
	var e_out = getThisId(evt)
	document.getElementById(e_out).className = 'selectedItem';

}
function unhighlightDdrape(evt)
{
	var e_out = getThisId(evt);
	document.getElementById(e_out).className = 'noStylingOnItem';
}

function loadTerritory(evt)
{
	var e_out = getThisId(evt);
	//alert('load Territory id = '+e_out)
	var elNo = e_out.split(":");
	var parts = infoTarget[list[elNo[1]]].split(" :: ");
	currentDrape = parts[1];

	// move selecetd file name up into current Territory display window
	textDisplay('selectedTerr',  parts[0]);
	
	// now go and display the newly selected Territory
	showTerritory(territoryFolder+parts[4])
		
	new Event.stop(evt);
}

function toggleSearch(id)
{
	searchOriginator = id;
	var searchButt = document.getElementById(id);
	if(searchButt.title == 'Launch search panel')
	{
	
		document.getElementById("searchHolder").style.display="block";
		document.getElementById("keyword").focus();
		searchButt.title = 'Close search panel';
		highlightDiv(id);
	}
	else
	{
		document.getElementById("searchHolder").style.display="none";
		searchButt.title = 'Launch search panel';
		normalDiv(id);
	}
}
