//------------- 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)
{
	progressBar('progBar', 'Adding Points...', '') ;
	// 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('editButtons')) 
	{	document.getElementById('editButtons').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;
	if(!showUserPoints(geocodedFile))
	{	
		progressBar('progBar', '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';}
	
	progressBar('progBar', '', '') ;

	// activate all the file control buttons
	document.getElementById('filterDiv').style.display='block';
	document.getElementById('dragDiv').style.display='block';
	document.getElementById('saveDiv').style.display='block';
	document.getElementById('killDiv').style.display='block';
}

function changeSource(Id)
{
	//alert(Id)
	if(userMarkers != null){	killMarkers();}
	if(Id == 'lrad2')
	{// set up for the XML file input
		mouseup('lrad1');
		genLoadStatus('Fetching List of Files ...', true)
		makeTableSelectControl('useroverlays/preGeocoded/', 'publishedList', 'Addresses', 'name', 'upload');
		document.getElementById('fileEnter').style.display='none';
		document.getElementById('xmlEnter').style.display='block';
		progressBarVer = 'progBar2';
		document.getElementById(progressBarVer).style.display='none';
		document.getElementById('amlOD').style.display='none';
		document.getElementById('saveDiv').style.display='none';
		document.getElementById('dragDiv').style.display='none';
		document.getElementById('killDiv').style.display='none';
		document.getElementById('filterDiv').style.display='none';
		document.getElementById('editButtons0').style.display='none';
		//document.getElementById('editButtons6').style.display='none';
		genLoadStatus('', false)
	}
	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');
		document.getElementById('amlOD').style.display='none';
		document.getElementById('saveDiv').style.display='none';
		document.getElementById('dragDiv').style.display='none';
		document.getElementById('killDiv').style.display='none';
		document.getElementById('filterDiv').style.display='none';
		//if(fileUploaded)
		//{
		//	document.getElementById('editButtons5').style.display='block';
		//	document.getElementById('editButtons6').style.display='block';
		//}
		initializeForms();
	}
}


// -------------- this will plot all user uploaded data as markers ----------------
function showUserPoints(xmlFile)
{
	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';
	}
	
	//alert(xmlFile)
	progressBar('progBar', 'Fetching ...', '') ;
	if(document.getElementById(progressBarVer)){document.getElementById(progressBarVer).style.display='none';}
	
	// remove any existing markers layers
	if(userMarkers != null)
	{
		//alert('destroying userMarkers')
		if(popupFlag)	{	popup.destroy(); popup=null;	popupFlag=false;}
		if(userMarkers != null)	{	userMarkers.destroyFeatures(); 	userMarkers=null;}
		if(vectorLayer2 != null){	vectorLayer2.destroyFeatures(); vectorLayer2=null;}
	}
	valuesPresent=false;
	//alert('drag control 1 = '+dragItControl);


	// generate full url of xml file
	var file = applicationBase+"inc/"+xmlFile;
	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;
	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; 
	}

	// OK we have a successfully geocoded file so process addresses
	addresses = ajaxRequest.responseXML.getElementsByTagName("Address");
	if(addresses.length > 0)
	{
		//alert('atempting to get the address')
		//addresses = userPoints.getElementsByTagName("Address");
		attribs = addresses[0].getElementsByTagName("Attribute");
		hiVal = -9999999; loVal = 9999999;
	 
		// now scan through all Addresses in XML file and pick off symbol scaling attrib value then sum to determine range
		if(addresses.length > 0 && attribs.length > 0)
		{
			// calculate range of values for all the Value attributes
			var tot = parseInt(addresses.length);
			for (var i=0; i<addresses.length ; i++)
			{
				attribs = addresses[i].getElementsByTagName("Attribute");			
				for(var g=0; g<attribs.length; g++)
				{
					if(attribs[g].getAttribute('type') == 'symbolVar')
					{
						var value = parseFloat(attribs[g].getAttribute("value"));
						if (value > hiVal) {hiVal = value}
						if (value < loVal) {loVal = value} 
					}
				}
			}
			
			// now round low down and hi up to get inclusive range 
			hiVal = Math.ceil(hiVal);
			loVal = Math.floor(loVal);
		
			// if we have some points with numeric data set up five symbol sizes
			if(hiVal != -9999999 && loVal != 9999999) //i.e. have changed from start 
			{
				// now calculate the four threshholds
				var delta = hiVal-loVal;
				var aDiv = delta/5;
				var Div1 = Math.ceil(loVal + aDiv);
				var Div2 = Math.ceil(Div1 + aDiv);
				var Div3 = Math.ceil(Div2 + aDiv);
				var Div4 = Math.ceil(Div3 + aDiv)
				
				// set up five classification ranges
				lowRange =    [loVal, Div1];
				midlowRange = [Div1, Div2];
				midRange =    [Div2, Div3];
				midhiRange =  [Div3, Div4];
				hiRange =     [Div4, hiVal];
			}
		}
		else
		{	return false;	}
	}
	else
	{
		// check to see if the file is present
		//alert(file+query)
		if(browser == 'msie')
		{
			alert('this file is probably too big for Internet Explorer. /n Try using Firefox as your browser, it handles bigger files \nand this application performs faster on Firefox.');
		}
		return false;
	}

 //alert('show User Points 1');
