//------------- file upload section with Vectors ------------//
function zoomExtent(zoom)
{
	if(zoom)
	{
		// if zooming to whole collection 
		// calculate a buffer around the collection's bounding box by 30% of the biggest difference in x and y
		var deltaX = Math.abs(hiLng-loLng);
		var deltaY = Math.abs(hiLat-loLat);
		if (deltaX > deltaY){var buff = 0.3*deltaX;}
		else if (deltaY >= deltaX){var buff = 0.3*deltaY;}

		// apply the buffer amount and add zoom to new area
		loLat=loLat-buff; loLng=loLng-buff;	hiLat=hiLat+buff; hiLng=hiLng+buff;
		bounds = new OpenLayers.Bounds(loLng,loLat,hiLng,hiLat);
		
	}
	// this will zoom to bounds of collection/window	
	map.setCenter(bounds.getCenterLonLat(),map.getZoomForExtent(bounds));  
}

// this function will plot the XML file defined 'uploadFilename'
function fetchFile(csvFileHeaders)
{	
	progress(progressBarVer, 'Adding Points...', '') ;
	//alert('geocoding done')
	// turn on the listings/report and Marker Editing controls
	if(document.getElementById('amlOD')) 
	{	document.getElementById('amlOD').style.display='block';}
	if(fileUploaded)
	{	document.getElementById('saveDiv').style.display='block';}
	if(document.getElementById('editButtons0')) 
	{	document.getElementById('editButtons0').style.display='block';}
	
	// Get geocoded file defined in variable 'geocodedFile' from server
	var file = uploadFilename.split(".");
	geocodedFile = file[0]+"_"+stamp+".xml";
	geocodedCsv = file[0]+"_"+stamp+".csv";

	geocodedFile = 'useroverlays/'+geocodedFile;
	//alert(geocodedFile)
	if(!showUserPoints(geocodedFile, overrideAttribute, ''))
	{	
		progress(progressBarVer, 'Error on Load', ''); 
		initializeForms(); 
		return;
	}
	
	// zoom to extent or to window collection of uploaded points
	zoomExtent(zoom);
	
	// remove the processing indicators
	//document.getElementById('indicatorText').style.display='none';
	//if(document.getElementById('indicText')){document.getElementById('indicText').style.display='none';}
	
	progress(progressBarVer, '', '') ;
	//if(document.getElementById('eventsLogID')){document.getElementById('eventsLogID').styple.display='none';}

	// activate all the file control buttons
	document.getElementById('filterDiv').style.display='block';
	document.getElementById('pointTheme').style.display='block';
	document.getElementById('infoThemeDiv').style.display='block';
	if(document.getElementById('dragDiv')){document.getElementById('dragDiv').style.display='block';}
	if(document.getElementById('heatDiv')){document.getElementById('heatDiv').style.display='block';}
	document.getElementById('saveDiv').style.display='block';
	document.getElementById('killDiv').style.display='block';
}

function changeSource(Id)
{	
	killAllMarkers(); 	
	if(Id == 'lrad2')
	{
		// set up for the XML file input
		mouseup('lrad1');
		genLoadStatus('Fetching List of Files ...', true)
		makeTableSelectControl('useroverlays/preGeocoded/', 'publishedList', 'Addresses', 'name', 'abstract', 'upload');
		document.getElementById('fileEnter').style.display='none';
		document.getElementById('xmlEnter').style.display='block';
		progressBarVer = 'progBar2';
		document.getElementById(progressBarVer).style.display='none';
		genLoadStatus('', false);
		xmlPublished = true;
	}
	else 
	{ 
		// set up for the default csv file upload & geocode
		document.getElementById('fileEnter').style.display='block';
		document.getElementById('xmlEnter').style.display='none';
		progressBarVer = 'progBar';
		mouseup('lrad2');
		mousedown('lrad1');	
		xmlPublished = false;
	}
	// reset application panel buttons etc
	document.getElementById('amlOD').style.display='none';
	document.getElementById('saveDiv').style.display='none';
	if(document.getElementById('dragDiv')){document.getElementById('dragDiv').style.display='none';}
	document.getElementById('killDiv').style.display='none';
	document.getElementById('filterDiv').style.display='none';
	document.getElementById('pointTheme').style.display='none';
	document.getElementById('infoThemeDiv').style.display='none';
	if(document.getElementById('attributeHolder')){document.getElementById('attributeHolder').style.display='none';}
	document.getElementById('editButtons0').style.display='none';
	
}
function changeColor(id)
{
	var newColor = document.getElementById(id).value;
	showUserPoints(geocodedFile, overrideAttribute, newColor);
}

function getAttributeRanges(ajaxRequest)
{
	attributeName = [];
	attributeType = [];
	attributeRange = [];
	attributeAbstract = [];
	
	// get a list of Addresses
	addresses = ajaxRequest.responseXML.getElementsByTagName("Addresses");
	xmlTitle = addresses[0].getAttribute('name');
	xmlAbstract = addresses[0].getAttribute('abstract');

//	alert('title = '+xmlTitle);
//	alert('abstract = '+xmlAbstract);
	
	address = addresses[0].getElementsByTagName("Address");
	schemaAttribs = address[0].getElementsByTagName('Attribute');
	totalAttribs = addresses[0].getElementsByTagName("Attribute");
	if(addresses.length > 0)
	{
		//alert('total Address = '+address.length)
		//alert('total Scheme Attribs = '+schemaAttribs.length);
		//alert('total Attribs = '+totalAttribs.length)

		for(var n=0; n<schemaAttribs.length; n++)
		{
			// For each address get the list of Attribute elements
			hiVal = -9999999999; loVal = 9999999999;
			attributeName[n]= schemaAttribs[n].getAttribute('name');
			for(var i=n; i<totalAttribs.length; i=i+schemaAttribs.length)
			{
				// check if the attribute is numeric			
				//alert(totalAttribs[i].getAttribute('value'))
				attributeType[i] = 'nonNumeric';
				if(checkNumeric(totalAttribs[i].getAttribute('value')))
				{
					//alert('numeric')
					attributeType[i] = 'numeric';
					attributeAbstract[i] = totalAttribs[i].getAttribute('abstract');
					var value = parseFloat(totalAttribs[i].getAttribute('value'));
					if(value)
					{	// find hi and lo values
						if (value > hiVal) {hiVal = value;}
						if (value < loVal) {loVal = value;}
					}
				}
				else
				{
					//alert('non-numeric');
				}
			}
			hiVal = Math.ceil(hiVal);
			loVal = Math.floor(loVal);
			attributeRange[n] = loVal+":"+hiVal;		
		}
		//alert('att range = '+attributeRange)
		//alert('att name = '+attributeName)
		rangesDone = true;
	}
}


// -------------- this will plot all user uploaded data as markers ----------------
function showUserPoints(xmlFile, overrideAttribute, overrideColor)
{
	genLoadStatus('Fetching Data from XML ...', true, '');
	// if file uploaded make bottom buttons visibble or not
	document.getElementById('editButtons0').style.display='block';
	if(fileUploaded)
	{
		document.getElementById('editButtons5').style.display='block';
		document.getElementById('editButtons6').style.display='block';
	}
	else
	{
		document.getElementById('editButtons5').style.display='none';
		document.getElementById('editButtons6').style.display='none';
	}
	
	//turn off internal progress bar
	progress(progressBarVer, 'Fetching ...', '') ;
	//alert(progressBarVer)
	if(document.getElementById(progressBarVer)){document.getElementById(progressBarVer).style.display='none';}
	
	//alert('destroying userMarkers and their popups')
	if(popupFlag)	{	popup.destroy(); popup=null;	popupFlag=false;}
	if(userMarkers)	{	userMarkers.destroyFeatures(); 	userMarkers=null;}
	if(vectorLayer2){	vectorLayer2.destroyFeatures(); vectorLayer2=null;}
	valuesPresent=false;
	//alert('drag control 1 = '+dragItControl);


	// generate full url of xml file
	var file = applicationBase+"inc/"+xmlFile;
	//alert(file)
	var query="?"+new Date().getTime();
	loLat=999999999; hiLat=-999999999; loLng=99999999; hiLng=-99999999;

	// first check to see if file is available
	//pause(100)
	var testfile = file.split(applicationBase+'inc/')[1];
	//alert('checking for file = '+testfile)
	if(!filePresent(testfile)){alert('file not present'); return false;}

	// OK now go and fetch the data from geocoded file on server
	var pointsXml = applicationBase+'inc/'+testfile;

//alert(pointsXml+query)
	ajaxRequest = loadXml(pointsXml, query, false)
	if (!ajaxRequest.responseXML) 
	{
		if(document.getElementById('indicatorText')){document.getElementById('indicatorText').style.display='none';}
		if(document.getElementById('indicText')){document.getElementById('indicText').style.display='none';	}
		alert ("File Upload was unsuccessful");  
		return false; 
	}
	//genLoadStatus('Plotting Data ...', true, '')

	// determine ranges for all numeric columns
	if(!rangesDone) {getAttributeRanges(ajaxRequest); }
	//alert('show User Points : '+overrideAttribute)

	// reprocess all address occurrances
	addresses = ajaxRequest.responseXML.getElementsByTagName("Address");
	//alert('total addresses in XML = '+addresses.length)
	if(addresses.length > 0)
	{
		// get the Attribute occurrences for this Address 
		var attribute = addresses[0].getElementsByTagName("Attribute");

		// search for the attribute that is to be used for scaling
		subjectAtt = null;
		subjectRange = null;
		if(overrideAttribute != '')
		{
			for(var n=0; n<attribute.length; n++)
			{
				// check if this is the override attribute				
				if(overrideAttribute == attribute[n].getAttribute('name'))
				{	subjectAtt = attribute[n].getAttribute('name'); 
					subjectRange = attributeRange[n];
					break;	
				}
			}
		}
		if(subjectAtt == null)
		{	
			for(var n=0; n<attribute.length; n++)
			{
				// check if this is the default symbolVar
				if(attribute[n].getAttribute('type') == 'symbolVar')
				{	subjectAtt = attribute[n].getAttribute('name'); 
					subjectRange = attributeRange[n];
					break;
				}
			}
		}
		//alert('subject attrib = '+subjectAtt+'   &  subject range = '+subjectRange)
	}	

	//alert('select Att = '+subjectAtt+"  Range = "+subjectRange)

	// build the break points for this attribute
	loVal = 9999999999; hiVal = -9999999999;
	if(subjectRange)
	{
		loVal = subjectRange.split(":")[0];
		hiVal = subjectRange.split(":")[1];
		bdy=[];
	}
	
	if(hiVal !=  -9999999999 && loVal != 9999999999) //i.e. have changed from start 
	{
		// now calculate the four threshholds
		var delta = hiVal-loVal;
		var parts = uploadDivs;
		var aDiv = delta/parts;
		for (var z=0; z<parts ; z++ )
		{
			if(z==0) {bdy[z] = Math.ceil(loVal);}
			else{bdy[z] = Math.ceil(bdy[z-1] + aDiv);}
		}
		bdy[parts] = hiVal;
	}
	//alert(bdy)

 //alert('show User Points');

// ---------------Now we can process each Address point in source file-------------------//
	var k=0;
	sortedPoints = [];
	sortedAddress = [];
	range = [];
	sortedRange = [];
	sortedRecNo = [];
	sortedOldLoc = [];
	recNo = [];
	pointAddress = [];
	pointFeature = [];
	oldLocation = [];
	markerClass = [];
	markerColor = [];
	markerOpacity = [];

	ozBoxGeog = getBboxOfView(zoom, srs)
	//alert(ozBoxGeog)

	// if the user wants to see only for window then generate the smaller oxBox bounds
	var ozBoxGeog = [104.0,  -70.0,  180.0,  0.0];
	var pnt=[];
	if(!zoom) 
	{
		// get the bounds of the map window
		if (srs == "EPSG:900913")
		{
			// convert first point
			pnt[0] = map.getExtent().left;
			pnt[1] = map.getExtent().bottom;
			var point = google2geogs(pnt);
			loLeft = decodePoint(point);
			point1X = roundNumber(loLeft[0],8);
			point1Y = roundNumber(loLeft[1],8);

			// convert second point
			pnt[0] = map.getExtent().right;
			pnt[1] = map.getExtent().top;
			var point = google2geogs(pnt);
			hiRight = decodePoint(point);
			point2X = roundNumber(hiRight[0],8);
			point2Y = roundNumber(hiRight[1],8);

			// create a new ozBoxGeo
			ozBoxGeog = [point1X, point1Y, point2X, point2Y]
		}
		else
		{
			// create the geographicals version of the ozBoxGeo bound
			ozBoxGeog = [map.getExtent().left, map.getExtent().bottom, map.getExtent().right, map.getExtent().top]; 
		}
	}
	//alert('ozboxgeog = '+ozBoxGeog)

	// set up the point symbol styling
	//setupSymbols() ;

	// - main vector plotting loop -
	//progress('progBar', 'Plotting ...', '') ;
	var jk=0;
	allPoints = [];

	// if we have a polygon-feature filter, rearange into polygon array
	var loX = 9999999999; loY=9999999999; hiX=-9999999999; hiY=-9999999999;
	var pointList = new Array();

	//alert('polly = '+polly)
	
	if(polly)
	{
		for (var z=0 ; z<allX.length ; z++)
		{
			// get all the points of the polygon from input arrays
			pointList.push(new OpenLayers.Geometry.Point(allX[z], allY[z]));
			allPoints[z] = {x:allX[z], y: allY[z]}
			
			
			// calculate BBox of search polygon
			if(allX[z] < loX){loX=allX[z];}
			if(allX[z] > hiX){hiX=allX[z];}
			if(allY[z] < loY){loY=allY[z];}
			if(allY[z] > hiY){hiY=allY[z];}
		}
	
		// make sure last point and first point are the same
		if(allX[0] != allX[allX.length-1] || allY[0] != allY[allX.length-1])
		{  allX[allX.length-1] = allX[0]; allY[allX.length-1] = allY[0];}

		// create the outer polygon as a line string
		var parcel01= new OpenLayers.Geometry.LinearRing(pointList);

		// clear out any existing search polygon
		if(vectorLayer2) 
		{	vectorLayer2.destroyFeatures(); vectorLayer2.destroyFeatures(); vectorLayer2=null;	}

		// initialise a new vector layer
		vectorLayer2 = new OpenLayers.Layer.Vector("Search Polygon", {style: select_box});
		vectorLayer2.addOptions({reproject: true, visibility:true, reaspect: false});
		map.addLayer(vectorLayer2);
		
		// draw the polygon
		var parcel01= new OpenLayers.Geometry.LinearRing(pointList);
		polygonFeature2 = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Polygon([parcel01]));
		vectorLayer2.addFeatures(polygonFeature2);	
		vectorLayer2.setZIndex(map.Z_INDEX_BASE['Popup'] -2000);	

		// set zoom to the polygon
		bounds = new OpenLayers.Bounds(loX,loY,hiX,hiY);
		var zoomlevel = map.getZoomForExtent(bounds)-1;
		map.setCenter(bounds.getCenterLonLat(),zoomlevel);
		map.updateSize();
	}
	else
	{
		if(vectorLayer2) {	vectorLayer2.destroyFeatures();  vectorLayer2=null;}
	}

	// process each point in the uploaded file
	//alert ('polly = '+polly)
	var step = 0;
	progress(progressBarVer, 'Plotting','');
	
	
	//alert('total addresses  = '+addresses.length)
	for (var i=0; i<addresses.length; i++)
	{		
		var percent = Math.ceil(i/(parseInt(addresses.length))*100);
		//alert(percent)
		if(step <= percent) 
		{	//alert(step+"  "+percent);
			//percent = Math.ceil(i/(parseInt(addresses.length))*100);
			progress(progressBarVer, 'Plotting', percent) ;
			step = step + 2;// every second percentage point
		
		//var percentDone = parseInt( Math.round((i+1)/addresses.length*100));
		//genLoadStatus('Plotting '+percentDone+"%", false, percentDone);
		}
		genLoadStatus('Plotting '+percent+"%", false, percent);
				
		// initialise batch variables
		pointLon = 0.0; 
		pointLat = 0.0;
		description=''; 
		symbols = ''; 
		pointAcc = 0;
		pointClass = '';
		
		// set the defaults for circle vector symbols
		symbolFillColor = '#FF0000';
		symbolFillOpacity = '0.8';
		symbolStrokeColor = '#FFFFFF';
		symbolStrokeWidth = '1';
		found = false;

		// pick off attributes for this point
		if (addresses[i].getAttribute("lng"))  {pointLon = addresses[i].getAttribute("lng");}
		if (addresses[i].getAttribute("lat"))  {pointLat = addresses[i].getAttribute("lat");}
		//alert(pointLat+", "+pointLon)
		
		// get the other attributre data from the XML input file if we have a lat & long
		if (pointLon == parseFloat(pointLon) && pointLat == parseFloat(pointLat) ) 
		{
			if (addresses[i].getAttribute("addr"))			{pointAddress[i] = addresses[i].getAttribute("addr");}
			if (addresses[i].getAttribute("addrNumber"))	{recNo[i]= addresses[i].getAttribute("addrNumber"); }
			if (addresses[i].getAttribute("acc"))			{pointAcc = addresses[i].getAttribute("acc");}
			if (addresses[i].getAttribute("class"))			{pointClass	= addresses[i].getAttribute("class");}
			
			// now get the rendering controls from XML into the filtering arrays
			if (addresses[i].getAttribute("fillOpacity"))	{symbolFillOpacity = addresses[i].getAttribute("fillOpacity");	}
			if (addresses[i].getAttribute("strokeColor"))	{symbolStrokeColor = addresses[i].getAttribute("strokeColor");	}
			if (addresses[i].getAttribute("strokeWidth"))	{symbolStrokeWidth = addresses[i].getAttribute("strokeWidth");	}
			if (addresses[i].getAttribute("fillColor"))  
			{	
				// force marker color to be as what is set by user
				symbolFillColor	 = addresses[i].getAttribute("fillColor");			
				for(var x=0; x<markerClass.length ; x++)
				{
					if(markerClass[x] == pointClass) 
					{	markerColor[x] = symbolFillColor; 
						found = true;
						break;
					}
				}
				// disable the override color feature			
				document.getElementById('redOpt').checked=false;
				document.getElementById('blueOpt').checked=false;
				document.getElementById('greenOpt').checked=false;
				document.getElementById('yellowOpt').checked=false;
				document.getElementById('redOpt').disabled = true;
				document.getElementById('blueOpt').disabled = true;
				document.getElementById('greenOpt').disabled = true;
				document.getElementById('yellowOpt').disabled = true;
			}
			else
			{				
				symbolFillColor = overrideColor;				
				// search through markerClass looking for the same pointClass as this
				for(var x=0; x<markerClass.length ; x++)
				{
					if(markerClass[x] == pointClass) 
					{	symbolFillColor = markerColor[x]; 
						found = true;
						break;
					}
				}
				// re enable override color feature
				document.getElementById('redOpt').disabled = false;
				document.getElementById('blueOpt').disabled = false;
				document.getElementById('greenOpt').disabled = false;
				document.getElementById('yellowOpt').disabled = false;			
			}
			
			// if not found then add MarkerClass and MarkerColor to array
			if(!found) 
			{	if(symbolFillColor == '') {symbolFillColor = random_color('hex');	}
				markerClass.push(pointClass);
				markerColor.push(symbolFillColor);
				markerOpacity.push(symbolFillOpacity);
			}
		}
		else 
		{ 
			return false;
		}

		// check if polygon-in-point check applies
		if(polly)
		{
			// first transform point into google coords
			var p = new Array(pointLon, pointLat);
			if (srs == 'EPSG:900913') 
			{
				var point = geogs2google(p);
				var p = decodePoint(point);
				var pt = {x: p[0], y: p[1]};
				point = new OpenLayers.Geometry.Point(p[0], p[1]); 
			}
			// check if inside polygon
			if (pt.x > loX && pt.y > loY && pt.x < hiX && pt.y < hiY) 
			{ 
				//if(isPointInPoly(allPoints, pt))
				if(polygonFeature2.geometry.intersects(point) )
				{	
					includeThisPoint(i, pointLon, pointLat, subjectAtt); 
					jk++ ;	
				}
			}
		}
		
		// else if point is outside of Australia & NZ just skip over it -	ozBoxGeog = [104.94141,  -44.96480,  180.0,  0.0]		
		else if(pointLon >= ozBoxGeog[0] && pointLon <= ozBoxGeog[2] && pointLat >= ozBoxGeog[1] && pointLat <= ozBoxGeog[3]) 
		{	includeThisPoint(i, pointLon, pointLat, subjectAtt);	jk++}
				
	}
	genLoadStatus('Plotting Done ...', false, '');