// ---------------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)

	// if the user wants to see only for window then generate the smaller oxBox bounds
	var ozBoxGeog = [104.94141,  -44.96480,  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
			ozBoxGeo = [map.getExtent().left, map.getExtent().bottom, map.getExtent().right, map.getExtent().top]; 
		}
	}

	// set up the point symbol styling
	setupSymbols() ;

	// - main vector plotting loop -
	progressBar('progBar', 'Plotting ...', '') ;
	var jk=0;
	allPoints = [];

	// if we have a polygon-feature filter, rearange into polygon array
	var loX = 99999999999999; loY=99999999999999; hiX=-99999999999999; hiY=-9999999999999999999;
	var pointList = new Array();
	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 != null) 
		{	vectorLayer2.destroyFeatures(); vectorLayer2.destroy(); 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 != null) {	vectorLayer2.destroyFeatures();  vectorLayer2=null;}
	}

	// process each point in the uploaded file
	for (var i=0; i<addresses.length; i++)
	{
		//var percent = Math.ceil(i/(parseInt(addresses.length))*100);
		//alert(percent)
		//progressBar('progBar', 'Plotting', 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.7';
		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");}
		
		// 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;
					}
				}			
			}
			else
			{	
				symbolFillColor = '';
				// 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;
					}
				}
			}
			
			// if not found then add MarkerClass and MarkerColor to arraye
			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); 
					jk++ ;	
				}
			}
		}
		// else if point is outside of Australia 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);	jk++}
				
	}
	//alert('show User Points 3');
	//alert('drag control 5 = '+dragItControl);
	// sort the arrays by range value
	var ptr = 0;
	//for (var m=0; m<range.length ; m++ )	// smallest first
	for (var m=5; 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];
				sortedAddress[ptr] = pointAddress[n];
				sortedOldLoc[ptr] = oldLocation[n];
				ptr++;
			}
		}
	}

	// now build the markers overlay
	//alert('sorted point numbers = '+sortedPoints.length);
	if(firstTime) {filterMarkers();} else {filterMarkers(getFilterList());}
	//alert('show User Points 4');
	
	
	//resetZlevels();
	bringToTop(vectorLayer2);
	return true;
}