//alert('range = '+range)
	// sort the arrays by range value
	var ptr = 0;
	//for (var m=0; m<range.length ; m++ )	// smallest first
	for (var m = range.length-1; m>=0 ; m-- )	// largest first
	{
		for (var n=0; n<range.length ; n++ )
		{	
			if(range[n] == m)
			{
				sortedPoints[ptr] = pointFeature[n];
				sortedRange[ptr] = range[n];
				sortedRecNo[ptr] = recNo[n];
				if(pointAddress[n]){sortedAddress[ptr] = pointAddress[n].toString();} else {sortedAddress[ptr] =''}
				//sortedAddress[ptr] = pointAddress[n].toString();
				sortedOldLoc[ptr] = oldLocation[n];
				ptr++;
			}
		}
	}
//alert('ptr = '+ptr)
	
	// now build the markers overlay
	if(firstTime) 
	{	filterMarkers();	} 
	else 
	{	filterMarkers(getFilterList());		}
	
	// rebuild the attribute selection control
	buildAttributeList(subjectAtt, subjectRange);
	
	// make sure the Markers layer is clickable
	bringToTop(userMarkers);

	genLoadStatus('',false, '');

	return true;
}

function buildAttributeList(subjectAtt, subjectRange)
{
	//alert('subjectAtt = '+subjectAtt+' Range = '+subjectRange);
	
	// remove any previous pick list
	checkRemoveObject('attPickList');

	// create the Select object
	
		
		
		var table = document.createElement('table');
		table.style.color='#000000'; 
		table.style.position='absolute'; 
		table.style.top='0px'; 
		table.style.left='0px'; 
		table.style.paddingTop='0px'; 
		table.style.paddingBottom='2px'; 
		table.style.borderCollapse='collapse'; 
		table.style.fontWeight='bold'; 
		table.style.fontSize='9px'; 
		table.style.backgroundColor='#FFFFFF';
		
		
		//select.className='tree';
		//select.style.verticalAlign='middle';
		table.style.width='210px';
		table.style.height='auto';
		table.style.maxHeight='200px';
		table.style.overflowX = 'scroll';
		table.style.overflowY = 'scroll';
		//select.setAttribute('size','15');
		//select.setAttribute('width','70');
		table.id='attPickList';
		table.setAttribute('id','attPickList');

		// make the tablebody
		var tBody = document.createElement('tbody');
		//tBody.style.height='100%';
		//tBody.style.width='100%'
		


			// now create the selectable rows for numeric values only
			for (var i=0; i<attributeName.length ; i++ )
			{										
				//alert(attributeName[i]+"  -  "+attributeType[i]);
				if(attributeType[i] == 'numeric')
				{
					var row = document.createElement('tr');
					row.style.height="15px";
					row.style.width="100%";
						var cell = document.createElement('td');
						var textString = attributeName[i];
						if(subjectRange)
						{
							var textRange = subjectRange.replace(/:/, '-');
							if(attributeName[i] == subjectAtt){textString = subjectAtt+" ("+textRange+")";}
						}
						var cellText = document.createTextNode(textString);
						cell.appendChild(cellText);
						cell.value = attributeName[i];
						cell.style.color = 'black';
						cell.className='unselectedItem';
						if(attributeName[i] == subjectAtt ){cell.className='selectedItem';}
						cell.style.fontSize = '10px';
						cell.style.width = "100%";
						cell.style.height='15px';
						cell.style.cursor='pointer';
						cell.id = 'attOpt:'+i;
						cell.setAttribute('id','attOpt:'+i);
						cell.title = attributeName[i];
						bindEvent(cell, 'click', swapSymbolVar, 'false');
					row.appendChild(cell);
					tBody.appendChild(row);
				}
			}
		table.appendChild(tBody)
		document.getElementById('pointThematicsEditor').appendChild(table);
}

function swapSymbolVar(evt)
{
	// get the attribute selected 
	var id = getThisId(evt);
	var rownumb = id.split(":")[1];
	overrideAttribute = document.getElementById(id).value;
	//alert('new att = '+overrideAttribute)
	for (var i=0; i<attributeName.length ; i++ )
	{
		if(rownumb == i){document.getElementById(id).className = 'slectedItem';}
		else {document.getElementById(id).className = 'unselectedItem';}
	}

	// get the override color option
	var overrideColor = '';
	if(document.getElementById('redOpt').checked){overrideColor = document.getElementById('redOpt').value;} 
	if(document.getElementById('blueOpt').checked){overrideColor = document.getElementById('blueOpt').value;} 
	if(document.getElementById('greenOpt').checked){overrideColor = document.getElementById('greenOpt').value;} 
	if(document.getElementById('yellowOpt').checked){overrideColor = document.getElementById('yellowOpt').value;} 

	// get all points from xml file
	firstTime = true;
	showUserPoints(geocodedFile, overrideAttribute, overrideColor)

	// update attribute list title and text
	//document.getElementById(id).selected = true;
	var loVal = attributeRange[rownumb].split(":")[0];
	var hiVal = attributeRange[rownumb].split(":")[1];
	document.getElementById(id).nodeValue = attributeName[rownumb]+" ("+loVal+"-"+hiVal+")";
	document.getElementById(id).title = attributeName[rownumb]+" ("+loVal+"-"+hiVal+")"

	Event.stop(evt);
}

function changeGeocodeType(ident)
{
	// first determine which option was selected
	// [Address, MESHBLOCKS, CENSUS_DISTRICTS, SUBURBS, POSTAL_AREAS, COUNCILS]
	var selectObject = document.getElementById(ident); 
	geocodeLayerName = selectObject.options[selectObject.selectedIndex].value;
	//alert('user choice = '+geocodeLayerName)
	// push selected value into form
	document.getElementById('gtype').value = geocodeLayerName;

	// swap the label for address cols entry
	var labelObj = document.getElementById('addrInstruct');
	//alert(labelObj.id);
	//alert('label text = '+labelObj.firstChild.nodeValue)
	if(geocodeLayerName != 'Address')
	{	labelObj.firstChild.nodeValue = '*Feature Code Cols:';
		document.getElementById('addressCols').title = 'This column contains the unique Feature ID or Code used to identify the area feature.';}
	else
	{	labelObj.firstChild.nodeValue = '*Address Cols:';
		document.getElementById('addressCols').title = 'Enter column numbers separated by a dash and used for the complete address (e.g. start-end).';}
	
}

function includeThisPoint(i, pointLon, pointLat, subjectAtt)
{
	xtype = 'Longitude';
	ytype = 'Latitude';
	pointX = pointLon; 
	pointY = pointLat;	// save for output
	oldLocation[i] = pointLon+","+pointLat;
	
	// if accuracy supplied prepare the popup data
	acc = '';
	if(pointAcc > 0 ) {acc = "<br/><b>Geocode Accuracy : </b>"+accuracyDesc[pointAcc];}

	// transform to Google Projection if required
	if (srs == 'EPSG:900913') 
	{
		p = [pointLon, pointLat];
		var googlePoint = geogs2google(p)
		var newP = decodePoint(googlePoint);
		pointX = newP[0];
		pointY = newP[1];
		//xtype = 'Eastings';
		//ytype = 'Northings'
	}
		
	// check for attributes and assign a classification level if required
	range[i]=1;						// this is the default
	attribs = addresses[i].getElementsByTagName("Attribute");
	chartFlag = false;
	if (attribs.length > 0 && (hiVal != -9999999999 && loVal != 9999999999))
	{
		// look for the subject attribute
		for(var g=0; g<attribs.length; g++)
		{	// check for subjectAttribute
			if(subjectAtt == attribs[g].getAttribute('name'))
			{
				var name = attribs[g].getAttribute('name');
				var value = parseFloat(attribs[g].getAttribute('value'));
				valuesPresent = true;
				break;
			}
		}
		//alert('values present = '+valuesPresent);
		// set symbol size
		//alert(bdy.length)
		for (var z=1; z<bdy.length ; z++ )
		{
			var testString = value.toString();
			//alert('test string for value = '+testString)
			if(testString == '0' || testString == '' || testString == null || testString == 'undefined'){range[i] == 0; break;}
			if(z == bdy.length - 1){if(value >= bdy[z-1] && value <= bdy[z]) {range[i] = z; break;}}
			if(value >= bdy[z-1] && value < bdy[z]){range[i] = z; break;}
		}
	}
	//alert('range = '+range[i])

	
	if(range[i] > 0)
	{	
		var mapPieCharts = false;
		if(document.getElementById('mapPieRadio').checked)		
		{	
			chart = 'p3';	
			var pieContext = buildPieChart(attribs, range[i], chart);
			var mapPieCharts = true;
		}		
		
		//alert('chart = '+chart)
		
		var label = '';
		if(labelsRequired)	{label=pointAddress[i];}
		if(!mapPieCharts)
		{	
			var size = range[i] * uploadRadius/4;
			var fillColor = symbolFillColor;
			var fillOpacity = symbolFillOpacity;
			var strokeColor = symbolStrokeColor;
			var strokeWidth = symbolStrokeWidth;
			var externalGraphic = '';
			var graphicOpacity = '';
			var graphicWidth = '';
			var graphicHeight = '';
			var label=label;

		}
		else
		{		
			var graphicOpacity = 1.0;
			var externalGraphic = pieContext.link;
			var graphicWidth = pieContext.size;
			var graphicHeight = pieContext.size;
			var strokeWidth= symbolStrokeWidth;
			var fillColor='';
			var fillOpacity='';
			var strokeColor=''
			var strokeWidth='';
			var label=label;
			var size='';
		}
		
		// set up the content details for the popup
		description = setupPopupDescription(i);

		// add the point to the pointFeature array of Vector objects
		var point = new OpenLayers.Geometry.Point(pointX, pointY);
		pointFeature[i] = new OpenLayers.Feature.Vector
		(	point, 
			{
				type: size 
				,fillColor: fillColor
				,fillOpacity: fillOpacity
				,strokeColor: strokeColor
				,strokeWidth: strokeWidth
				,label:label
				,graphicOpacity: graphicOpacity
				,externalGraphic: externalGraphic
				,graphicWidth: graphicWidth
				,graphicHeight: graphicHeight
				
			}
		);

		// add other attributes to pointFeature array of Vector Objects
		pointFeature[i].attributes.description = description;
		pointFeature[i].attributes.fillColor = symbolFillColor;
		pointFeature[i].attributes.fillOpacity = symbolFillOpacity;
		pointFeature[i].attributes.strokeColor = symbolStrokeColor;
		pointFeature[i].attributes.strokeWidth = symbolStrokeWidth;
		if(pieContext)
		{
			pointFeature[i].attributes.graphicOpacity = symbolFillOpacity;
			pointFeature[i].attributes.externalGraphic = pieContext.link;
			pointFeature[i].attributes.graphicWidth = pieContext.size;
			pointFeature[i].attributes.graphicHeight = pieContext.size;
		}
		pointFeature[i].id = recNo[i];
		
		// calculate BBox as we go and add to bounds
		adjustBoundsExtent(pointY, pointX, i);
		bounds = new OpenLayers.Bounds(loLng,loLat,hiLng,hiLat);
	}
}

function buildPieChart(attribs, scaleRange, pieType)
{
	// adjust range to scale better for map based pie charts
	var fact = 1;
	if(scaleRange == 2){var fact=1.25;}
	if(scaleRange == 3){var fact=1.5;}
	if(scaleRange == 4){var fact=1.75;}
	if(scaleRange == 5){var fact=2.0;}
	var chSize = fact * uploadRadius *1.2;
	//alert('chSize = '+chSize)	
	// now build up the optional pieChart external graphic
	var pieContext = new Object();
	var k=0;

	// first get the attributes used to size the piechart
	var chValues = ''; var chLabels = ''; var chValuesTotal = 0; var tempValues = []; var colorRange='';
	for(var z=0; z<attribs.length; z++)
	{		
		// build up the pie part values and labels
		if(attribs[z].getAttribute('type') == 'chartVar' )	
		{
			// get the min/max values for all values
			//minVal = attribs[z].getAttribute("min");
			//if(minVal == ''){minVal=0;}
			//maxVal = attribs[z].getAttribute("max");
				
			tempValues[k] = attribs[z].getAttribute("value"); 
			chValuesTotal = chValuesTotal + parseInt(tempValues[k]);
			if(z==0)
			{	
				//chValues = attribs[z].getAttribute("value"); 
				chLabels = attribs[z].getAttribute("name");
			}
			else	
			{	
				//chValues += ","+attribs[z].getAttribute("value"); 
				chLabels += "|"+attribs[z].getAttribute("name");	
			}
			k++;
		}
		
	}

	//var yHigh = parseInt(Math.ceil(maxVal)*1.1);
	//var yLow = 0.0;

	// calculate percentages	
	for(var z=0; z<tempValues.length; z++)
	{
		var valPercent = roundNumber((tempValues[z]/chValuesTotal)*100, 1);
		//alert(valPercent)
		if(z==0)
		{	chValues = valPercent;
			colorRange = colorArray[z];
		}
		else
		{	chValues+= ","+valPercent;
			colorRange += ","+colorArray[z];
		}
	}
	
	// now build the pieChart link
	pieContext.size = chSize;
	//var colorRange = 'FF0000,0000FF';
	var chartBackground = 'bg,s,00000000'; // sets background to transparent
	if(chValues !='')
	{	
		//pieContext.link = 'http://chart.apis.google.com/chart?cht=p&chd=t:' + chValues + '&chds='+yLow+','+yHigh+'&chs=' + chSize + 'x' + chSize + '&chco='+colorRange + '&chf='+chartBackground;
		pieContext.link = 'http://chart.apis.google.com/chart?cht='+pieType+'&chd=t:' + chValues + '&chs=' + chSize + 'x' + chSize + '&chco='+colorRange + '&chf='+chartBackground;
	}
	else
	{	pieContext.link = chValues;}
	//alert(pieContext.link)
	return pieContext;
}

function popAllButts()
{
	// make sure all buttons are popped up
	document.getElementById('editButtons11').className = "buttup";
	document.getElementById('editButtons12').className = "buttup";
	document.getElementById('editButtons13').className = "buttup";
	document.getElementById('editButtons14').className = "buttup";
}

function popupFileAbstractEditor(targetId)
{
	// 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 = textEditor(document.getElementById('attributeEditor'), 'editor', targetId, 'Abstract Editor');
	//Event.stop(evt);

}
function textEditor(sldBuilderDiv, editorId, targetId, 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)';
	var content = document.getElementById(targetId).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; 
	textarea.id = 'abstractContent';
	textarea.setAttribute('id','abstractContent');
	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='5px';
	saveButt.id = targetId+":"+editorId;
	saveButt.setAttribute('id',targetId+":"+editorId)
	bindEvent(saveButt, 'click', saveAbstractChanges, 'false');
	attribEditor.appendChild(saveButt);
	
	// close off the tool
	sldBuilderDiv.appendChild(attribEditor);
	Drag.init(editorBanner, attribEditor);
}

function saveAbstractChanges(evt)
{
	var id = getThisId(evt);
	var target = id.split(":")[0];
	var editor = id.split(":")[1];
	
	document.getElementById(target).value = document.getElementById('abstractContent').value;
	document.getElementById(editor).style.display='none';
	Event.stop(evt);
}



// ------------ function to undertake CRUD to uploaded file ----------------------//
function crudTransaction(trans)
{

	document.getElementById('fileAbstract').value = xmlAbstract;
	currentTrans = trans;
	var numHeadRecs = document.getElementById('header').value;
	var totalCurrents = pointAddress.length - parseInt(numHeadRecs);

	// set up for the Create Mode selection
	if(trans == 'CREATE')
	{	
		// toggle mode button off and return
		if(document.getElementById('editButtons11').className == "buttdown")
		{
			// just pop the button deactivate the clickedit control and exit
			document.getElementById('editButtons11').className='buttup';
			document.getElementById('attributeEditor').style.display='none';
			if(inputNew) {inputNew.deactivate();}
			if(dragItControl) {dragItControl['drag'].deactivate();}
			return;
		}
		
		// set to Create mode
		popAllButts();
		document.getElementById('editButtons11').className = "buttdown";
		current = sortedOldLoc.length+1;
		if(document.getElementById('addrEditing')){document.getElementById('addrEditing').disabled=false; document.getElementById('addrEditing').focus();}
		if(document.getElementById('latEditing')){document.getElementById('latEditing').disabled=false;}
		if(document.getElementById('lngEditing')){document.getElementById('lngEditing').disabled=false;}
		
	}

	// set up for the Read mode selection
	if(trans == 'READ')
	{			
		// if current is out of range force it to the start
		if(current < 0 || current > totalCurrents ){current = 0;}
		
		// get the number of attributes to resize panel		
		attribs = addresses[current].getElementsByTagName("Attribute");
		if(inputNew) {inputNew.deactivate();}
		if(dragItControl) {dragItControl['drag'].deactivate();}
		
		// toggle mode button off and return
		if(document.getElementById('editButtons12').className == "buttdown")
		{
			// just pop the button deactivate the clickedit control and exit
			document.getElementById('editButtons12').className='buttup';
			document.getElementById('attributeEditor').style.display='none';
			return;
		}
		
		// set to Read mode
		popAllButts();
		document.getElementById('editButtons12').className = "buttdown";
		if(document.getElementById('addrEditing')){document.getElementById('addrEditing').disabled=false; document.getElementById('addrEditing').focus();}
	}

	// set up for the Read mode selection
	if(trans == 'UPDATE')
	{			
		if(current >= 0 && current <= totalCurrents)
		{
		
		// get the number of attributes to resize panel		
			attribs = addresses[current].getElementsByTagName("Attribute");
			if(inputNew) {inputNew.deactivate();}	
			
			// toggle mode button off and return
			if(document.getElementById('editButtons13').className == "buttdown")
			{
				// just pop the button deactivate the clickedit control and exit
				document.getElementById('editButtons13').className='buttup';
				document.getElementById('attributeEditor').style.display='none';
				if(dragItControl) {dragItControl['drag'].deactivate();}
				return;
			}
			
			// set to Create mode
			popAllButts();
			document.getElementById('editButtons13').className = "buttdown";
			if(document.getElementById('addrEditing')){document.getElementById('addrEditing').disabled=false; document.getElementById('addrEditing').focus();}
			if(document.getElementById('latEditing')){document.getElementById('latEditing').disabled=false;}
			if(document.getElementById('lngEditing')){document.getElementById('lngEditing').disabled=false;}
		}
		else {return; }
	}
	
	// set up for the Delete transaction
	if(trans == 'DELETE')
	{				
		var east = pointFeature[current].geometry.x;
		var north = pointFeature[current].geometry.y;
		if(east == null && north == null)
		{alert('selected record already deleted'); return;}
		
		if(current >= 0 && current <= totalCurrents)
		{
			// get the number of attributes to resize panel		
			attribs = addresses[current].getElementsByTagName("Attribute");
			
			// kill off any controls
			if(inputNew) {inputNew.deactivate();}
			if(dragItControl) {dragItControl['drag'].deactivate();}
			
			// if confirmed proceed with the delete
			if(confirm('This will delete the selected/current Marker. Do you wish to proceed?'))
			{
				//alert (document.getElementById('editButtons14').className)
				if(document.getElementById('editButtons14').className == "buttdown")
				{
					// just pop the button deactivate the clickedit control and exit
					document.getElementById('editButtons14').className='buttup';
					document.getElementById('attributeEditor').style.display='none';
					return;
				}

				// set to Delete mode
				popAllButts();
				document.getElementById('editButtons14').className='buttdown';
				if(document.getElementById('addrEditing')){document.getElementById('addrEditing').disabled=true;}
				if(document.getElementById('latEditing')){document.getElementById('latEditing').disabled=true;}
				if(document.getElementById('lngEditing')){document.getElementById('lngEditing').disabled=true;}
				//document.getElementById('addrEditing').focus();
				
				// clear out the lat longs to indicate a delete
				var addr = pointAddress[current];
				var lat = '';
				var lng = '';
			}
			else {return;}
		}
		else {return;}
	}
	
	// set up the size od the editor based on number of attributes
	var adjHeight = 110 + (parseInt(attribs.length) * 50 );
	var inputWidth = 190;
	if(adjHeight < 370)
	{
		document.getElementById('attributeEditor').style.height = parseInt(adjHeight+100)+'px';
		document.getElementById('editorContent').style.height = parseInt(adjHeight+80)+'px';
		document.getElementById('editorEntryDiv').style.height = parseInt(adjHeight)+'px';
		//document.getElementById('editorEntryDiv').style.maxHeight = '200px';
		//document.getElementById('editorEntryDiv').style.overflowY = 'scroll';
		document.getElementById('commitChanges').style.top = parseInt(adjHeight+75)+'px';
		//alert('total height = '+adjHeight)
	}
	else
	{	inputWidth = 200;	}
	var inputHeight = 20;
	var labelHeight = 12;
	var newTop = 5;
	var addr = ''; var lat = ''; var lng = '';

	// get the Address header information
	if(trans == 'READ' || trans == 'UPDATE' || trans == 'LOAD')
	{
		// get the lat longs
		var east = pointFeature[current].geometry.x;
		var north = pointFeature[current].geometry.y;
		var p = [east, north];
		if (srs == 'EPSG:900913') 
		{	
			var googlePoint = google2geogs(p)	
			var newP = decodePoint(googlePoint);
			var lng = newP[0];	
			var lat = newP[1];
		}
		var addr = pointAddress[current];
		//var addr	= addresses[current].getAttribute('addr');
		//var lat		= addresses[current].getAttribute('lat');
		//var lng		= addresses[current].getAttribute('lng');
	}
	
	// start building the embedded form - kill of any previous form first
	checkRemoveObject('internalEditorRows');
	var pointDiv = document.createElement('table');
	pointDiv.id = 'internalEditorRows'; pointDiv.setAttribute('id','internalEditorRows');
	pointDiv.style.position = 'absolute';
	pointDiv.style.top = '0px';
	pointDiv.style.left = '0px';
	pointDiv.border = 0;
	//pointDiv.style.overflowY = 'scroll';
	//pointDiv.style.overflowX = 'hidden';
	//pointDiv.style.height = '70px';
	pointDiv.style.height = parseInt(adjHeight)+'px';
	pointDiv.style.width = '80%';
	//pointDiv.style.border = '1px solid red';

		// build the form in a table
		var tableBody = document.createElement('tbody');
		//tableBody.style.height = '100%';
		//tableBody.style.width = '100%';

		// now start adding the row pairs
		var tr = document.createElement('tr');		
			var td = document.createElement('td');
			td.style.height = '11px'; 
			var text = document.createTextNode("Address:");
			td.appendChild(text);
			tr.appendChild(td);
		tableBody.appendChild(tr);

		var tr = document.createElement('tr');
		tr.style.height = '20px'; 
			var td = document.createElement('td');
				td.style.width = '200px';
				var input = document.createElement("input");
				input.style.width = inputWidth+'px';
				input.id = 'addrEditing'; input.setAttribute('id','addrEditing');
				input.value = addr;
				//var text = document.createTextNode(addr);
				//input.appendChild(text);
			td.appendChild(input);
			tr.appendChild(td);
		tableBody.appendChild(tr);


		// now start adding the row pairs
		var tr = document.createElement('tr');
			var td = document.createElement('td');
			td.style.height = '11px';
			var text = document.createTextNode("Latitude:");
			td.appendChild(text);
			tr.appendChild(td);
		tableBody.appendChild(tr);

		var tr = document.createElement('tr');
		tr.style.height = '20px'; 
			var td = document.createElement('td');
			td.style.width = '200px';
				var input = document.createElement("input");
				input.style.width = inputWidth+'px';
				input.id = 'latEditing'; input.setAttribute('id','latEditing');
				input.value = lat;
				//var text = document.createTextNode(lat);
				//input.appendChild(text);
			td.appendChild(input);
			tr.appendChild(td);
		tableBody.appendChild(tr);

		// now start adding the row pairs
		var tr = document.createElement('tr');
			var td = document.createElement('td');
			td.style.height = '11px';
			var text = document.createTextNode("Longitude:");
			td.appendChild(text);
			tr.appendChild(td);
		tableBody.appendChild(tr);

		var tr = document.createElement('tr');
		tr.style.height = '20px'; 	
			var td = document.createElement('td');
			td.style.width = '200px';
				var input = document.createElement("input");
				input.style.width = inputWidth+'px';
				input.id = 'lngEditing'; input.setAttribute('id','lngEditing');
				input.value = lng;
				//var text = document.createTextNode(lng);
				//input.appendChild(text);
			td.appendChild(input);
			tr.appendChild(td);
		tableBody.appendChild(tr);

		// get the attributes and the attribute names
		for(var i=0; i<attribs.length ; i++)
		{
			var attribName = attribs[i].getAttribute("name");
			if(trans == 'CREATE'){var attribValue = '';}
			else{var attribValue = attribs[i].getAttribute("value");}

			// now start adding the row pairs
			var tr = document.createElement('tr');
				var td = document.createElement('td');
				td.style.height = '11px';
				var text = document.createTextNode(attribName+":");
				td.appendChild(text);
				tr.appendChild(td);
			tableBody.appendChild(tr);

			var tr = document.createElement('tr');
			tr.style.height = '20px'; 	
				var td = document.createElement('td');
				td.style.width = '200px';
					var input = document.createElement("input");
					input.style.width = inputWidth+'px';
					input.id = 'attribEdit:'+i; input.setAttribute('id','attribEdit:'+i);
					input.value = attribValue;
					//var text = document.createTextNode(lng);
					//input.appendChild(text);
				td.appendChild(input);
				tr.appendChild(td);
			tableBody.appendChild(tr);
		}
		// append all this to the form
		pointDiv.appendChild(tableBody);
		document.getElementById('editorEntryForm').appendChild(pointDiv);

		// set default status for updating
		document.getElementById('commitChanges').disabled=false;
		document.getElementById('commitChanges').style.color='black';
		//alert(document.getElementById('editButtons12').className)

		// set the appropriate panel settings
		if(trans == 'LOAD')
		{
			
			if(document.getElementById('editButtons12').className == 'buttdown'){trans = 'READ';}
			if(document.getElementById('editButtons13').className == 'buttdown'){trans = 'UPDATE';}
		}
		if(trans == 'CREATE')
		{
			setupClickControl();
			document.getElementById('commitChanges').disabled=false;
			document.getElementById('commitChanges').style.color='black';
			document.getElementById('addrEditing').focus();
			document.getElementById('commitChanges').value='Commit Changes';
		}

		if(trans == 'UPDATE')
		{
			setupDragControl(false);
			document.getElementById('commitChanges').disabled=false;
			document.getElementById('commitChanges').style.color='black';
			document.getElementById('addrEditing').focus();
			document.getElementById('commitChanges').value='Commit Changes';
		}
	
		if(trans == 'DELETE')
		{	
			deleteCurrentMarker(addr);	
			document.getElementById('commitChanges').disabled=false;
			document.getElementById('commitChanges').style.color='black';
			document.getElementById('commitChanges').value='Commit Changes';
		}

		if(trans == 'READ' )
		{
			// make sure for READ that most of the form is not editable
			document.getElementById('latEditing').disabled=true;
			document.getElementById('lngEditing').disabled=true;
					
			// allow them to enter an address and go to that value
			document.getElementById('commitChanges').value='Go To This Point';
			document.getElementById('commitChanges').style.color='black';
			document.getElementById('addrEditing').disabled=false;
		}

		// launch the attribute editor
		document.getElementById('attributeEditor').style.display='block';
	
}