function includeThisPoint(i, pointLon, pointLat)
{
	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 != -9999999 && loVal != 9999999))
	{
		// scan through all attributes
		for(var g=0; g<attribs.length; g++)
		{
			// check for symbolVar type attribute
			if(attribs[g].getAttribute('type') == 'symbolVar')
			{
				// assign a classification level for this feature - this is used to scale the symbol radius
				valuesPresent = true;
				var name = attribs[g].getAttribute('name');
				var value = parseFloat(attribs[g].getAttribute('value'));
				if (value >= lowRange[0] && value < lowRange[1])			{range[i]=1}
				else if (value >= midlowRange[0] && value < midlowRange[1])	{range[i]=2}
				else if (value >= midRange[0] && value < midRange[1])		{range[i]=3}
				else if (value >= midhiRange[0] && value < midhiRange[1])	{range[i]=4}
				else if	(value >= hiRange[0] && value <= hiRange[1])		{range[i]=5}
				//break;
			}
		}
	}

	// set up the content details for the popup
	description = setupPopups(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: range[i]*10 
			,fillColor: symbolFillColor
			,fillOpacity: symbolFillOpacity
			,strokeColor: symbolStrokeColor
			,strokeWidth: symbolStrokeWidth
		});

	// 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;
	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 to load all or filtered list of points ------------------//
function filterMarkers(filteredMarkers)
{
	// first time just load all the points
	//alert('firsttime = '+firstTime)
	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 != null)
		{
			//alert('destroying userMarkers')
			if(popupFlag)	{	popup.destroy(); popup=null;	popupFlag=false;}
			if(userMarkers != null)	{	userMarkers.destroyFeatures(); 	userMarkers=null;}
			if(vectorLayer2 != null){	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')
		{
			for (var i=0; i<sortedPoints.length;  i++)
			{
				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 as they could have changed
		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);
		}
	}
	// 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
		});
	}
	// 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');
	progressBar('progBar', '', '') ;
	//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
		var title = document.getElementById('dragMarker').title;
		//alert('drag title = '+title);
		//alert('pickmode = '+pickMode)
		if(title == 'Turn off Dragging' && !pickMode)
		//if(dragCheckBox && !pickMode)
		{
			//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'] -4200);	 }
				
		// make sure the file accessing controls are active
		
		if(document.getElementById('filterDiv')) 
		{	document.getElementById('filterDiv').style.display='block';}
		if(document.getElementById('dragDiv')) 
		{	document.getElementById('dragDiv').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');
		}
	}
}	
	
/*	
	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;
	//alert('in onFeatureSelect')
	// 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]) * 10;
	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();
}

function onPopupClose(evt) 
{	
	selectControl.unselect(selectedFeature); 
	popupFlag=false;
	activateControls('onPopupClose');
	//resetZlevels();
}
					
function onFeatureUnselect(feature) 
{
	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
		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;
						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;
				break;
			}
			//alert('could not find the point!')
		}
		
		if(feature.popup)
		{
			// close existing popup
			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();

}

/*
this is how to build pie charts as the curcle symbol
 var context = {
                getSize: function(feature) {
                    return 20 + Math.round(symbol.getSize(feature.attributes["population"]) * Math.pow(2,map.getZoom()-1));
                },
                getChartURL: function(feature) {
                    var values = feature.attributes["pop_0_14"] + ',' + feature.attributes["pop_15_59"] + ',' + feature.attributes["pop_60_above"];
                    var size = 20 + Math.round(symbol.getSize(feature.attributes["population"]) * Math.pow(2,map.getZoom()-1));
                    var charturl = 'http://chart.apis.google.com/chart?cht=p&chd=t:' + values + '&chs=' + size + 'x' + size + '&chf=bg,s,ffffff00';
                    return charturl;
                }
            };

            var template = {
                fillOpacity: 1.0,
                externalGraphic: "${getChartURL}",
                graphicWidth: "${getSize}",
                graphicHeight: "${getSize}",
                strokeWidth: 0
            };

*/