function setupDragControl(reverseGeocode)
{
	reverse = reverseGeocode;
	if(dragItControl){return;}
	
	// setup Dragging of Markers
	dragItControl = { drag: new OpenLayers.Control.DragFeature(userMarkers, 
	{
		'onComplete': onCompleteMove} 
	)};
	map.addControl(dragItControl['drag']);
	dragItControl['drag'].activate();
	//alert('in drag mode')
}

function deleteCurrentMarker(addr)
{
		// make the coordinates of the deleted element null
		pointFeature[current].geometry.x=null;
		pointFeature[current].geometry.y=null;
		popAllButts();
		filterMarkers(getFilterList());
		
		crudTransaction('LOAD');
		
		// now put bar on the Progress Bar window as a record pointer
		if(document.getElementById(progressBarVer)) {	recordNumber (progressBarVer, current+1, sortedOldLoc.length);}	
}

function setupClickControl()
{
	// check if already done
	if(inputNew) {inputNew.activate(); return;}
	
	// create the control 
	OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, 
	{                
		defaultHandlerOptions: {
			'single': true,
			'double': false,
			'pixelTolerance': 0,
			'stopSingle': false,
			'stopDouble': false
		},

		initialize: function(options) {
			this.handlerOptions = OpenLayers.Util.extend(
				{}, this.defaultHandlerOptions
			);
			OpenLayers.Control.prototype.initialize.apply(
				this, arguments
			); 
			this.handler = new OpenLayers.Handler.Click(
				this, {
					'click': this.trigger
				}, this.handlerOptions
			);
		}, 

		trigger: function(e) 
		{
			var found = false;

			// get digitized point
			var lonlat = map.getLonLatFromViewPortPx(e.xy);
			var pointX = lonlat.lon; 
			var pointY = lonlat.lat;			
			
			// convert to lat/lon
			var p = [lonlat.lon, lonlat.lat];
			if (srs == 'EPSG:900913') 
			{	
				var googlePoint = google2geogs(p)	
				var newP = decodePoint(googlePoint);
				var newLon = newP[0];	
				var newLat = newP[1];
			}
			
			// post the lat/lon values back into the editing form
			var newLoc = new GLatLng(newLat,newLon);
			document.getElementById('latEditing').value = newLat;
			document.getElementById('lngEditing').value = newLon;

			// validate form data
			if(document.getElementById('addrEditing').value == '')
			{	
				alert ("Please enter the mandatory ID for this item and re-digitize the point"); 
				document.getElementById('latEditing').value = '';
				document.getElementById('lngEditing').value = '';
				document.getElementById('attributeEditor').style.display='block';
				document.getElementById('addrEditing').focus();
				return;
			}
			else 
			{	
				// deterimine if code already used
				var inputCode = document.getElementById('addrEditing').value.toString();
				for(var z=0; z<sortedAddress.length; z++)
				{
					if(inputCode == sortedAddress[z].toString())
					{ found = true; break;}
				}
				
				// if code already exists tell user to do again
				if(found)
				{		
					alert("The code ["+inputCode+"] has already been used! Please enter a different code and re-digitze the point?");
					//alert(inputCode+" == "+sortedAddress[z])
					document.getElementById('addrEditing').value = '';
					document.getElementById('latEditing').value = '';
					document.getElementById('lngEditing').value = '';
					document.getElementById('attributeEditor').style.display='block';
					document.getElementById('addrEditing').focus();
					return;
				}
			}

			// all is well so proceed...
			newAdd = document.getElementById('addrEditing').value;
			description = "Address: </b>"+newAdd+"<br/><b>latitude : </b>"+newLat+"<br/><b>Longitude : </b>"+newLon+"<br/><b>Rec Number : </b>"+current+"<br/><b>Symbol Size : 1";
			loadAttsToDescription();
			//alert(description)
			
			// set the defaults for circle vector symbols
			symbolFillColor = '#FF0000';
			symbolFillOpacity = '0.8';
			symbolStrokeColor = '#FFFFFF';
			symbolStrokeWidth = '1';
			//setupSymbols();
			
			// add the point to the pointFeature array of Vector objects
			var point = new OpenLayers.Geometry.Point(pointX, pointY);		
			next = parseInt(pointFeature.length);
			
			if(labelsRequired)
			{
				pointFeature[next] = new OpenLayers.Feature.Vector
				(	point, 
					{
						type: 1 * uploadRadius 
						,fillColor: symbolFillColor
						,fillOpacity: symbolFillOpacity
						,strokeColor: symbolStrokeColor
						,strokeWidth: symbolStrokeWidth
						,label: newAdd
					}
				);
			}

			else if(pieChartsRequired)
			{
				var pieSize = parseInt(range[i]) * parseInt(uploadRadius) * 8;
				//alert(pieSize)
				var pieContext = buildPieChart(attribs, pieSize, 'p');
				//alert(pieContext.link);
				symbolFillOpacity = 0.8;
				symbolStrokeWidth = 0;
				symbolFillColor = '';
				symbolStrokeColor = '';
				pointFeature[i] = new OpenLayers.Feature.Vector
				(	point, 
					{
						//type: range[i] * uploadRadius, 
						graphicOpacity: symbolFillOpacity,
						externalGraphic: pieContext.link,
						graphicWidth: pieContext.size,
						graphicHeight: pieContext.size,
						strokeWidth: symbolStrokeWidth
					}
				);
			}
			else
			{

				pointFeature[next] = new OpenLayers.Feature.Vector
				(	point, 
					{
						type: 1 * uploadRadius 
						,fillColor: symbolFillColor
						,fillOpacity: symbolFillOpacity
						,strokeColor: symbolStrokeColor
						,strokeWidth: symbolStrokeWidth
					}
				);
			}
		
			
			// add other attributes to pointFeature array of Vector Objects
			pointFeature[next].attributes.description = description;
			pointFeature[next].attributes.fillColor = symbolFillColor;
			pointFeature[next].attributes.fillOpacity = symbolFillOpacity;
			pointFeature[next].attributes.strokeColor = symbolStrokeColor;
			pointFeature[next].attributes.strokeWidth = symbolStrokeWidth;
			if(pieContext)
			{
				pointFeature[next].attributes.graphicOpacity = symbolFillOpacity;
				pointFeature[next].attributes.externalGraphic = pieContext.link;
				pointFeature[next].attributes.graphicWidth = pieContext.size;
				pointFeature[next].attributes.graphicHeight = pieContext.size;
			}
			pointFeature[next].id = current;
			userMarkers.addFeatures(pointFeature[next]);
			//alert(pointFeature[next].geometry.x+", "+pointFeature[next].geometry.y)
			
			//alert('pointFeature = '+pointFeature[current]);
			var numHeadRecs = document.getElementById('header').value;
			current = next + parseInt(numHeadRecs);
			//alert('current = '+current)
			
			// insert the new point into the currently active arrays
			pointAddress[next] = newAdd;
			//recNo[next]= current ;
			pointAcc = 8;
			pointClass	= 'users'
			sortedPoints[next] = pointFeature[next];
			sortedRange[next] = 1;
			sortedRecNo[next] = current + 1;
			sortedAddress[next] = newAdd.toString();
			sortedOldLoc[next] = '';
			
			//for(var n=0; n<sortedPoints.length; n++)
			//{	alert('debug ' +n+ " : "+sortedAddress[n]+" : "+sortedRecNo[n]);	}
			
			// add this new class to the list for display
			var found=false;
			for(var x=0; x<markerClass.length ; x++)
			{
				if(markerClass[x] == pointClass) 
				{	found = true;	break;	}		
			}
			
			// if not already in the list add it
			if(!found)
			{	
				markerClass.push(pointClass);
				markerColor.push(symbolFillColor);
				markerOpacity.push(symbolFillOpacity);
			}

			// rebuild the marker Control panel
			var holderDivObj = document.getElementById('markersList');
			createDestMarkersTable(holderDivObj); 	
			if(valuesPresent)
			{	var holderDivObj = document.getElementById('markersList2');
				createDestMarkersTableValues(holderDivObj); 
			}
			
			// refresh all markers from the current arrays
			filterMarkers(getFilterList())
		}

    });

	inputNew = new OpenLayers.Control.Click();
    map.addControl(inputNew);
    inputNew.activate();

}

function commitAttributeChanges()
{
	// Chck if this is update, create or delete transaction
	if(document.getElementById('commitChanges').value == 'Commit Changes')
	{	document.getElementById('attributeEditor').style.display='none';
		saveAndQuit();
		//alert('file being updated = '+geocodedFile)
		showUserPoints(geocodedFile, '', '');
		// delete files from server
		//if(userMarkers != null){killAllMarkers();}
	}
	else // for a read transaction
	{
		if(document.getElementById('addrEditing').value != '')
		{
			var desiredPoint = document.getElementById('addrEditing').value.toString();
			//alert('desired point = '+desiredPoint)
			var found = false;
			for(var i=0; i<sortedAddress.length ; i++)
			{
				if(sortedAddress[i] == desiredPoint) 
				{
					//var ptLocX = sortedPoints[i].geometry.x;
					//var ptLocY = sortedPoints[i].geometry.y;
					//alert(ptLocX+", "+ptLocY)
					current=i;
					found=true;
					break;
				}
				

			}
			if(found)
			{
				setToMarker(current);
			}
			else{ alert('point address = '+desiredPoint+ ' is not loaded');		}
		}
	}
}

// ------------- function to load all or filtered list of points ------------------//
function filterMarkers(filteredMarkers)
{
	// first time just load all the points
	if(firstTime)
	{
		// just copy all as is - this is for the first time thru
		filteredPoints = sortedPoints;
		filteredRange = sortedRange;
		filteredRecNo = sortedRecNo;
		filteredAddress = sortedAddress;
		filteredOldLoc = sortedOldLoc;
		
		// finally just build the marker Control panel
		var holderDivObj = document.getElementById('markersList');
		createDestMarkersTable(holderDivObj); 	
		if(valuesPresent)
		{	
			var holderDivObj = document.getElementById('markersList2');
			createDestMarkersTableValues(holderDivObj); 
		}	
		firstTime = false;
	}
	
	// reload points as indicated from user selection
	else
	{	
		if(userMarkers)
		{
			//alert('destroying userMarkers and their popups')
			if(popupFlag)	{	popup.destroy(); popup=null;	popupFlag=false;}
			if(userMarkers)	{	userMarkers.destroyFeatures(); 	userMarkers=null;}
			if(vectorLayer2){	vectorLayer2.destroyFeatures(); vectorLayer2=null;}
		}
		filteredPoints = new Array();
		filteredAddress = new Array();
		filteredRange = new Array();
		filteredRecNo = new Array();
		filteredOldLoc = new Array();

		// create a filtered array list from sorted arrays
		var ptr = 0;
		if(vectorFilter == 'byClass')
		{
			//alert('sorted address length = '+sortedPoints.length)
			for (var i=0; i<sortedPoints.length;  i++)
			{
				//alert('i = '+sortedPoints[i].attributes.fillColor)
				for (var ii=0; ii<filteredMarkers.length; ii++)
				{	
					if(sortedPoints[i].attributes.fillColor == filteredMarkers[ii])
					{	
						filteredPoints[ptr] = sortedPoints[i];
						filteredRange[ptr] = sortedRange[i];
						filteredRecNo[ptr] = sortedRecNo[i];
						filteredAddress[ptr] = sortedAddress[i];
						filteredOldLoc[ptr] = sortedOldLoc[i];
						ptr++;
					}
				}
			}
		}
		else if(vectorFilter == 'byValue' && valuesPresent)
		{
			//alert(filteredMarkers)
			for (var i=0; i<sortedPoints.length;  i++)
			{
				for (var ii=0; ii<filteredMarkers.length; ii++)
				{
					if(sortedRange[i] == filteredMarkers[ii]+1)
					{	
						filteredPoints[ptr] = sortedPoints[i];
						filteredRange[ptr] = sortedRange[i];
						filteredRecNo[ptr] = sortedRecNo[i];
						filteredAddress[ptr] = sortedAddress[i];
						filteredOldLoc[ptr] = sortedOldLoc[i];
						ptr++;
					}
				}
			}
		}

		// reset the markerColors and ranges as they could have changed
		var holderDivObj = document.getElementById('markersList');
/*		
		createDestMarkersTable(holderDivObj); 	
		if(valuesPresent)
		{	
			var holderDivObj = document.getElementById('markersList2');
			
			// update the values rows leaving checkboxes as is
			var start = ''; 
			var end = '';
			for (var i=0; i<bdy.length-1; i++)
			{
				start = bdy[i];
				end	  = bdy[i+1];
				var limit = end;
				if(i != bdy.length){var limit = end - 1;}
				if(document.getElementById('value:'+i)){document.getElementById('value:'+i).firstChild.nodeValue = start+" to "+limit;}
			}
			
			createDestMarkersTableValues(holderDivObj); 
		}
		
*/		
		for(var m=0; m<markerClass.length; m++)
		{
			var innerCell = document.getElementById("cellColor:"+m);
			innerCell.style.backgroundColor = markerColor[m];
			var fillNumber = Math.abs(markerOpacity[m] * 100);
			setOpacity(innerCell, fillNumber);
		}
		// now update the ranges
/*		if(valuesPresent)
		{	var holderDivObj = document.getElementById('markersList2');
			createDestMarkersTableValues(holderDivObj); 
		}
*/
	}
	// create the selectmode style if not in pickMode
	if(pickMode)
	{
		// create the style map
		styleMap = new OpenLayers.StyleMap(
		{
			"default":	symbolizer 
	//		,"select":	selectStyle
		});
	}
	else
	{
		// create the style map
		styleMap = new OpenLayers.StyleMap(
		{
			"default":	symbolizer 
			,"select":	selectStyle
		});
	}
	//alert('filtered points = '+filteredPoints.length)
	// create the vector layer and apply the styleMap at the same time
	userMarkers = new OpenLayers.Layer.Vector( "Vector Markers", 
	{	styleMap: styleMap, 
		rendererOptions: {zIndexing: true}
	});
	
	//alert('no of points = ' +  filteredPoints.length)
	// pointFeature is the array of sorted point objects to be added as vector markers
	userMarkers.addFeatures(filteredPoints);				
	map.addLayer(userMarkers);
	
	// activate the refresh button and deactivate the Geocoder button
	userdata=true;
	document.getElementById('refreshButton').style.color='#000000';
	document.getElementById('upButt1').value = 'New Upload';
	userMarkers.refresh();
	
	// activate the select and dragging controls
	activateControls('filterMarkers');
	progress(progressBarVer, '', '') ;
	bringToTop(userMarkers);
	//resetZlevels();
	
}

function activateControls(caller)
{
	//alert('pick mode = '+pickMode)
	if(pickMode){	exitPolygonAggregation();	}
	
	//alert('activate from '+caller);
	if(userMarkers !=null)
	{
		// destroy all drag and select controls
		//if(dragItControl){map.removeControl(dragItControl);}
		//if(selectControl) {map.removeControl(selectControl);}
		//var conts=['Drag','Select'];
		//deactivateControls(conts, 'activateControls');
		
		// create the Drag Feature Control if pickMode is not set AND dragging is set		
		if(document.getElementById('dragMarker'))
		{
			var title = document.getElementById('dragMarker').title;
			//alert('drag title = '+title);
			//alert('pickmode = '+pickMode)
			if(title == 'Turn off Dragging' && !pickMode)
			//if(dragCheckBox && !pickMode)
			
			{	setupDragControl(true);
			/*	//alert('setting up dragging')
				dragItControl = { drag: new OpenLayers.Control.DragFeature(userMarkers, 
				{
					'onComplete': onCompleteMove} 
				)};
				map.addControl(dragItControl['drag']);
				dragItControl['drag'].activate(); */
			}
		}
							 
		//	Create a select feature control and add it to the map.
		selectControl = new OpenLayers.Control.SelectFeature(userMarkers, 
		{	//hover: true
			onSelect: onFeatureSelect 
			,onUnselect: onFeatureUnselect
		});
		map.addControl(selectControl);
		selectControl.activate();
		//alert('select Activated')
	
		//map.Z_INDEX_BASE['Popup'] = 20000;
		//if(userMarkers){userMarkers.setZIndex(map.Z_INDEX_BASE['Popup'] -4000);	 }
		bringToTop(userMarkers);		
		// make sure the file accessing controls are active
		
		if(document.getElementById('pointTheme')) 
		{	document.getElementById('pointTheme').style.display='block';}
		if(document.getElementById('infoThemeDiv')) 
		{	document.getElementById('infoThemeDiv').style.display='block';}
		if(document.getElementById('infoThemeDiv')) 
		{	document.getElementById('infoThemeDiv').style.display='block';}
		if(document.getElementById('filterDiv')) 
		{	document.getElementById('filterDiv').style.display='block';}
		if(document.getElementById('dragDiv')) 
		{	document.getElementById('dragDiv').style.display='block';}
		if(document.getElementById('heatDiv')) 
		{	document.getElementById('heatDiv').style.display='block';}
		if(document.getElementById('editButtons0')) 
		{	document.getElementById('editButtons0').style.display='block';}
		if(document.getElementById('killDiv')) 
		{	document.getElementById('killDiv').style.display='block';}
		
		// now activate the save and report features if csv upload mode
		if(document.getElementById('lrad1').style.backgroundColor == 'white')
		{
			if(document.getElementById('saveDiv')) 
			{	document.getElementById('saveDiv').style.display='block';}
			
			if(document.getElementById('amlOD')) 
			{	document.getElementById('amlOD').style.display='block';}
		}
	}
	
}

function toggleDragging(id)
{
	//alert('id = '+id)
	var dragButtonTitle = document.getElementById(id).title;
	if(dragButtonTitle == 'Turn on Dragging')
	{
		if(userMarkers && !pickMode)
		{	
			document.getElementById(id).title = 'Turn off Dragging';
			depressedDiv(id);
			activateControls('toggleDragging'); 
		} 
	}
	else
	{
		document.getElementById(id).title = 'Turn on Dragging';
		normalDiv(id);
		if (dragItControl)
		{
			var conts = ['Drag'];
			deactivateControls(conts, 'toggleDragging');
		}
	}
}
function toggleHeatmap(id)
{
//alert('id = '+id)
	var heatmapTitle = document.getElementById(id).title;
	if(heatmapTitle == 'Turn on heatmap viewing')
	{
		if(userMarkers)
		{	
			document.getElementById(id).title = 'Turn off heatmap viewing';
			depressedDiv(id);
			// this is where we place the heatmap code
			heatmapControlPanel(true);
			loadHeatmapLayer();
			heatmapLayerVisibility(true);
		} 
	}
	else
	{
		document.getElementById(id).title = 'Turn on heatmap viewing';
		normalDiv(id);
		heatmapControlPanel(false);
		heatmapLayerVisibility(false);
		
	}
}

function heatmapControlPanel(on)
{
	if(document.getElementById('heatmapHolder'))
	{
		if(on){	document.getElementById('heatmapHolder').style.display='block';}
		else  {	document.getElementById('heatmapHolder').style.display='none';	}
	}
}
function loadHeatmapLayer()
{
	// get data from xml file into coordinates array

/*	var coordinates = 
	[
		[ 54.7408333333, 9.43472222222 ],
		[ 54.4700375, 9.51416 ],
		[ 54.6144, 9.894 ],
	]
*/
	//
	
	if(heat){	heat.destroy(); heat=null; }
	heat = new Heatmap.Layer("Heatmap"); 
	
	//alert('filtered points = '+filteredPoints.length)
	for(var vv=0; vv<filteredPoints.length; vv++)
	{
		//alert("point = "+vv+" : "+filteredPoints[vv].geometry.x+", "+filteredPoints[vv].geometry.y);
		var point = new Heatmap.Source(new OpenLayers.LonLat(filteredPoints[vv].geometry.x, filteredPoints[vv].geometry.y));
		heat.addSource(point);
	}
	
	//heat.defaultIntensity = defaultIntensity;
	//heat.defaultradius = defaultRadius;
	heat.setOpacity(0.5);
	map.addLayer(heat);
	map.zoomToExtent(heat.getDataExtent());
	heat.defaultIntensity = defaultIntensity;
	heat.defaultradius = defaultRadius;
	heat.redraw();
}

function adjustHeatmap()
{
	
	// get the intensity value
	var intense = document.getElementById('heatIntensity').value;
	if(intense <= 10 && intense >= 0)
	{
		//alert('value = '+intense);
		intense = parseFloat(intense)/10;
		heat.defaultIntensity = intense;
		heat.redraw();
	}
	else 
	{ 
		document.getElementById('heatIntensity').value = '';
		document.getElementById('heatIntensity').focus();
		return false;
	}
	// now get the radius parameter
	var radius = document.getElementById('heatRadius').value;
	if(radius <= 50 && radius >= 0)
	{
		//alert('value = '+intense);
		radius = parseFloat(radius);
		heat.defaultRadius = radius;
	}
	else 
	{ 
		document.getElementById('heatRadius').value = '';
		document.getElementById('heatRadius').focus();
		return false;
	}
	
	// now get the opacity parameter
	var opacity = document.getElementById('heatOpacity').value;
	if(opacity <= 1 && opacity >= 0)
	{
		//alert('value = '+intense);
		opacity = parseFloat(opacity);
		heat.setOpacity(opacity);
		
	}
	else 
	{ 
		document.getElementById('heatOpacity').value = '';
		document.getElementById('heatOpacity').focus();
		return false;
	}
	heat.redraw();

}



function heatmapLayerVisibility(on)
{
	// toggle existing points first
	if(on)
	{
		userMarkers.setVisibility(false);	
		heat.redraw();
	}
	else
	{
		userMarkers.setVisibility(true);
		userMarkers.redraw();
	}
	heat.setVisibility(on);
}
	
/*	
	var checked = document.getElementById(id).checked;
	//alert('drag checkbox = '+checked)
	if(checked) 
	{	
		if(userMarkers && !pickMode) 
		{	activateControls('toggleDragging'); } 
		else
		{	document.getElementById(id).checked=false;}
	}
	else 
	{ 
		if(dragItControl)
		{ 	
			var conts = ['Drag'];
			deactivateControls(conts, 'toggleDragging');
			//dragItControl['drag'].destroy();	
		}

	}
}

function deactivateControls(conts, caller)
{
	alert('deactivating via '+caller)
	
	if(dragItControl['drag']) {dragItControl['drag'].deactivate(); }
	//if(selectControl != null) {selectControl.deactivate(); selectControl = null;}
	alert('done')
}
*/
function deactivateControls(conts, caller)
{
	//alert('deactivating via '+caller)
	//alert('map controls = '+map.controls.length)
	//alert('controls for deactivation = ' +conts)
	if(map.controls)
	{
		for (var i = 0; i< map.controls.length; i++) 
		{
			//alert('control : '+map.controls[i].displayClass);
			for(var j=0; j<conts.length; j++)
			{
				// check which ones in array are requested for deactivation
				if (map.controls[i].displayClass == "olControl"+conts[j]+"Feature" 	) 
				{		
					//alert('control deactivated = '+map.controls[i].displayClass)						
					map.controls[i].deactivate();
					map.controls[i].destroy();
					//if(map.controls[i] != null){map.controls[i].destroy();}
					
				}
			}
		} 
	}
}

function onFeatureSelect(feature) 
{
	//alert('pickmode = '+pickMode);
	if(pickMode) {return;}
	selectedFeature = feature;
	popupFlag=true;
	
	// extract the Symbol Size from the description data	
	var parts = feature.attributes.description.split('Symbol Size : </b>')
	var rangeIndicator = parts[1].split('<');
	var radiusPixels = parseInt(rangeIndicator[0]) * uploadRadius/4;
	var size = radiusPixels * 2;
	
	// now calculate the pixel off sets from the centre point
	var delX = parseInt(Math.sin(45.0)*radiusPixels);
	var delY = parseInt(Math.cos(45.0)*radiusPixels);
	
	// set up the anchor point
    var anchor = {
		'size': new OpenLayers.Size(0,0), 
		'offset': new OpenLayers.Pixel(delX, -delY)
	};

	// generate the framedCloud popup
/*
	id				{String}
	lonlat			{OpenLayers.LonLat}
	size			{OpenLayers.Size}
	contentHTML		{String}
	anchor			{Object} Object to which we’ll anchor the popup.  Must expose a ‘size’ (OpenLayers.Size) and ‘offset’ (OpenLayers.Pixel) (Note that this is generally an OpenLayers.Icon).
	closeBox		{Boolean}
	closeBoxCallback{Function} Function to be called on closeBox click.

*/
	//if(popup){popup.destroy(); popup=null;}
	popup = new OpenLayers.Popup.FramedCloud
	(	"whatever" 
		,feature.geometry.getBounds().getCenterLonLat()
		,null
		,"<div style='font-size:9px; height:auto; '><br/>"+feature.attributes.description+" <br/></div>"
		,anchor
		,true
		,onPopupClose);

	// add popup to this map feature
	feature.popup = popup;
	map.addPopup(popup);
	popup.panMapIfOutOfView = true;
	//popup.autoSize(true);
	//popup.setOpacity(.90);
	//alert('activating controls')
	//activateControls('onFeatureSelect');
	//resetZlevels();
	
	// set current to the object selected
	//alert(feature.id)
	var numHeadRecs = document.getElementById('header').value;
	current= parseInt(feature.id) - (1+ parseInt(numHeadRecs));
	
	// populate the attribute editor
	//if(document.getElementById('editButtons12').className == 'buttdown')
	//{	crudTransaction('LOAD');}
}

function onPopupClose(evt) 
{	
	selectControl.unselect(selectedFeature); 
	popupFlag=false;
	activateControls('onPopupClose');
	//resetZlevels();
}
					
function onFeatureUnselect(feature) 
{
	if(feature.popup)
	{
		//alert('removing popup1')
		map.removePopup(feature.popup);
		feature.popup.destroy();
		feature.popup = null;
		activateControls('onFeatureSelect');
		resetZlevels();
	}
}