function setupSymbols()
{
	template = 
	{
		 fillColor: '${fillColor}' 
		,fillOpacity: '${fillOpacity}'
		,strokeColor: '${strokeColor}'
		,strokeWidth: '${strokeWidth}'
		,pointRadius: "${type}"
	//	,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
		});
	}
	
	
	// check for Pie Chart and Bar Chart
	col01 = ''; col02 = '';  chart = '';
	var chartColsRange = document.getElementById('graphCols').value;
	if(chartColsRange != '')
	{
		// get the individual column extremedies
		var parts = chartColsRange.split('-');
		if(parts.length > 1)
		{	
			col1 = parts[0]; 
			col2 = parts[1];

			// set the selected chart type
			if(document.getElementById('pieRadio').checked) {	chart = 'p3'}
			else if (document.getElementById('barRadio').checked){	chart = 'bvs'}
			else if (document.getElementById('lineRadio').checked){	chart = 'lc'}
		}
	}
	userdata = true;
}

function setupPopups(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
	var m=0;
	if (attribs.length > 0) 
	{	
	   description +="<br/><br/><b><u>Attribute Data</u></b>";
		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
				var minVal = attribs[z].getAttribute("min");
				//if(minVal == ''){minVal=0;}
				var maxVal = attribs[z].getAttribute("max");
				
				var 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) 
				{	var chartVal = tempVal;
					var 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/>";
	//alert(description)
	// now add the relocation button
	//description += "<input type='button' id='relocatePoint' value='Move Point' onclick='relocateUploadedPoint();'/><br/><br/>"

	// make sure graph controls are visible if we found chart data
	if(chartFlag)
	{	document.getElementById('graphRadio').style.display='block';	}

	// create Y axis Chart Labels
	var yHigh = parseInt(Math.ceil(maxVal)*1.1);
	var yLow = 0.0;
	//alert('chart Value = '+chartVal)

	// if charts are requested add Chart to the info bubble
	//if(document.getElementById('graphCols').value != ''	)
	//alert('chartFlag = '+chartFlag)
	if(chartFlag)
	{
		// 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('pieRadio').checked) {	chart = 'p3'}
		else if (document.getElementById('barRadio').checked){	chart = 'bvs'}
		else if (document.getElementById('lineRadio').checked){	chart = 'lc'}
		
		// 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(obj)
{
	// Determine the ststus desired
	if(obj.title == 'show all classes')
	{	var checkedSwitch = true; 
		obj.title='hide all classes'; 
	}
	else 
	{	var checkedSwitch = false; 
		obj.title='show all classes';
	}

	// now change all the checkboxes for ByClass tab
	if(obj.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(obj.id == 'allClassesCheckbox2' && valuesPresent)
	{
		for(var i=0; i<5; 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
	if(vectorFilter == 'byClass')
	{
		for (var i=0; i < markerClass.length ; 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 < 5 ; i++)
		{
			if (document.getElementById('markerValue2:'+i).checked)
			{	filteredMarkers.push(i);	}
		}
	}
	//alert(filteredMarkers)
	return filteredMarkers;
}




function initializeForms()
{
	// 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('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('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('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('markerVisOnOff'))	{document.getElementById('markerVisOnOff').title = 'show marker visibility control';}
	if(document.getElementById('markerVisOnOff'))	{document.getElementById('markerVisOnOff').src='images/markv_off.jpg';}
	firstTime=true;
	pickMode=false;
	currentXmlRow = -1;

	// 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()
{
	// set all forms back to beginning
	initializeForms();
	
	// do the actual layer kill
	killMarkers();	
}

function killMarkers()
{
//	alert('destroying userMarkers')

	if(popupFlag)	
	{	popup.destroy(); 
		popup=null;
		popupFlag=false;
	}

	if(userMarkers != null)	
	{	
		userMarkers.destroy(); 
		userMarkers=null;
	}

	if(vectorLayer2 != null)
	{	vectorLayer2.destroy(); vectorLayer2=null }
	
	// deactivate any Drag and Select Controls dragItControl['drag']
	//var conts = ['Drag','Select'];
	//deactivateControls(conts, 'killMarkers');
	userdata = false;
}

function publishXml()
{
	// set up the source file
	var source = "/inc/"+geocodedFile;
	var destFilename = '';

	// strip out the date stamp from file name
	var parts = geocodedFile.split('_');
	if(parts.length > 1)
	{
		for (var i=0; i<parts.length-1 ; i++)
		{	destFilename = destFilename+'_'+parts[i];	}
		geocodedFile = destFilename;
	}
	
	// strip out the path info
	var parts = geocodedFile.split('/');
	destination = "/inc/useroverlays/preGeocoded/"+parts[length];
	destination = destination+'.xml';
	
	// strip off leading slash for testing
	var newDest = destination.replace(/\/inc\//,'');
	var testFilename = newDest;
	//alert(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)
		makeTableSelectControl('useroverlays/preGeocoded/', 'publishedList', 'Addresses', 'name', 'upload');
		document.getElementById('saveDiv').style.display='none';
		if(!fileUploaded)
		{	document.getElementById('amlOD').style.display='none';}
		genLoadStatus('', false)
	}
}

function toggleMarkers(markerLayer, buttId)
{
	var title = document.getElementById(buttId).title;
	var titleBits = title.split(" ")
	if (titleBits[0] == 'hide')
	{	
		markerLayer.setVisibility(false);									// This clears out the markers on the map
		markerLayer.addOptions({'displayInLayerSwitcher': false});			// This clears out the old marker name
		document.getElementById(buttId).src="images/mark_off.jpg";
		document.getElementById(buttId).title = 'show markers';
	}
	else if (titleBits[0] == 'show')
	{
		markerLayer.setVisibility(true);									// This clears out the markers on the map
		markerLayer.addOptions({'displayInLayerSwitcher': true});			// This clears out the old marker name
		markerLayer.redraw(true)	
		document.getElementById(buttId).src="images/mark_on.jpg";
		document.getElementById(buttId).title = 'hide markers';
	}
	//resetZlevels();
}
function toggleMarkersVisibility(buttId, holderId)
{
	if(fileUploaded || xmlFileActive)
	{
		//alert('button Id = '+buttId)
		var title = document.getElementById(buttId).title;
		//alert(title);
		var titleBits = title.split(" ")
		if (titleBits[0] == 'hide')
		{	
			document.getElementById(holderId).style.display='none';
			document.getElementById(buttId).title = 'show marker filter control';
			//mouseup(buttId)
			normalDiv(buttId)
		}
		else if (titleBits[0] == 'show')
		{
			document.getElementById(holderId).style.display='block';
			document.getElementById(buttId).title = 'hide marker filter control';
			depressedDiv(buttId);
		}
	}
	else
	{
		document.getElementById(buttId).title = 'show marker filter control';
		normalDiv(buttId)
	}
	//resetZlevels();
}
function toggleButton(id)
{
	if(!userdata) {return;}
	// specify the file as selected in radio buttons
	var xml = 'useroverlays/'+geocodedFile;
	var csv='';
	if(geocodedCsv != '' || geocodedCsv != null){	csv = 'useroverlays/'+geocodedCsv; }
	
	//var xmlRadio = document.getElementById('lrad2').checked;	
	var delme=false;
	if(xmlFileActive)
	{	var processFile = xml;	
		width=600;
		height=800;
	}
	else 
	{	var processFile = csv;	
		width=0;
		height=0;
		if (confirm('Select OK to delete your uploaded CSV file from the server after viewing.\nCancel will not delete your files after viewing.')) {delme = true;}
	}
		
	// now show the file and delete it after if requested
	if(filePresent(processFile))
	{
		normalDiv(id);
		makePopup('inc/'+processFile, width, height, 'both');
		if(delme){deleteit(processFile);}	
	}
	else
	{	alert('The file you request has been deleted or was not uploaded');	}
	
	// if both files are deleted then kill off the control
	if(!xmlFileActive && !filePresent(csv) )
	{	document.getElementById('amlOD').style.display='none';	}
}

function checkComplete()
{
	if(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 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 != null && 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 != null && 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 != null && 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 (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;
			//alert('all is well')
			//resetZlevels();
			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());
	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
	
	// set to the new point
	var markerLoc = new OpenLayers.LonLat(pointX, pointY);
	//map.setCenter(markerLoc, 14);
	map.setCenter(markerLoc, markerZm);
	userMarkers.refresh();
	current = arrayNumber;
	
	// now put bar on the Progress Bar window as a record pointer
	if(document.getElementById(progressBarVer)) {	recordNumber (progressBarVer, current, sortedOldLoc.length-1);}
	//resetZlevels();
}

function saveAndQuit()
{
	if(progressBarVer == 'progBar2')
	{alert ('Save is not available for pre-Geocoded XML files'); return; }
	
	// parse each object in the uploaded points array
	var fileRow = []; var fileCell = []; var dataCellX = []; var dataCellY = []; var dataAddr = []; 
	var k=0;
	var updateString = '';  
	for (var i=0; i<sortedPoints.length ; i++ )
	{	
		// transform new 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);
		}
		
		// check to see if the coordinates have changed againsted saved coords
		var coords = sortedOldLoc[i].split(",");
		var testX = roundNumber(coords[0],8); 
		var testY = roundNumber(coords[1],8);
		if(testX != pointX || testY != pointY)
		{	
			// build up the transaction arrays
			fileRow[k] = sortedRecNo[i];
			dataAddr[k] = sortedAddress[i];
			dataCellX[k] = pointX;
			dataCellY[k] = pointY;
			k=k+1
		}
	}

	// turn off the editing buttons block
	document.getElementById("editButtons").style.display="none"; 
	//alert('header Rows = '+csvHeadRows)
	// 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 += '&row='+fileRow;
	query += '&addr='+dataAddr;
	query += '&x='+dataCellX;
	query += '&y='+dataCellY;
	

	//document.write(url+query)
	// now go off to server and generate a new updated csv file
	loadXml(url, query, false);
	
	document.getElementById("progBar").style.display='none';
	initializeForms();
	document.getElementById("amlOD").style.display='block';
	if(fileUploaded)
	{	document.getElementById('saveDiv').style.display='block';}
}

function quitNoSave()
{
	document.getElementById("editButtons").style.display="none"; 
	document.getElementById("progBar").style.display='none';
	//document.getElementById("editMarkers").style.display="block";
	if(userMarkers != null){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<5; 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='Toggle this checkbox to control visibility of this marker class';
					box.checked=true;	
					if(browser == 'msie') {box.setAttribute('defaultChecked', 'defaultChecked');}
					// attach the interactive event handler
					//bindEvent(box, 'change', 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
	//alert(markerColor)
	// 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 < 5 ; i++)
		{
			// Create the Row
			var start = ''; var end = '';
			var innerRow = document.createElement('tr');
				if(i==0) {start=lowRange[0]; end=lowRange[1];}
				if(i==1) {start=midlowRange[0]; end=midlowRange[1];}
				if(i==2) {start=midRange[0]; end=midRange[1];}
				if(i==3) {start=midhiRange[0]; end=midhiRange[1];}
				if(i==4) {start=hiRange[0]; end=hiRange[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'; 
				
				// set the background color to match marker color
				//innerCell.style.backgroundColor = markerColor[i];
				//var fillNumber = Math.abs(markerOpacity[i] * 100);
				//setOpacity(innerCell, fillNumber);

					// create the Input checkbox for Attribute Summation
					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='Toggle this checkbox to control visibility of this markers by value class';
					box.checked=true;	
					if(browser == 'msie') {box.setAttribute('defaultChecked', 'defaultChecked');}
					// attach the interactive event handler
					//bindEvent(box, 'change', 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; innerCell.setAttribute('id','value:'+i);
					innerDiv.style.float = 'left';
					var textElement = document.createTextNode(start+" - "+end);
					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);
}