function onCompleteMove(feature)
{
	if(feature && !pickMode)
	{	
		activateControls();
		
		// replace coordinate values in feature attributes
		var pointX = feature.geometry.x;
		var pointY = feature.geometry.y;
		var p = [pointX, pointY];
		if (srs == 'EPSG:900913') 
		{	
			var googlePoint = google2geogs(p)	
			var newP = decodePoint(googlePoint);
			var newLon = newP[0];	
			var newLat = newP[1];
		}
		//alert(feature.id+" : \nOld point = "+pointX+", "+pointY+"\nNew point = "+newLon+", "+newLat)
		// generate a new popup
		var newLoc = new GLatLng(newLat,newLon);
		newDesc = feature.attributes.description;

		// reverse geocode the new point and update the popup
		if(reverse)
		{
			geocoder.getLocations(newLoc, function(response)
			{
				if (!response || response.Status.code != 200) {   alert("Status Code:" + response.Status.code); } 
				else
				{
					place = response.Placemark[0];
					newAdd = place.address; 
					newAcc = place.AddressDetails.Accuracy;

					// get rid of the commas
					newAdd = newAdd.replace(/,/g, "");

					// replace the lat and long values in description string
					var parts = newDesc.split(":")
					newDesc = parts[0]+": </b>"+newAdd+"<br/><b>latitude : </b>"+newLat+"<br/><b>Longitude : </b>"+newLon+"<br/><b>Rec Number : </b>";
					
					
					for(var i=4; i<parts.length; i++)
					{
						newDesc = newDesc+parts[i];
						if(i<parts.length - 1) {	newDesc = newDesc + ":";	}
					}
					
					// now find this point in the sorted array and update its address
					for(var i=0; i<sortedRecNo.length ; i++)
					{	if(feature.id == sortedRecNo[i]) 
						{
							// now update old geometry with new location geometry
							sortedAddress[i] = newAdd.toString();
							break;
						}
					}
				}
				// update the feature's description attribute
				feature.attributes.description = newDesc;
			});
		}
		
		// find this id in sorted array to update the feature's geometry 
		for(var i=0; i<sortedRecNo.length ; i++)
		{	if(feature.id == sortedRecNo[i]) 
			{
				// now update old geometry with new location geometry
				sortedPoints[i].geometry.x = pointX;
				sortedPoints[i].geometry.y = pointY;
				
				// if point editing setup populater form with new data
				if(document.getElementById('latEditing')){document.getElementById('latEditing').value = newLat;}
				if(document.getElementById('lngEditing')){document.getElementById('lngEditing').value = newLon;}
				break;
			}
			
		}
		
		if(feature.popup)
		{
			// close existing popup
			//alert('removing popup2')
			map.removePopup(feature.popup);
			feature.popup.destroy();
			feature.popup = null;
			selectControl.unselect(feature); 
			popupFlag=false;
		}
	}
	// make sure the mouse click on Marker is activated again
	activateControls('onCompleteMove');
	//resetZlevels();

}








function setupSymbols()
{
	template = 
	{
		 fillColor: '${fillColor}' 
		,fillOpacity: '${fillOpacity}'
		,strokeColor: '${strokeColor}'
		,strokeWidth: '${strokeWidth}'
		,pointRadius: "${type}"
		,graphicOpacity: '${graphicOpacity}'
		,externalGraphic: "${externalGraphic}"
		,graphicWidth: "${graphicWidth}"
		,graphicHeight: "${graphicHeight}"
		,label: "${label}"
	//	,graphicZIndex: "${index}"
	};
	

	// set up the default styling for the vector layer
	symbolizer = new OpenLayers.Style(template);
				
	// set up the select styling for the vector layer
	selectStyle = new OpenLayers.Style(
	{ 	
		fillColor: "Green"
		,strokeColor: "White"
		,strokeWidth: '3'
	}); 

	// create the style map
	if(pickMode)
	{
		// create the style map
		styleMap = new OpenLayers.StyleMap(
		{
			"default":	symbolizer 
	//		,"select":	selectStyle
		});
	}
	else
	{
		// create the style map
		styleMap = new OpenLayers.StyleMap(
		{
			"default":	symbolizer 
			,"select":	selectStyle
		});
	}
	userdata = true;
}

// load the arttributes part of description
function loadAttsToDescription()
{
    m=0;
    description +="<br/><br/><b><u>Attribute Data</u></b>";

	// get all allattributes
	for(var z=0; z<attribs.length; z++)
	{
		// if this is an accuracy code swap for the full description
		var attribSupplied = attribs[z].getAttribute("value");
		//alert('type = '+attribs[z].getAttribute('type'))
		if (attribs[z].getAttribute("name") == 'Geocode Accuracy')
		{	
			attribSupplied = accuracyDesc[attribs[z].getAttribute("value")];
			description += 
			"<br/><b>"+attribs[z].getAttribute("name")+
			" : </b>"+attribSupplied;
		}
		// build up the attribute name and value into decription var
		
		else if(attribs[z].getAttribute('type') == 'linkVar' )
		{
			description +=
			"<br/><b>"+attribs[z].getAttribute("name")+
			" : </b><a target='_blank' href='"+attribSupplied+" '>"+attribSupplied+"</a>";
		}
		
		// get the Chart attributes and accumulate in string
		else if(attribs[z].getAttribute('type') == 'chartVar' )
		{
			// get the min/max values for all values
			minVal = attribs[z].getAttribute("min");
			//if(minVal == ''){minVal=0;}
			maxVal = attribs[z].getAttribute("max");
			
			tempVal =  attribs[z].getAttribute("value");
			if(tempVal == '' ){tempVal = 0;} // zero fills a null value
			//if(!checkNumeric(tempVal)){tempVal = 0.0;}
			
			// build up the values and labels strings
			if(m == 0) 
			{	chartVal = tempVal;
				chartLab = attribs[z].getAttribute("name");}
			else 
			{	chartVal += ','+tempVal;
				chartLab += '|'+attribs[z].getAttribute("name");}
			m=m+1;
			
			// finally just add to the popup
			description +=
			"<br/><b>"+attribs[z].getAttribute("name")+
			" : </b>"+attribSupplied;
			chartFlag = true;
		}
		else
		{
			description +=
			"<br/><b>"+attribs[z].getAttribute("name")+
			" : </b>"+attribSupplied;
		}
	}
	description += "<br/><br/>";
}

function buildMapPieChartLegend()
{
	//alert(chartLab)
	//alert(colorArray)
	description+="<br/><br/><b><u>Map Pie Chart Legend Key</u></b><br/></br>";
	var classifications = chartLab.split("|")
	for (var i=0; i<classifications.length; i++)
	{
		//alert('here = '+colorArray[i]+"   "+classifications[i]);
		description+="<table style='width:300px; border-collapse:collapse;'><tr><td style='width:10%; height:20px;'><div style='height:100%; width:100%; padding:1px; background-color:#"+colorArray[i]+"; opacity:0.8; filter:alpha(opacity=80);'></div></td><td><div style='font-weight:bold; width:80%;padding:1px;'>"+classifications[i]+"</div></td></tr></table>";		
	}
	description += "<br/><br/>";
}

function setupPopupDescription(i)
{	
	// Setup info for popup
	description = '';
	var link='http://www.numaps.com.au';
	description = 
		"<div class='attributes'><b><u>Upload Information</u></b>"+
		"<br/><b>Address : </b>"+pointAddress[i]+
		"<br/><b>Latitude : </b>"+pointLat+
		"<br/><b>Longitude : </b>"+pointLon+
		//"<br/><b>"+xtype+" : </b>"+pointX+
		//"<br/><b>"+ytype+" : </b>"+pointY+
		"<br/><b>Rec Number : </b>"+recNo[i]+
		acc+
		"<br/><b>Symbol Size : </b>"+range[i];

	
	// Loop through all the attributes and add them here
	if (attribs.length > 0) 
	{	loadAttsToDescription();	} 
	
	// now add the relocation button
	//description += "<input type='button' id='relocatePoint' value='Move Point' onclick='relocateUploadedPoint();'/><br/><br/>"

	// if charts are requested add not MapPieCharts add to the info bubble
	if(chartFlag)
	{	
		if(document.getElementById('mapPieRadio').checked)
		{
			// generate the mapPieChart legend
			buildMapPieChartLegend();
		}
		else
		{
			// build the popup chart
			document.getElementById('graphRadio').style.display='block';	
			// create Y axis Chart Labels
			var yHigh = parseInt(Math.ceil(maxVal)*1.1);
			var yLow = 0.0;
			
			// get the Chart title from form
			var chartTitle = document.getElementById('chartTitle').value;
			if(chartTitle == ''){chartTitle = 'User defined Chart';}
			
			// get the selected chart type from form
			//if(document.getElementById('mapPieRadio').checked)		{	chart = 'p';	}
			if(document.getElementById('pieRadio').checked)			{	chart = 'p3';	}
			else if (document.getElementById('barRadio').checked)	{	chart = 'bvs';	}
			else if (document.getElementById('lineRadio').checked)	{	chart = 'lc';	}
			//alert(chart)
			// build up the requested chart type
			if(chart == 'p3')											// 3-D Pie Charts
			{
				var request="http://chart.apis.google.com/chart?"+
					"chs=300x150"+
					"&chd=t:"+chartVal+
					"&cht="+chart+
					"&chco=0000FF"+
					"&chl="+chartLab+
					"&chtt="+chartTitle+
					"&chds="+yLow+","+yHigh;
			}
			else if(chart == 'bvs')										// 2-D Bar Charts
			{
				var request="http://chart.apis.google.com/chart?"+
					"chs=300x200"+
					"&chd=t:"+chartVal+
					"&cht="+chart+
					"&chxt=x,y"+
					"&chxr=1,"+yLow+","+yHigh+
					"&chxl=0:|"+chartLab+"|"+
					"&chm=N,FF0000,0,-1,10"+
					"&chco=0000FF"+
					"&chtt="+chartTitle+
					"&chds=0,"+yHigh+
					"&chbh=a";
			}
			else if(chart == 'lc')										// basic line Charts
			{
				var request="http://chart.apis.google.com/chart?"+
					"chs=300x200"+
					"&cht="+chart+
					"&chxt=x,y"+
					"&chxr=1,"+yLow+","+yHigh+
					//"&chxr=1,"+minVal+","+maxVal+
					"&chd=t:"+chartVal+
					"&chds=0,"+yHigh+
					"&chxl=0:|"+chartLab+"|"+
					"&chco=0000FF"+
					"&chtt="+chartTitle+
					"&chbh=a"+
					"&chg=10,10"
			}
			//alert(request)
			//setup the popup data
			description += "<center><div id='chartId' style='width:300px; height:200px; border:1px solid gray;' ><img src='"+request+"' /></div></center>";
		}
		
	}
	//alert('description:\n'+description)
	return description;
}

function toggleAllClasses(thisObj)
{
	// Determine the status desired
	if(thisObj.title == 'show all classes')
	{	var checkedSwitch = true; 
		thisObj.title='hide all classes'; 
	}
	else 
	{	var checkedSwitch = false; 
		thisObj.title='show all classes';
	}

	// now change all the checkboxes for ByClass tab
	if(thisObj.id == 'allClassesCheckbox')
	{
		for(var i=0; i<markerClass.length; i++)
		{	document.getElementById('markerClass:'+i).checked = checkedSwitch;		}
	}
	
	// now change all the checkboxes for ByValue tab
	else if(thisObj.id == 'allClassesCheckbox2' )
	{
		for(var i=0; i<bdy.length-1; i++)
		{	document.getElementById('markerValue2:'+i).checked = checkedSwitch;		}
	}
	//resetZlevels();
}

//-----------  get all the checked filter classes ----------//
function getFilterList()
{
	//alert('marker Class len = '+markerClass.length);
	filteredMarkers = [];
	
	// check for the Classification Filters
	//alert('vectorFilter = '+vectorFilter)
	if(vectorFilter == 'byClass')
	{
		for (var i=0; i < markerClass.length ; i++)
		{
			//alert(markerColor[i])
			if (document.getElementById('markerClass:'+i).checked)
			{	filteredMarkers.push(markerColor[i]);	}
		}
	}
	// check for Values Filters
	else if(vectorFilter == 'byValue' && valuesPresent)
	{
		for (var i=0; i < uploadDivs ; i++)
		{
			if (document.getElementById('markerValue2:'+i).checked)
			{	filteredMarkers.push(i);	}
		}
	}
	//alert('filtered markers list = '+filteredMarkers)
	return filteredMarkers;
}


function initializeForms()
{
	//alert('initializing everything');
	
	// initialize all forms back to start
	if(document.form1)								{document.form1.file1.value = '';}
	if(document.getElementById('header'))			{document.getElementById('header').value='';}
	if(document.getElementById('addressCols'))		{document.getElementById('addressCols').value=''; }
	if(document.getElementById('latlongCols'))		{document.getElementById('latlongCols').value=''; }
	if(document.getElementById('symbolCols'))		{document.getElementById('symbolCols').value=''; }
	if(document.getElementById('classCols'))		{document.getElementById('classCols').value=''; }
	if(document.getElementById('edurButton11'))		{document.getElementById('edurButton11').className = 'buttup';}
	if(document.getElementById('userAbs'))		{document.getElementById('userAbs').value ='';}
	var labelObj = document.getElementById('addrInstruct');
	labelObj.firstChild.nodeValue = '*Address Cols:';

	var selectObject = document.getElementById('geocodeOptions');
	selectObject.selectedIndex = 0;
	//geocodeLayerName = selectObject.options[selectObject.selectedIndex].value;

	if(document.getElementById('progBar'))			
	{
		document.getElementById('progBar').style.borderStyle='none'; 
		document.getElementById('progBar').style.display='none'; 
	}
	if(document.getElementById('progBar2'))			
	{
		document.getElementById('progBar2').style.borderStyle='none'; 
		document.getElementById('progBar2').style.display='none'; 
	}
	checkRemoveObject('indicText');
	if(document.getElementById('red'))				{document.getElementById('red').checked='checked'; }
	if(document.getElementById('graphCols'))		{document.getElementById('graphCols').value=''; }
	if(document.getElementById('pieRadio'))			{document.getElementById('pieRadio').checked='checked'; }
	if(document.getElementById('chartTitle'))		{document.getElementById('chartTitle').value = 'User Defined Chart'; }
	if(document.getElementById('refreshButton'))	
	{	document.getElementById('refreshButton').style.display='block';	document.getElementById('refreshButton').style.color='gray';	}
	if(document.getElementById('upButt1'))			
	{	document.getElementById('upButt1').value='Geocode Data'; document.getElementById('upButt1').style.color='gray';}
	

	//reset the controls
	//document.getElementById('markerOnOff').src='images/mark_off.jpg';
	if(document.getElementById('pointTheme')) 
	{	document.getElementById('pointTheme').style.display='none'; document.getElementById('pointTheme').title='show point thematics editor control';}
	if(document.getElementById('infoThemeDiv')) 
	{	document.getElementById('infoThemeDiv').style.display='none'; document.getElementById('infoThemeDiv').title='bring points to top to click them';}
	if(document.getElementById('filterDiv')) 
	{	document.getElementById('filterDiv').style.display='none'; document.getElementById('filterDiv').title='show marker filter control';}
	if(document.getElementById('dragDiv')) 
	{	document.getElementById('dragDiv').style.display='none'; document.getElementById('dragDiv').title = 'Turn On Dragging';}
	if(document.getElementById('heatDiv'))
	{	document.getElementById('heatDiv').style.display='none'; document.getElementById('heatDiv').title = 'Turn on heatmap viewing';}
	if(document.getElementById('saveDiv')) 
	{	document.getElementById('saveDiv').style.display='none';}
	if(document.getElementById('killDiv')) 
	{	document.getElementById('killDiv').style.display='none';}
	if(document.getElementById('amlOD')) 
	{	document.getElementById('amlOD').style.display='none';}
	if(document.getElementById('editButtons0')) 
	{	
		document.getElementById('editButtons0').style.display='none';
		document.getElementById('editButtons5').style.display='none';
		document.getElementById('editButtons6').style.display='none';
	}
	
	if(document.getElementById('editButtons'))		{document.getElementById('editButtons').style.display='none';}
	if(document.getElementById('graphRadio'))		{document.getElementById('graphRadio').style.display='none'; }
	if(document.getElementById('zmto1'))			{document.getElementById('zmto1').disabled=false; }
	if(document.getElementById('zmto2'))			{document.getElementById('zmto2').disabled=false; }

	// reset the filter panel
	if(document.getElementById('markersHolder'))	{document.getElementById('markersHolder').style.display='none';}
	//if(document.getElementById('markerDownload'))	{document.getElementById('markerDownload').title = 'Show geocoded CSV file and allow user to download';}
	//if(document.getElementById('markerDownload'))	{document.getElementById('markerVisOnOff').src='images/markv_off.jpg';}

	// reset the point Thematics panel
	if(document.getElementById('pointThematics'))	{document.getElementById('pointThematics').style.display='none';}
	document.getElementById('redOpt').checked=false;
	document.getElementById('blueOpt').checked=false;
	document.getElementById('greenOpt').checked=false;
	document.getElementById('yellowOpt').checked=false;
	//if(document.getElementById('markerVisOnOff'))	{document.getElementById('markerVisOnOff').title = 'show marker visibility control';}
	//if(document.getElementById('markerVisOnOff'))	{document.getElementById('markerVisOnOff').src='images/markv_off.jpg';}

	if(document.getElementById("attributeEditor")) {document.getElementById("attributeEditor").style.display="none";}

	// now reset all event controls
	deactivateControls('','initializeForms');
	//alert('input new = '+inputNew)
	if(inputNew) {inputNew.deactivate();}
	if(dragItControl) {dragItControl['drag'].deactivate();}
	
	firstTime=true;
	userdata = false;
	pickMode=false;
	currentXmlRow = -1;
	rangesDone = false;
	overrideAttribute = '';
	xmlTitle = '';
	xmlAbstract = '';

	// make sure all marker arrays are reinitialised
	sortedPoints = new Array();
	sortedAddress =  new Array();
	range =  new Array();
	sortedRange =  new Array();
	sortedRecNo =  new Array();
	sortedOldLoc =  new Array();
	recNo =  new Array();
	pointAddress =  new Array();
	pointFeature =  new Array();
	oldLocation =  new Array();
	markerClass =  new Array();
	markerColor =  new Array();
	markerOpacity =  new Array();

	// make sure the published list file is set back to normal
	if (noOfXml > 0)
	{
		for(var i=0; i<noOfXml ; i++)
		{
			document.getElementById('upload_op:'+i).className = 'unselectedItem';
			document.getElementById('upload_kill:'+i).className = 'unselectedItem';
			document.getElementById('upload_name:'+i).className = 'unselectedItem';
		}
	}
	// make sure all zlevels are reset
	//resetZlevels();

}

function killAllMarkers()
{
	//alert('about to kill all markers')
	// set all forms back to beginning
	initializeForms();
	
	// do the actual layer kill
	killMarkers();
	//deleteAllUploadedFiles("lrad1")
}

function killMarkers()
{
	if(userMarkers)
	{
		//alert('destroying userMarkers')
		if(popupFlag)	{	popup.destroy(); popup=null;	popupFlag=false;}
		if(userMarkers)	{	userMarkers.destroyFeatures(); 	userMarkers=null;}
		if(vectorLayer2){	vectorLayer2.destroyFeatures(); vectorLayer2=null;}
	}
	//alert('about to kill off uploaded files');
	//deleteAllUploadedFiles("lrad1")
	userdata = false;
}

function publishXml()
{
	// get the user entered description/title
	var title = document.getElementById('userAbs').value;
	title = title.replace(/ /g,"_")
	//alert(title)

	// set up the source file
	var source = "/inc/"+geocodedFile;
	//alert('source = '+source)

	// strip out the path info
	//var parts = geocodedFile.split('/');
	var testFilename = "useroverlays/preGeocoded/"+title+".xml"; 
	var destination = "/inc/"+testFilename;
	//alert('destination = '+destination)	
	//alert('testFileName = '+testFilename);

	// check to see if the destination file already exists
	if (filePresent(testFilename))
	{ 
		if(!confirm ('"'+testFilename+'" already exists.\nIf you continue you will overwrite this the existing XML file on the server.\n\n Do you wish to continue?'))
		{
			return;
		}
	}

	// go ahead and rename the file
	if(!replaceFileCF(source, destination))
	{alert('error on rename');}
	else
	// rebuild the list of files
	{
		genLoadStatus('Fetching List of Files ...', true)
			//(folder, holderId, xmlTag, xmlAttrib, xmlAbstractId, filePrefix)
		makeTableSelectControl('useroverlays/preGeocoded/', 'publishedList', 'Addresses', 'name', 'abstract', 'upload');
		document.getElementById('saveDiv').style.display='none';
		if(!fileUploaded)
		{	document.getElementById('amlOD').style.display='none';}
		genLoadStatus('', false)
	}
	xmlPublished = true;
}

function toggleMarkersVisibility(buttId, holderId)
{
	if(fileUploaded || xmlFileActive)
	{
		//alert('button Id = '+buttId)
		var title = document.getElementById(buttId).title;
		var titleBits = title.split(" ")
		if (titleBits[0] == 'hide')
		{	
			document.getElementById(holderId).style.display='none';
			document.getElementById(buttId).title = document.getElementById(buttId).title.replace(/hide/,"show");
			//mouseup(buttId)
			normalDiv(buttId)
		}
		else if (titleBits[0] == 'show')
		{
			document.getElementById(holderId).style.display='block';
			document.getElementById(buttId).title = document.getElementById(buttId).title.replace(/show/,'hide');
			depressedDiv(buttId);
		}
	}
	else
	{
		document.getElementById(buttId).title = document.getElementById(buttId).title.replace(/show/,'hide');
		normalDiv(buttId)
	}
	//resetZlevels();
}

function deleteAllUploadedFiles(id)
{
	//if(!userdata) { return;}
	
	// specify the file as selected in radio buttons
	
	var csv = '';
	if(geocodedCsv != '' || geocodedCsv){	csv = 'useroverlays/'+geocodedCsv; }
	deleteit(csv);
		
	// now show the file and delete it after if requested
	//alert('published flag in deleteAllUploadedFiles = '+xmlPublished)
	if(!xmlPublished) 
	{
		var xml = geocodedFile;
		deleteit(xml);
	}
	xmlPublished = false;

	// now set back to start
	userdata = false;
	//changeSource(id);

}

function downloadCsv(id)
{
	//alert('userdata flag = '+userdata)
	if(!userdata) {	return;	}
	// specify the file as selected in radio buttons
	//var xml = 'useroverlays/'+geocodedFile;
	//alert('csv filename = '+geocodedCsv)
	var csv='';
	if(geocodedCsv != '' || geocodedCsv){	csv = 'useroverlays/'+geocodedCsv; }
	if(csv == '') {	return;	}
	
		
	// now show the file and delete it after if requested
	if(filePresent(csv))
	{
		//normalDiv(id);
		startDownload('inc/'+csv)
		//makePopup('inc/'+csv, 600, 600, 'both');
		//if(delme){deleteit(processFile);}	
	}
	
}

  
function checkComplete()
{
	if( document.getElementById('userAbs').value != '' &&
		document.getElementById('header').value != '' && 
		document.getElementById('addressCols').value != '' && 
		document.getElementById('latlongCols').value != '' )
		{ document.getElementById('upButt1').style.color = 'black';}
}
// ------------------- validate file types entered for uploading ---------------//
function fileCheck1() 
{
	// if a data set is already loaded simply switch to upload mode
	//alert(document.getElementById('upButt1').value );
	if(document.getElementById('upButt1').value != 'Geocode Data' )
	{
		//alert('returning to upload mode')
		killAllMarkers();
		document.getElementById('upButt1').value = 'Geocode Data';
		checkComplete();
		return false;
	}

	if(document.getElementById('amlOD')) 
	{	document.getElementById('amlOD').style.display='none';}
	if(document.getElementById('saveDiv'))
	{	document.getElementById('saveDiv').style.display='none';}
	
	// check that header rows have been selected 0,1,2 are valid
	csvHeadRows = document.getElementById('header').value; 
	//alert(csvHeadRows)
	if(csvHeadRows !=0 && csvHeadRows !=1 && csvHeadRows !=2 ) 
	{	alert('You can only have 0 to 2 Header rows. e.g. 0 or 1 or 2 only'); 
		document.form1.header.focus(); 
		return false;
	}
	// ----------------- the user MUST enter an Abstract field
	var userAbstract = document.getElementById('userAbs').value;
	if(userAbstract == null)
	{	alert('please enter a Description/Abstract for this uploaded file');
		doecument.form1.userAbs.focus();
		return false;
	}
	// push abstact into hidden form
	else{	document.getElementById('userAbstract').value = userAbstract;	}
	
	// ----------------- the user MUST enter the address columns
	csvAddrCols = document.getElementById('addressCols').value; 
	if(csvAddrCols == null || csvAddrCols == '')
	{	alert('Please enter columns used for Address data. e.g. 1 or 1-3');
		document.form1.addressCols.focus(); 
		return false;
	}
	else
	{
		// covert alpha to numerics
		returnedValue = alphaToNumeric(csvAddrCols);
		if(returnedValue == '0')	
		{	alert('Please enter columns used for Address data. e.g. 1 or 1-3');
			document.form1.addressCols.focus(); 
			return false;
		}
		else { csvAddrCols = returnedValue; }
	}
	document.form1.addressCols.value = csvAddrCols;
	//alert(csvAddrCols)

	// ---------------- the user MUST enter latlong columns
	csvLatLongCols = document.getElementById('latlongCols').value; 

	if(csvLatLongCols == null || csvLatLongCols == '')
	{	alert('Please enter columns used for Latitude and Longitude data. e.g. 3-4 or c-d or C-D');		
		document.form1.latlongCols.focus(); return false;}
	else
	{
		// covert alpha to numerics
		returnedValue = alphaToNumeric(csvLatLongCols);
		if(returnedValue == '0')	
		{	alert('Please enter columns used for Latitude and Longitude data. e.g. 3-4 or c-d or C-D');
			document.form1.latlongCols.focus(); return false;
		}
		else { csvLatLongCols = returnedValue; }
	}
	document.form1.latlongCols.value = csvLatLongCols;
	//alert(csvLatLongCols)

	// ----------------- Optional entry for Value to scale symbol
	csvSymbolCol = document.getElementById('symbolCols').value; 
	if(csvSymbolCol && csvSymbolCol != '')
	{
		// covert alpha to numerics
		returnedValue = alphaToNumeric(csvSymbolCol);
		if(returnedValue == '0')	
		{	alert('Marker scaling column must be alpha or numeric or nothing e.g. 2 or B');
			document.form1.symbolCols.focus(); return false;}
		else { csvSymbolCol = returnedValue; }
		document.form1.symbolCols.value = csvSymbolCol;
	}
	//alert(csvSymbolCol)

	// ---------------- Optional entry for classification/colour columns
	csvColorCols = document.getElementById('classCols').value; 
	if(csvColorCols && csvColorCols != '')
	{	// covert alpha to numerics
		returnedValue = alphaToNumeric(csvColorCols);
		if(returnedValue == '0')	
		{	alert('Please enter columns used for Classification & Colour columns data. e.g. 3-4 or c-d or C-D');
			document.form1.classCols.focus(); 
			return false;
		}
		else { csvColorCols = returnedValue; }
		document.form1.classCols.value = csvColorCols;
	}
	//alert(csvColorCols)

	 // --------------- Optional entry for graph columns
	csvChartCol = document.getElementById('graphCols').value; 
	if(csvChartCol && csvChartCol != '')
	{
		// covert alpha to numerics
		returnedValue = alphaToNumeric(csvChartCol);
		if(returnedValue == '0')	
		{	alert('Please enter columns used for Address data. e.g. 1 or 1-3 or a-c or A-C');
			document.form1.graphCols.focus(); return false;}
		else { csvChartCol = returnedValue; }
		document.form1.graphCols.value = csvChartCol;
	}
	//alert(csvChartCol)

	//------------- automatically add the date stamp to the form
	document.form1.stamp.value = getStamp();
	//alert('OK')
	
	// check uploaded file extension
	uploadFilename = document.form1.file1.value;

	if(document.getElementById('uploadedFilename')){document.getElementById('uploadedFilename').value= 'useroverlays/'+uploadFilename;}
	if (uploadFilename)
	{
		ext = uploadFilename.substring(uploadFilename.length-3,uploadFilename.length);
		ext = ext.toLowerCase();
		var file = uploadFilename.split(".");
		geocodedFile = file[0]+".xml";
		if(ext != 'csv' && ext != 'xml' ) 
		{	alert('You selected a .'+ext+' file; please select only a .csv or a .xml file instead!');  
			return	false; 
		}
		else
		{		
			// extract just the filename being uploaded
			var parts = uploadFilename.split("\\");
			uploadFilename = parts[parts.length-1]
			document.getElementById('upButt1').style.display='block';
			document.getElementById('upButt1').blur();
			fileUploaded =  true;
			firstTime = true;

			// get the header records from uploaded file
			progressBar(progressBarVer,'Uploading Data', '');
			//if(document.getElementById('eventsLogID')){document.getElementById('eventsLogID').styple.display='block';}
			//alert('done')
			return true; 
		}
	}
}

function alphaToNumeric(csvAddrCols)
{
	var parts = csvAddrCols.split('-');
	
	// process first part
	var firstNumber = 0;  var secondNumber = 0;
	firstNumber = oneAlphaToNumber(parts[0]);
	
	// if necessary process the second part
	if (parts.length > 1)
	{ var secondNumber = oneAlphaToNumber(parts[1]);}
	
	// build the new returned number string
	if(firstNumber == 0 || (secondNumber == 0 && parts.length > 1)) 
	{	returnedNumber = '0';		}
	else 
	{ 
		returnedNumber = firstNumber.toString()
		if (parts.length > 1)
		{	returnedNumber += '-'+secondNumber.toString();	}	
	}
	return returnedNumber;
	
}

function oneAlphaToNumber(letNo)
{
	//alert('letno = '+letNo)
	var alphabet = new Array("A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q",
"R","S","T","U","V","W","X","Y","Z");
	if(checkNumeric(letNo)) {return letNo;}
	else 
	// converts a letter into a number 1-26
	{
		var test = letNo.toUpperCase();
		var number = 0;
		for (var i=0 ; alphabet.length ; i++)
		{	if(test == alphabet[i]) { var number = i+1; break; } 	}
		return number;
	}
}

function stepThruMarkers(moveType)
{
	//alert('current zoom = '+map.getZoom());
	//alert('current = '+current)
	//alert('total in file = '+sortedOldLoc.length);
	markerZm = map.getZoom();
	if(moveType == 'START')		{	setToMarker(0); }
	else if(moveType == 'BACK')	{	setToMarker(current-1); }
	else if(moveType == 'NEXT')	{	setToMarker(current+1); }
	else if(moveType == 'END')	{	setToMarker(sortedOldLoc.length-1); }
}

function setToMarker(arrayNumber)
{
	//alert(current+" "+arrayNumber)
	if(arrayNumber < 0 ){return;}
	if(arrayNumber >= sortedOldLoc.length){return;}
		
	// get the stored coords of point
	var pointX = sortedPoints[arrayNumber].geometry.x
	var pointY = sortedPoints[arrayNumber].geometry.y
	
	var desc = sortedPoints[arrayNumber].attributes.description ;
	//alert(desc)
	// set to the new point
	var markerLoc = new OpenLayers.LonLat(pointX, pointY);
	//map.setCenter(markerLoc, 14);
	map.setCenter(markerLoc, map.getZoom());
	userMarkers.refresh();
	current = arrayNumber;
	//var startNum = 1; var endNum = sortedOldLoc.length;
	
	// now put bar on the Progress Bar window as a record pointer
	if(document.getElementById(progressBarVer)) {	recordNumber (progressBarVer, current+1, sortedOldLoc.length);}
	//resetZlevels();

	// populate the attribute editor if in READ, UPDATE or DELETE mode
	if(document.getElementById('editButtons12').className == 'buttdown' ){crudTransaction('LOAD')}
	if(document.getElementById('editButtons13').className == 'buttdown' ){crudTransaction('LOAD')}
	if(document.getElementById('editButtons14').className == 'buttdown' ){crudTransaction('LOAD')}
	
}

function saveAndQuit()
{
	if(progressBarVer == 'progBar2')
	{alert ('Save is not available for pre-Geocoded XML files'); return; }

	popAllButts();
	
	// parse each object in the uploaded points array
	var fileRow = []; var fileCell = []; var dataCellX = []; var dataCellY = []; var dataAddr = []; var transType = [];
	var k=0;
	var updateString = '';  

	for (var i=0; i<sortedPoints.length ; i++ )
	{	
		//alert(sortedPoints[i].geometry.x+", "+sortedPoints[i].geometry.y)
		// get coords first
		if(sortedPoints[i].geometry.x == null || sortedPoints[i].geometry.y == null)
		{
			transType[k] = 'delete';
			// build up the transaction arrays
			fileRow[k] = sortedRecNo[i];
			dataAddr[k] = sortedAddress[i];
			dataCellX[k] = pointX;
			dataCellY[k] = pointY;
			k=k+1
		}
		else
		{		
			// transform new plotted point into EPSG:4236 if required
			if (srs == 'EPSG:900913') 
			{
				p = [sortedPoints[i].geometry.x, sortedPoints[i].geometry.y];
				var point = google2geogs(p)
				var newP = decodePoint(point);
				pointX = roundNumber(newP[0],8);
				pointY = roundNumber(newP[1],8);
			}
		//	alert('new Point = '+i+" : "+pointX+", "+pointY)
			// check to see if the coordinates have changed against saved coords
			var coords = sortedOldLoc[i].split(",");
		//	alert('old Point = '+i+" : "+coords)
			var testX = roundNumber(coords[0],8); 
			var testY = roundNumber(coords[1],8);
			
			// check if point has been moved
			if(testX != pointX || testY != pointY)
			{			
				transType[k] = 'update';
				if(testX == '' || testY == '')	{transType[k] = 'create';}
				
				// build up the transaction arrays
				fileRow[k] = sortedRecNo[i];
				dataAddr[k] = sortedAddress[i];
				dataCellX[k] = pointX;
				dataCellY[k] = pointY;
				k=k+1
			}
		}
	}

	// remove the _new from the xml file
	
	// turn off the editing buttons block
	document.getElementById("editButtons0").style.display="none"; 

	// now send the updates transaction string to the server 
	var url = 'inc/updateCsvFile.php';
	var query = '?file=useroverlays/'+geocodedCsv;
	query += '&headRows='+csvHeadRows;
	query += '&addrCols='+csvAddrCols;
	query += '&latLngCols='+document.getElementById('latlongCols').value;
	query += '&row='+fileRow;
	query += '&addr='+dataAddr;
	query += '&x='+dataCellX;
	query += '&y='+dataCellY;
	query += '&trans='+transType;
	query += '&newAbs='+document.getElementById('fileAbstract').value;

	//document.write(url+query)
	// now go off to server and generate a new updated csv file
	loadXml(url, query, false);

	// force the download to start
	downloadCsv('markerDownload');
	
	document.getElementById("progBar").style.display='none';
	initializeForms();
	userdata=true;

	// present the two file management buttons on panel
	document.getElementById("killDiv").style.display='block';
	document.getElementById("amlOD").style.display='block';
	if(fileUploaded){document.getElementById('saveDiv').style.display='block';}

}

function quitNoSave()
{
	//alert('quit and no save');
	document.getElementById("editButtons0").style.display="none"; 
	document.getElementById("progBar").style.display='none';
	//document.getElementById("editMarkers").style.display="block";
	if(userMarkers){killAllMarkers();}
}

function switchFilter(selectedObj)
{
	// this will switch from classification to values filtering and back via Tabs
	if(selectedObj.id == 'byValue')
	{	
		var classif = document.getElementById('byClass');
		selectedObj.style.zIndex = '10001';
		selectedObj.style.backgroundColor='#ECE9D8';
		classif.style.zIndex = '9999';
		classif.style.backgroundColor='#ffffff';
		document.getElementById('markersValuesInner').style.display='block';
		document.getElementById('markersInner').style.display='none';
		vectorFilter = 'byValue';

		// now reset all checkboxes for the ByClass tab
		for(var i=0; i<markerClass.length; i++)
		{
			document.getElementById('markerClass:'+i).checked = true;
		}
		document.getElementById('allClassesCheckbox').checked=true;
		
	}
	else
	{
		var value = document.getElementById('byValue');
		selectedObj.style.zIndex = '10001';
		selectedObj.style.backgroundColor='#ECE9D8';
		value.style.zIndex = '9999';
		value.style.backgroundColor='#ffffff';
		document.getElementById('markersInner').style.display='block';
		document.getElementById('markersValuesInner').style.display='none';
		vectorFilter = 'byClass';

		// now reset all checkboxes for the ByValue tab
		if(valuesPresent)
		{
			for(var i=0; i<bdy.length-1; i++)
			{
				document.getElementById('markerValue2:'+i).checked = true;
			}
			document.getElementById('allClassesCheckbox2').checked=true;
		}
	}
	//resetZlevels();
}

function createDestMarkersTable(holderDivObj)
{
	// inputs are two arrays markerClass (name of class) and markerColor (marker color)
	// also needs the name of object that the table will be attached to holderDivObj
	//alert(markerColor)
	// first kill off any existing table
	checkRemoveObject('destMarkersTable');

	// create the surrounding Form element <form  action='' id='reptRadioButts'>
	var markersForm = document.createElement('form');
	markersForm.id='destMarkersTable'; markersForm.setAttribute('id','destMarkersTable');
	markersForm.action=''; markersForm.setAttribute('action','');
	markersForm.setAttribute('name','markersName'); 
	markersForm.name='markersName';	
	
	// create the Table element
	var markersTable = document.createElement('table');
	markersTable.style.top='0px';
	markersTable.style.left='0px';
	markersTable.style.height='auto';
	markersTable.style.width='100%';
	markersTable.style.overflowY='auto'; 
	markersTable.style.borderCollapse='collapse';
		var markersTableBody = document.createElement('tbody');
		
		// add each row to the body
		var found=false;
		for (var i=0; i < markerClass.length ; i++)
		{
			// Create the Row
			var innerRow = document.createElement('tr');
				
				// now the TD cell for filter Checkbox
				var innerCell = document.createElement('td');
				innerCell.style.height='15px';
				innerCell.style.width='40px';
				innerCell.style.fontSize='10px'; 
				
				// set the background color to match marker color
				innerCell.style.backgroundColor = markerColor[i];
				var fillNumber = Math.abs(markerOpacity[i] * 100);
				setOpacity(innerCell, fillNumber);
				innerCell.id = "cellColor:"+i; innerCell.setAttribute('id','cellColor:'+i);

					// create the Input checkbox for Attribute Summation
					var box = document.createElement('input');
					box.setAttribute('type','checkbox');
					box.value = 'braddles';
					box.setAttribute('name','markersName'); box.name='markersName';
					box.setAttribute('id','markerClass:'+i); box.id='markerClass:'+i;
					box.style.backgroundColor='transparent';
					box.title='show markers';
					
					// if all markers checked then set all
					box.checked = document.getElementById('allClassesCheckbox').checked;	
					box.setAttribute('checked', document.getElementById('allClassesCheckbox').checked);
					
					if(browser == 'msie') {box.setAttribute('defaultChecked', 'defaultChecked');}
					// attach the interactive event handler
					//bindEvent(box, 'click', toggleMarkers, 'false');
					//if(browser == 'msie'){bindEvent(box, 'click', blurIt, 'false');}
					innerCell.appendChild(box);
			innerRow.appendChild(innerCell)	;
			

				// now add the TD cell for the attribute name
				var innerCell = document.createElement('td');
				innerCell.style.height='15px';
				//innerCell.style.width='80%';
				innerCell.style.fontSize='10px';
				innerCell.style.overflowX='auto'; 
				//innerCell.style.backgroundColor = markerColor[i];
				//setOpacity(innerCell, fillNumber);

					// now add a Div inside TD cell with its own opacity
					var innerDiv = document.createElement('div')
					innerDiv.style.width='100%'
					innerDiv.style.height='100%';
					innerDiv.id='class:'+i; innerCell.setAttribute('id','class:'+i);
					innerDiv.style.float = 'left';
					var textElement = document.createTextNode(markerClass[i]);
					innerDiv.appendChild(textElement);
					var solid = Math.abs(100);
					setOpacity(innerDiv, solid);
					innerDiv.style.zIndex='5000';
				innerCell.appendChild(innerDiv)
				
			innerRow.appendChild(innerCell)	;
			markersTableBody.appendChild(innerRow);
		}
	markersTable.appendChild(markersTableBody);
    markersForm.appendChild(markersTable);
	holderDivObj.appendChild(markersForm);
}
function createDestMarkersTableValues(holderDivObj)
{
	// inputs are two arrays markerClass (name of class) and markerColor (marker color)
	// also needs the name of object that the table will be attached to holderDivObj
	
	// first kill off any existing table
	checkRemoveObject('destMarkersTable2');

	// create the surrounding Form element <form  action='' id='reptRadioButts'>
	var markersForm = document.createElement('form');
	markersForm.id='destMarkersTable2'; 
	markersForm.setAttribute('id','destMarkersTable2');
	markersForm.action='';
	markersForm.setAttribute('action','');
	markersForm.setAttribute('name','markersName2'); 
	markersForm.name='markersName2';	
	
	// create the Table element
	var markersTable = document.createElement('table');
	markersTable.style.top='0px';
	markersTable.style.left='0px';
	markersTable.style.height='auto';
	markersTable.style.width='100%';
	markersTable.style.overflowY='auto'; 
	markersTable.style.borderCollapse='collapse';
		var markersTableBody = document.createElement('tbody');
		
		// add each row to the body
		var found=false;

		for (var i=0; i < bdy.length-1 ; i++)
		{
			// Create the Row
			var start = ''; var end = '';
			var innerRow = document.createElement('tr');
			start = bdy[i];
			end	  = bdy[i+1];
			
				// now the TD cell for filter Checkbox
				var innerCell = document.createElement('td');
				innerCell.style.height='15px';
				innerCell.style.width='40px';
				innerCell.style.fontSize='10px'; 

					// create the Input checkbox for Attribute Ranges
					var box = document.createElement('input');
					box.setAttribute('type','checkbox');
					//box.value = 'braddles';
					box.setAttribute('name','markersName2'); box.name='markersName2';
					box.setAttribute('id','markerValue2:'+i); box.id='markerValue2:'+i;
					box.style.backgroundColor='transparent';
					box.title='show markers';
		
					box.checked = document.getElementById("allClassesCheckbox2").checked;	
					if(browser == 'msie') {box.setAttribute('defaultChecked', 'defaultChecked');}
					// attach the interactive event handler
					//bindEvent(box, 'click', toggleMarkers, 'false');
					//if(browser == 'msie'){bindEvent(box, 'click', blurIt, 'false');}
					innerCell.appendChild(box);
			innerRow.appendChild(innerCell)	;
			

				// now add the TD cell for the attribute name
				var innerCell = document.createElement('td');
				innerCell.style.height='15px';
				//innerCell.style.width='80%';
				innerCell.style.fontSize='10px';
				innerCell.style.overflowX='auto'; 
				//innerCell.style.backgroundColor = markerColor[i];
				//setOpacity(innerCell, fillNumber);

					// now add a Div inside TD cell with its own opacity
					var innerDiv = document.createElement('div')
					innerDiv.style.width='100%'
					innerDiv.style.height='100%';
					innerDiv.id='value:'+i; 
					innerDiv.setAttribute('id','value:'+i);
					innerDiv.style.float = 'left';
					var limit = end;
					if(i != bdy.length){var limit = end - 1;}
					var textElement = document.createTextNode(start+" to "+limit);
					innerDiv.appendChild(textElement);
					//var solid = Math.abs(100);
					//setOpacity(innerDiv, solid);
					innerDiv.style.zIndex='5000';
				innerCell.appendChild(innerDiv)
				
			innerRow.appendChild(innerCell)	;
			markersTableBody.appendChild(innerRow);
		}
	markersTable.appendChild(markersTableBody);
    markersForm.appendChild(markersTable);
	holderDivObj.appendChild(markersForm);
}

