var step2html="Step 2";
var step1html="Step 1";
var step3postcodehtml="Step 3 postcode";
var step3maphtml="";
var captureUserDatahtml = "capture userdata";
var geocoder = null;
var userPolyline = null;
var userPoint = null;
var userPolygon = null;

var userLoginReq; // httpxml to log the user in ...

var myUsername = "";

var xhReq; // the http xml request to see if the user is logged in or not!
var xhAdminReq; // the http xml request to see if the user is logged in as an administrator or not!
var xhReqData; // the http xml request to download the correct form for data entry

var thePoint;
var theLine;
var thePolygon;
var pts = [];
var tempPts = [];
var dataCaptureListener;


//function deleteExistingAndReturnToNewParent(lookuptablename, lookupid, parenttablename, parentid) {
function deleteExReturnToNewParent(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("deleteExistingAndReturnToNewParent");
	
	// in this case, the child record should be deleted from the database first
	// this is a PROPER delete as opposed to a 'delete' requested by the user / moderator, whic
	// only flags the data as deleted

	// so the CANCEL button should only appear for an 'add new' operation


	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	poststring = "";
		//var sPath = window.location;
		//var paths = String(sPath).split("=");
		//minisitename = paths[1];
		//minisitename = minisitename.replace("#","");
		minisitename = getMinisiteName();
		poststring = poststring+ "&minisitename="+minisitename

	poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
	poststring = poststring + "&tablename="+lookuptablename+"&id="+lookupid;
	poststring = poststring + "&action=clearChild";
	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = showNewRecordForm;

	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	//alert(poststring);
	xhReq.send(poststring);
}


function ExtensionName_ClickElement(e){
	try {
		 if( document.createEvent ) {
			// for firefox
			//   var evObj = document.createEvent('MouseEvents');
			//   evObj.initMouseEvent( 'mousemove', true, false, window, 0, 12, 345, 7, 220, false, false, true, false, 0, null );
			//   fireOnThis.dispatchEvent(evObj);

			var evt = e.ownerDocument.createEvent('MouseEvents');
			evt.initMouseEvent('click', true, true, e.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
			e.dispatchEvent(evt);

		 } else if( document.createEventObject ) {
		 	// for internet explorer
			  var evObj = document.createEventObject();
			  /*evObj.detail = 1;
			  evObj.screenX = 0;
			   evObj.screenY = 0;
			   evObj.clientX = 0;
			   evObj.clientY = 0;
			   evObj.ctrlKey = false;
			   evObj.altKey = false;
			   evObj.shiftKey = false;
			   evObj.metaKey = false;
			   evObj.button = 0;
			   evObj.relatedTarget = null;
			   alert("post null");*/
			   //e.fireEvent("onclick",evObj);
			   //e.fireEvent("onclick");
			   //e.fireEvent("click");
			   e.click();
		}
   
	}
	catch(err) {
		alert("evt="+err.description);
  
	 }
 
}

function submitfile() {
	// check that the photo is not a doc or other format
	var thePhoto = document.getElementById('photoname').value;
	var theType = thePhoto.substr(thePhoto.length - 3,thePhoto.length).toLowerCase();
	if (theType != "png" && theType != "jpg" && theType != "JPG" && theType != "PNG") {
		alert("Please select a png or jpg file to upload");
		document.getElementById('photoname').value = "";
		return;
	}
	try   {
		var submitphoto = document.getElementById('action');
		//try {
		//	submitphoto.click();
		//} catch (e) {
		//	// firefox will work but will raise an error as the click() event is not really supported
		//}
	}
	catch (e) {
		alert("submit photo"+e.description);
	}
		ExtensionName_ClickElement(submitphoto);
	//document.getElementById('file_upload_form').submit();
}
function doOnSubmit() {
	
		document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
				
}


function drawCaptureData() {
	if (startCapture == true) {
		if (tempPts.length > 0) {
			for (var i =0; i< tempPts.length; i++ ){
				map.addOverlay(tempPts[i]);
			}
		}
	}
}

function clearCaptureOverlays() {
	//alert(pts.length);
	//alert(tempPts.length);
	if (tempPts.length > 0) {
		for (var i = tempPts.length -1 ;i >= 0; i=i-1){
		//for (var i = 0 ;i < tempPts.length; i++ ){
			theOverlay = tempPts[i];
			map.removeOverlay(theOverlay);
			tempPts.pop(theOverlay);	
		}
	}
	if (pts.length > 0) {
		for (var j = pts.length - 1; j >=0; j=j-1) {
			pts.pop(pts[i]);
		}
	}
	pts = [];
	tempPts = [];
	
	map.enableDragging();
	//map.enableDoubleClickZoom();

}
function startDataCapture() {
 if (startCapture == false) {
 	// first check if the user has selected the type of data they wish to capture
	if (document.forms["processdata"].feature_type[0].checked ) {
		// capturing a point
		startCapture = true;
	}
	if (document.forms["processdata"].feature_type[1].checked ) {
		// capturing a line
		startCapture = true;

	}
	if (document.forms["processdata"].feature_type[2].checked ) {
		// capturing a polygon
		startCapture = true;

	}
	if (startCapture == false) {
		alert("Please select whether you want to capture a point, line or polygon");
		return 0;
	}

} // start capture = false


	// set up some icons
	var bicon = new GIcon();
	bicon.iconSize = new GSize(20, 20);
	bicon.iconAnchor = new GPoint(10, 10);

	var iconlocation = "../images/addline.png";
	var icon = new GIcon(bicon, iconlocation, null, null );

	
	var pointIconLocation = getIconLocation(contentLayer);
	var linecolour = getColour(contentLayer);
	var pointIcon = new GIcon(bicon, pointIconLocation, null, null );


	bicon.iconSize = new GSize(10, 10);
	bicon.iconAnchor = new GPoint(5, 5);

	var lineIconLocation = "../images/savepoint.png";
	var lineIcon = new GIcon(bicon, lineIconLocation, null, null );

	


// clear any pre-existing data and cancel the existing listener

if (pts.length > 0) {
	// clear capture 
	clearCaptureOverlays();
}
try {
	GEvent.removeListener(dataCaptureListener);
} catch (e) {}
// start the listener
    dataCaptureListener = GEvent.addListener(map,"click", function(overlay,point) {
        
	if (document.getElementById('feature_type1').checked ) {
			// create a point where teh user has clicked
		// remove the point
		
		if (pts.length > 0) {
			map.removeOverlay(thePoint);
			pts.pop(thePoint);
			tempPts.pop(thePoint);
		}
		thePoint = new GMarker(point, {icon:pointIcon, draggable: false});
		map.addOverlay(thePoint);
		tempPts.push(thePoint);
		pts.push(point);
	} // points
	if (document.getElementById('feature_type2').checked ) {
		
		//map.removeOverlay(thePoint);
		//tempPts.pop(thePoint);
		if (pts.length > 1) {
			map.removeOverlay(theLine);
			tempPts.pop(theLine);
		}
		thePoint = new GMarker(point, {icon:lineIcon});
		map.addOverlay(thePoint);
		tempPts.push(thePoint);
		pts.push(point);
		// if there is more than one point, then also draw the line that jons them
		if (pts.length > 1) {
			theLine = new GPolyline(pts,linecolour, 4,1);
			map.addOverlay(theLine);
			tempPts.push(theLine);
		}
    	} // lines
	if (document.getElementById('feature_type3').checked ) {
			
			//map.removeOverlay(thePoint);
			//tempPts.pop(thePoint);
			thePoint = new GMarker(point, {icon:lineIcon});
			map.addOverlay(thePoint);
			tempPts.push(thePoint);
			pts.push(point);
			// if there is more than one point, then also draw the line that jons them
			if (pts.length == 2) {
			    theLine = new GPolyline(pts,linecolour, 3,1);
				map.addOverlay(theLine);
				tempPts.push(theLine);
			}
			if (pts.length == 3) {
				map.removeOverlay(theLine);
				tempPts.pop(theLine);
			}
			if (pts.length > 3) {
				map.removeOverlay(thePolygon);
				tempPts.pop(thePolygon);
			}
			if (pts.length > 2 ) {
				//thePolygon = new GPolygon(pts,linecolour,3,1,linecolour,0.2);
				thePolygon = new GPolygon(pts,"#FF00FF",3,1,"#FF00FF",0.2);
				map.addOverlay(thePolygon);
				tempPts.push(thePolygon);
			}
			
	} // polygons
	
	} // end of the click function
    	); // end of the map listener

	// now change the point on the map ...
	map.disableDragging();
	map.disableDoubleClickZoom();
	map.disableContinuousZoom();
	//setCursor(map,"crosshair");
	//document.getElementById("map-canvas").style.cursor="crosshair";
	document.getElementById("mapinterface").style.cursor="crosshair";
	
	// add the data capture tip span
	addDataCaptureTip();
	
	try {
		if (document.getElementById('feature_type1').checked ) {
			document.getElementById("datacapturetip").onmouseover = tooltip("Click on the map <b>once</b> to draw the point.  <br> <br> Click <b>NEXT</b> when you have finished");
		}
		if (document.getElementById('feature_type2').checked ) {
			document.getElementById("datacapturetip").onmouseover = tooltip("Click on the map at least <b>twice</b> <br> to draw the line.  <br> <br> Click <b>NEXT</b> when you have finished");
		}
		if (document.getElementById('feature_type3').checked ) {
			document.getElementById("datacapturetip").onmouseover = tooltip("Click on the map at least <b>three</b> <br>times to draw the polygon.  <br><br>  Click <b>NEXT</b> when you have finished");
		}
		document.getElementById("datacapturetip").onmouseout = exit();
	}
	catch (e) {
	}
	// put a tooltip on the mouse depending on whether we are capturing a point line or polygon
	
}

function addDataCaptureTip() {
  var ni = document.getElementById('mapinterface');
  var newdiv = document.createElement('div');
  var divIdName = 'tooltip';
  newdiv.setAttribute('id',divIdName);
  ni.appendChild(newdiv);

}

function removeCoordinate() {
	// clear all overlays and start again !
	// don't remove just the one coordinate
	clearCaptureOverlays();	
}


function processClearMapData() {
	// we are starting step 3 map again
	startCapture = false;
	GEvent.removeListener(dataCaptureListener);
	clearCaptureOverlays();
	setupStep3Map();
	

}
function processUndoMapData() {
	clearCaptureOverlays();

}

var selectedGeometryType = "";

function processStep3Map() {	
	//alert("processStep3Map");
	if (pts.length == 0) {
		alert("Please draw on the map");
		return false;
		//return 0;

		
	}
	if (document.forms["processdata"].feature_type[0].checked ) {
		//document.forms["processdata"].selected_geometrytype.value = "point";
		selectedGeometryType = "point";
		// capturing a point
		if (pts.length != 1) {
			alert("Please draw a single point on the map");
			return false;
			
			
		}
	}
	if (document.forms["processdata"].feature_type[1].checked ) {
		//document.forms["processdata"].selected_geometrytype.value = "line";
		selectedGeometryType = "line";
		// capturing a line
		
		if (pts.length < 2) {
			alert("Please draw a line on the map - you need at least 2 points");
			return false;
		}
	}
	if (document.forms["processdata"].feature_type[2].checked ) {
		//document.forms["processdata"].selected_geometrytype.value = "polygon";
		selectedGeometryType = "polygon";
		// capturing a polygon
		if (pts.length < 3) {
			alert("Please draw a polygon on the map - you need at least 3 points");
			return false;
		}
		// add the first point again to close the polygon
		pts.push(pts[0]);
	}
	
	document.getElementById("mapinterface").style.cursor="hand";
	//alert(selectedGeometryType);
	return true;
	//setupStep4();
}



function processStep2() {
	if (document.forms["processdata"].capture_type[0].checked ) {
		document.forms["processdata"].selected_capture_type.value = "postcode";
	}
	if (document.forms["processdata"].capture_type[1].checked ) {
		document.forms["processdata"].selected_capture_type.value = "drawonmap";
	}
	if (document.forms["processdata"].selected_capture_type.value == "notselected") {
		alert("Please select the way you wish to capture your data");
	}
	else {
		if (document.forms["processdata"].selected_capture_type.value == "postcode") {
			setupStep3Postcode();
		}
		else {
			setupStep3Map();
		}
	}
}

function setupStep1() {


	// first check if there has been any geometry captured
	if (processStep3Map == false ) {
		return;
	}
	

	// get rid of the tooltip
	try { 
		exit();
	} catch (e) {}
	
	// make sure there are no data points left from step 3
	try {
		clearCaptureOverlays();
	
	} catch (e) {}
	startCapture = false;
	// make sure that the map listener is not on ...
	// make sure the map listener has been cleared:
	try   { 
		GEvent.removeListener(dataCaptureListener);
	}
	catch (e) {
		// do nothing - listener has been previously cleared
	}

	//setupAddContentTab1();
}
function step4showForm()  {
	if (xhReqData.readyState != 4)  {
		return;   	
	}

	var responseText = xhReqData.responseText;
	//now split out the text and the script parts !
	var splitresult = responseText.split("|XX|");


	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.text = splitresult[1];
	headID.appendChild(newScript);


	  // create the black baground div
	    var ni = document.getElementById('mapwrapper');
	    var overlaydiv = document.createElement('div');
	   var divIdName = 'mapoverlay';
	   overlaydiv.setAttribute('id',divIdName);
	   overlaydiv.setAttribute('class','png');
	   ni.appendChild(overlaydiv);



	  var ni = document.getElementById('mapwrapper');
	  var newdiv = document.createElement('div');
	  var divIdName = 'describe';
	  newdiv.setAttribute('id',divIdName);
	  newdiv.setAttribute('class','png');
	  //alert(splitresult[0]);
	  
	 // NB: need footer - to be consistent with the 'edit' functionality!!!
	 // also need the black background!  
	 
	 
	  var theHTML = splitresult[0] + generateFooter();
	  newdiv.innerHTML = theHTML;
	  ni.appendChild(newdiv);


	updateControlContentStep3();

}


function layersToEdit() {
   if (xhStep1Req.readyState != 4)  { 
   		return;
   	}
   
   var response = xhStep1Req.responseText;
   var htmlscript = response.split("|XX|");
   document.getElementById('currentStep').style.display = "block"; 
   document.getElementById('currentStep').innerHTML = htmlscript[0];

	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.text = htmlscript[1];
	headID.appendChild(newScript);
}

function setupStep2() {
}

function setupStep3instructions() {
	document.getElementById('step1').style.color ="#808080";
	document.getElementById('step1').style.fontWeight ="normal";
	//document.getElementById('step2').style.color ="blue";
	//document.getElementById('step2').style.fontWeight ="normal";
	document.getElementById('step3').style.color ="red";
	document.getElementById('step3').style.fontWeight ="normal";
	document.getElementById('step4').style.color ="#808080";
	document.getElementById('step4').style.fontWeight ="normal";
}
function setupStep3Postcode() {
	setupStep3instructions();
	document.getElementById('currentStep').innerHTML = step3postcodehtml;
	if (document.forms["processdata"].selected_postcode.value != "notselected") {
		document.forms["processdata"].postcode.value = document.forms["processdata"].selected_postcode.value;	
	}
	document.forms["processdata"].postcode.focus();
	document.forms["processdata"].postcode.select();
}

function backtoStep3(tablename, id) {
	doCloseFormWindow();
	try {
	  var pickerDiv = document.getElementById(datePickerDivID);
	  pickerDiv.style.visibility = "hidden";
	  pickerDiv.style.display = "none";
	} catch (e) {}
	// july 2008 - we now need to delete the record we have just created ...
	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	poststring = "";
	poststring = poststring + "&tablename="+tablename+"&id="+id;
	poststring = poststring + "&action=clearParent";
	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = processBackToStep3;
	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	xhReq.send(poststring);
}
function processBackToStep3() {
 if (xhReqData.readyState != 4)  { 
   		return;
   	}
 backtoStep3Map();
}
function backtoStep3Postcode(){
	setupStep3instructions();
	document.getElementById('currentStep').innerHTML = step3postcodehtml;
	document.forms["processdata"].postcode.value = document.forms["processdata"].selected_postcode.value;
}
function backtoStep3Map() {
	// clear all the data ...
	clearCaptureOverlays();


	//setupStep3Map();
	
	addContentText3 = document.getElementById('controlcontent').innerHTML;
	document.getElementById('controlcontent').innerHTML = addContentText2;	 	

	
}



function processSaveUserData() {
	if (validateUserData()) {
		//alert("Your data has been submitted to the moderators for approval.\n\n It will appear on the map once the approval process has been completed.");
		document.getElementById('container2').style.left = "-4000px";
		resetDataCapture();
	}
}
function resetDataCapture() {
		//map.clearOverlays();
		var elSel = document.getElementById('Select1[]');
		for (i=elSel.length-1;i=0;i++) {
			elSel.remove(i);
		}
		setupStep1();
		
}

function setupStep4() {
		// cancel the data capture first
		
		//startCapture = false;
	
		
		// remove the tooltip functionality
		try {
		document.getElementById("datacapturetip").onmouseout = "";
		document.getElementById("datacapturetip").onmouseover = "";
		}
		catch (e) { }
		
		    if(document.getElementById('tooltip')) {
			document.getElementById('tooltip').style.display = 'none';
		    }

		
		// create an http request to get the html text for the form!
	 xhReqData = createXMLHttpRequest();
	 var poststring = "action=createNewParent&tablename="+contentLayer+"&displayname="+contentLabel;
	 xhReqData.open("POST", "processAddNewData.php");
	 xhReqData.onreadystatechange = step4showForm;
	 
	 try {
	   xhReqData.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	 
	 //xhReqData.send("tablename="+contentLayer);
	 xhReqData.send(poststring);
	 
	}
		
		
function reenableMap() {
	//map.enableDragging();
	//map.enableDoubleClickZoom();
	//map.enableContinuousZoom();

	startCapture = false;
	
	// disable the listener
	document.getElementById("map-canvas").style.cursor="hand";
	
	// remove the tooltip
	    if(document.getElementById('tooltip')) {
		document.getElementById('tooltip').style.display = 'none';
	    }
	try {
		GEvent.removeListener(dataCaptureListener);
	}
	catch (e) {
	}

}

function drawLine() {

		var userPolylineString = "new GPolyline([";
		var elSel = document.getElementById('Select1[]');
		for (var i = 0; i < document.getElementById("Select1[]").length; i++) {
			var coordinate=elSel.options[i].text.split(" ");
			userPolylineString = userPolylineString + " new GLatLng(" +coordinate[1] + ","+ coordinate[0]+")";
			if (i < document.getElementById("Select1[]").length - 1) {
				userPolylineString = userPolylineString + ",";
			}
		}
		
		
		
		/*var polyline = new GPolyline([    
		new GLatLng(37.4419, -122.1419),    
		new GLatLng(37.4519, -122.1519),    
		new GLatLng( 37.4619, -122.1819)], "#FF0000", 5);
		map.addOverlay(polyline);*/
		
		
		
		
		
	//	userPolylineString = userPolylineString + "], \"#ff0000\", 5);";
	//	var userPolyline1 = eval(userPolylineString);
	//	map.addOverlay(userPolyline1);

		var polyline = new GPolyline([new GLatLng(51.51, 0.08),new GLatLng(51.50, 0.07)], "#FF0000", 5);
		map.addOverlay(polyline);
	
}

function drawPoint(latStart,longStart) {
        var marker = createMarker(new GLatLng(latStart,longStart),'', '');
        map.addOverlay(marker);
}


function createMarker(point, text, title) {
  var marker = new GMarker(point,{title:title});
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(text);
  });
  return marker;
}
function setCursor(object,cursorStyle) { 
    try { 
        object.style.cursor=cursorStyle; 
    } 
    catch(c) { 
         if ( cursorStyle=="pointer" ) { 
             setCursor(object,"hand") 
         } 
    } 
} 
var offsetx = -270;
var offsety =  20;

function newelement(newid)
{
    if(document.createElement)
    {
        var el = document.createElement('div');
        el.id = newid;
        with(el.style)
        {
            display = 'none';
            position = 'absolute';
        }
        el.innerHTML = '&nbsp;';
        document.body.appendChild(el);
    }
}
var ie5 = (document.getElementById && document.all);
var ns6 = (document.getElementById && !document.all);
var ua = navigator.userAgent.toLowerCase();
var isapple = (ua.indexOf('applewebkit') != -1 ? 1 : 0);
function getmouseposition(e)
{
    if(document.getElementById)
    {
        var iebody=(document.compatMode &&
        	document.compatMode != 'BackCompat') ?
        		document.documentElement : document.body;
        pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
        pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);
        mousex = (ie5)?event.x:(ns6)?clientX = e.clientX:false;
        mousey = (ie5)?event.y:(ns6)?clientY = e.clientY:false;

        var lixlpixel_tooltip = document.getElementById('tooltip');
        lixlpixel_tooltip.style.left = (mousex+pagex+offsetx) + 'px';
        lixlpixel_tooltip.style.top = (mousey+pagey+offsety) + 'px';
        //lixlpixel_tooltip.style.left = (mousex+offsetx) + 'px';
	//lixlpixel_tooltip.style.top = (mousey+offsety) + 'px';

    }
}
function tooltip(tip)

{
    if(!document.getElementById('tooltip')) {
    	newelement('tooltip');
    }
    var lixlpixel_tooltip = document.getElementById('tooltip');
    lixlpixel_tooltip.style.background = "#FFFFFF";
    lixlpixel_tooltip.innerHTML = tip;
    lixlpixel_tooltip.style.display = 'block';
    //document.getElementById('map-canvas').onmousemove = getmouseposition;
    document.getElementById('map-canvas').onmousemove = getmouseposition;
}
function exit()
{
    document.getElementById('tooltip').style.display = 'none';
}

function checkEnterUserLogin(event) {
	if(event.keyCode==13)
	doLogin();
}
function getPhotoName(photostring) {
	var fullpath = photostring.split("\\");
	var photoname = fullpath[fullpath.length - 1];
	return photoname;
}
function editExistingNewParent(tablename) {


	var theLayerChoice = document.getElementsByName("childEditGroup");
	var j=theLayerChoice.length; 
	for (i=0; i<j; i++){
		if(theLayerChoice[i].checked) {
			var lookuptablename = theLayerChoice[i].value;
		}
	}



	// save the main record, without any validation, then show an existing sub record
	var postdata = formData("userDataCapture");
	var poststring = stripNonValidXMLCharacters(postdata);
	poststring = poststring.substr(0,poststring.length - 1);
	
	try {
		if (document.getElementById('photoname')) {
			photoname = getPhotoName(document.getElementById('photoname').value);
			poststring = poststring + "&photoname="+ photoname;
		}
	}
	catch(e) {
	}

	minisitename = getMinisiteName();
	poststring = poststring+ "&minisitename="+minisitename

	// now add the tablename
	poststring = poststring + "&tablename="+tablename;
	poststring = poststring+"&approved=0";

	// as this is an add new record, also send the name of the lookup tablename, this will be used
	// to generate a new blank lookup table record to show to the user
	poststring = poststring + "&lookuptablename="+lookuptablename;
	poststring = poststring + "&action=showFirstChildNewParent";
	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	
	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = showChildNewForm;  //showform;

	 //
	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	xhReq.send(poststring);


}

function showChildNewForm() {
	
	  if (xhReq.readyState != 4)  { 
	   		return;
	   	}
		var response = xhReq.responseText;
		var htmlscript = response.split("|XX|");
		var headID = document.getElementsByTagName("head")[0];
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.text = htmlscript[1];
		headID.appendChild(newScript);
		// rather than have a new photo div, reuse the existing main form div
	
		  document.getElementById('describe').innerHTML = htmlscript[0]+generateFooter(); 
 

		  // create the black baground div
		  // if it does not exist
		  if (!document.getElementById('mapoverlay')) {
    		          var ni = document.getElementById('mapwrapper');
			  var overlaydiv = document.createElement('div');
			  var divIdName = 'mapoverlay';
			  overlaydiv.setAttribute('id',divIdName);
			  overlaydiv.setAttribute('class','png');
			  ni.appendChild(overlaydiv);
		}
}

function addlookuprecordNewParent(tablename) {
	// get the ID from the main form - this is hidden
	
	// get the table name from the selected radio button
	//lookuptablename = document.getElementById("
	
	var theLayerChoice = document.getElementsByName("childgroup");
	var j=theLayerChoice.length; 
	for (i=0; i<j; i++){
		if(theLayerChoice[i].checked) {
			var lookuptablename = theLayerChoice[i].value;
		}
	}


	// save the main record, without any validation, then show a new sub record
	var postdata = formData("userDataCapture");
	var poststring = stripNonValidXMLCharacters(postdata);
	poststring = poststring.substr(0,poststring.length - 1);


	if (document.getElementById('photoname')) {
		photoname = getPhotoName(document.getElementById('photoname').value);
		poststring = poststring + "&photoname="+ photoname;
	}


	 //var sPath = window.location;
	 //var paths = String(sPath).split("=");
	 //minisitename = paths[1];
	 
	 // remove any # characters
	 //minisitename = minisitename.replace("#","");
	 minisitename = getMinisiteName();
	poststring = poststring+ "&minisitename="+minisitename
	
	// now add the tablename
	poststring = poststring + "&tablename="+tablename;
	poststring = poststring+"&approved=0";

	// as this is an add new record, also send the name of the lookup tablename, this will be used
	// to generate a new blank lookup table record to show to the user
	poststring = poststring + "&lookuptablename="+lookuptablename;
	poststring = poststring + "&action=createNewChildNewParent";

	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	
	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = showChildNewForm; //showform;

	 //
	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	xhReq.send(poststring);
}

function showNewRecordForm() {
   if (xhReq.readyState != 4)  { 
   		return;
   	}
	var response = xhReq.responseText;
	var htmlscript = response.split("|XX|");
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.text = htmlscript[1];
	headID.appendChild(newScript);

	// find out if the 'describe' div already exists - if not,create it
	if (!document.getElementById('describe')) {
		  var ni = document.getElementById('mapwrapper');
		  var newdiv = document.createElement('div');
		  var divIdName = 'describe';
		  newdiv.setAttribute('id',divIdName);
		  newdiv.setAttribute('class','png');
		  ni.appendChild(newdiv);
	}
	
	// put the black background
 	if (!document.getElementById('mapoverlay')) {
		    var ni = document.getElementById('mapwrapper');
		    var overlaydiv = document.createElement('div');
		   var divIdName = 'mapoverlay';
		   overlaydiv.setAttribute('id',divIdName);
		   overlaydiv.setAttribute('class','png');
		   ni.appendChild(overlaydiv);
	}

	
	document.getElementById('describe').innerHTML = htmlscript[0]+generateFooter();
	
	// just in case there is a third element .. which may contain a message to the user
	// in this case, it may be the error message that the user tried to upload a photo > 2mb
	// october 2008
	try  {
		if (htmlscript[2]==undefined) {
		}
		else {
			alert(htmlscript[2]);
		}
	}
	catch (e) {
	}
	
	
	
  
}



function cancelExistingAndReturnToNewParent(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("cancelExistingReturnToNewParent");
			xhReq = createXMLHttpRequest();
			poststring = "parenttablename="+parenttablename+"&parentid="+parentid;
			poststring = poststring + "&lookuptablename="+lookuptablename+"&id="+lookupid;
			poststring = poststring + "&action=cancelExistingChildShowNewParent";
			
				//var sPath = window.location;
				//var paths = String(sPath).split("=");
				//minisitename = paths[1];
				//minisitename = minisitename.replace("#","");
				minisitename = getMinisiteName();
				poststring = poststring+ "&minisitename="+minisitename

			//alert(poststring);
			 xhReq.open("POST", "processAddNewData.php", true);
			 xhReq.onreadystatechange = showNewRecordForm;
		 //
			 try {
			   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			   //xhReq.setRequestHeader('Content-Type','text/html')
			 }
			 catch (e) {
				// this only works in internet explorer
			 }
			//alert(poststring);
			xhReq.send(poststring);
	
}
function saveExistingAndReturnToNewParent(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("saveExistingAndReturnToNewParent");
		if (checkData()) {
			// submit the form, save the changes and then re-create the main form
			// get the ID from the main form - this is hidden
	
			// save the main record, without any validation, then show a new sub record
			var postdata = formData("userDataCapture");
			var poststring = stripNonValidXMLCharacters(postdata);
			poststring = poststring.substr(0,poststring.length - 1);
			poststring = poststring+"&approved=0";
	
			xhReq = createXMLHttpRequest();
			// remove any dodgy characters
			
			minisitename = getMinisiteName();
			poststring = poststring+ "&minisitename="+minisitename

	
			poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
			poststring = poststring + "&lookuptablename="+lookuptablename+"&id="+lookupid;
			poststring = poststring + "&action=saveExistingChildShowNewParent";
			//alert(poststring);
			 xhReq.open("POST", "processAddNewData.php", true);
			 xhReq.onreadystatechange = showNewRecordForm;
		 //
			 try {
			   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			   //xhReq.setRequestHeader('Content-Type','text/html')
			 }
			 catch (e) {
				// this only works in internet explorer
			 }
			//alert(poststring);
			xhReq.send(poststring);
		}

	
}
function saveNewAndReturnToNewParent(lookuptablename, lookupid, parenttablename, parentid) {
	// new child, new parent

	// this method is called if the PARENT hasn't yet been saved
	//alert("saveNewAndReturnToNewParent");
	if (checkData()) {
		// submit the form, save the changes and then re-create the main form
		// get the ID from the main form - this is hidden

		// save the main record, without any validation, then show a new sub record
		var postdata = formData("userDataCapture");
		var poststring = stripNonValidXMLCharacters(postdata);
		poststring = poststring.substr(0,poststring.length - 1);
		poststring = poststring+"&approved=0";
		
		minisitename = getMinisiteName();
		poststring = poststring+ "&minisitename="+minisitename


	if (document.getElementById('photoname')) {
		photoname = getPhotoName(document.getElementById('photoname').value);
		poststring = poststring + "&photoname="+ photoname;
	}


		xhReq = createXMLHttpRequest();
		// remove any dodgy characters

		poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
		poststring = poststring + "&lookuptablename="+lookuptablename+"&id="+lookupid;
		poststring = poststring + "&action=saveNewChildShowNewParent";
		//alert(poststring);
		 xhReq.open("POST", "processAddNewData.php", true);
		 xhReq.onreadystatechange = showNewRecordForm;
	 //
		 try {
		   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		   //xhReq.setRequestHeader('Content-Type','text/html')
		 }
		 catch (e) {
			// this only works in internet explorer
		 }
		xhReq.send(poststring);
	}
	
}


function saveNewAndReturnToParent(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("saveNewAndReturnToParent");
	// this method is called if the PARENT hasn't yet been saved

	if (checkData()) {
		// submit the form, save the changes and then re-create the main form
		// get the ID from the main form - this is hidden

		// save the main record, without any validation, then show a new sub record
		var postdata = formData("userDataCapture");
		var poststring = stripNonValidXMLCharacters(postdata);
		poststring = poststring.substr(0,poststring.length - 1);
		poststring = poststring+"&approved=0";
		
			minisitename = getMinisiteName();
			poststring = poststring+ "&minisitename="+minisitename


		xhReq = createXMLHttpRequest();
		// remove any dodgy characters

	if (document.getElementById('photoname')) {
		photoname = getPhotoName(document.getElementById('photoname').value);
		poststring = poststring + "&photoname="+ photoname;
	}


		poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
		poststring = poststring + "&lookuptablename="+lookuptablename+"&id="+lookupid;
		poststring = poststring + "&action=saveNewChildShowNewParent";
		
		 xhReq.open("POST", "processAddNewData.php", true);
		 xhReq.onreadystatechange = showNewRecordForm;
	 //
		 try {
		   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		   //xhReq.setRequestHeader('Content-Type','text/html')
		 }
		 catch (e) {
			// this only works in internet explorer
		 }
		//alert(poststring);
		xhReq.send(poststring);
	}

		
}
function deleteNewAndReturnToNewParent(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("delete new and return to new parent");
	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	poststring = "";
		//var sPath = window.location;
		//var paths = String(sPath).split("=");
		//minisitename = paths[1];
		//minisitename = minisitename.replace("#","");
		minisitename = getMinisiteName();
		poststring = poststring+ "&minisitename="+minisitename

	poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
	poststring = poststring + "&tablename="+lookuptablename+"&id="+lookupid;
	poststring = poststring + "&action=clearChild";
	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = showNewRecordForm;

	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	//alert(poststring);
	xhReq.send(poststring);

}
	 

/*function showNextLookup(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("shownextlookup");
	// in this case, the child record should be deleted from the database first
	// this is a PROPER delete as opposed to a 'delete' requested by the user / moderator, whic
	// only flags the data as deleted

	// so the CANCEL button should only appear for an 'add new' operation


	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	var postdata = formData("userDataCapture");
	var poststring = stripNonValidXMLCharacters(postdata);
	poststring = poststring.substr(0,poststring.length - 1);
	
	poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
	poststring = poststring + "&lookuptablename="+lookuptablename+"&lookupid="+lookupid;
	poststring = poststring + "&action=showNextChildExistingParent";
	
		//var sPath = window.location;
		//var paths = String(sPath).split("=");
		//minisitename = paths[1];
		//minisitename = minisitename.replace("#","");
		minisitename = getMinisiteName();
		poststring = poststring+ "&minisitename="+minisitename

	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = getNextLookup;

	 //
	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	//alert(poststring);
	xhReq.send(poststring);
}*/

function showNextLookupNewParent(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("shownextlookupnewparent");
	// in this case, the child record should be deleted from the database first
	// this is a PROPER delete as opposed to a 'delete' requested by the user / moderator, whic
	// only flags the data as deleted

	// so the CANCEL button should only appear for an 'add new' operation


	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	var postdata = formData("userDataCapture");
	var poststring = stripNonValidXMLCharacters(postdata);
	poststring = poststring.substr(0,poststring.length - 1);
	
	poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
	poststring = poststring + "&lookuptablename="+lookuptablename+"&lookupid="+lookupid;
	poststring = poststring + "&action=showNextChildNewParent";
	
		//var sPath = window.location;
		//var paths = String(sPath).split("=");
		//minisitename = paths[1];
		//minisitename = minisitename.replace("#","");
		minisitename = getMinisiteName();
		poststring = poststring+ "&minisitename="+minisitename

	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = getNextLookup;

	 //
	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	//alert(poststring);
	xhReq.send(poststring);
}


function getNextLookup() {
   if (xhReq.readyState != 4)  { 
   		return;
   	}
	   
	   var response = xhReq.responseText;
	   //alert(response);
          var htmlscript = response.split("|XX|");
	   if (htmlscript[0].indexOf("No further records") > -1) {
	   	alert("No further records");
	   }
	   else {
		var headID = document.getElementsByTagName("head")[0];
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';

		newScript.text = htmlscript[1];
		headID.appendChild(newScript);
		
//		document.getElementById('opaquetext').innerHTML = htmlscript[0];
//		document.getElementById('opaquetext').innerHTML = htmlscript[0];
//		document.getElementById('buttonArea').innerHTML = generateFooter();
//		document.getElementById('opaquetext').style.height = "70%";
//		document.getElementById('buttonArea').style.height = "20%";
//		document.getElementById('topbuttonArea').innerHTML = generateHeader();

		if (!document.getElementById('describe')) {
			  var ni = document.getElementById('mapwrapper');
			  var newdiv = document.createElement('div');
			  var divIdName = 'describe';
			  newdiv.setAttribute('id',divIdName);
			  newdiv.setAttribute('class','png');
			  ni.appendChild(newdiv);
		}

		// put the black background
		if (!document.getElementById('mapoverlay')) {
			    var ni = document.getElementById('mapwrapper');
			    var overlaydiv = document.createElement('div');
			   var divIdName = 'mapoverlay';
			   overlaydiv.setAttribute('id',divIdName);
			   overlaydiv.setAttribute('class','png');
			   ni.appendChild(overlaydiv);
		}


		document.getElementById('describe').innerHTML = htmlscript[0]+generateFooter();


	   }
}
function getPreviousLookup() {
   if (xhReq.readyState != 4)  { 
   		return;
   	}
   	
	   var response = xhReq.responseText;
  	//alert(response);
  	var htmlscript = response.split("|XX|");
	   if (htmlscript[0].indexOf("No previous records") > -1) {
	   	alert("No previous records");
	   }
	   else {
		var headID = document.getElementsByTagName("head")[0];
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';

		newScript.text = htmlscript[1];
		headID.appendChild(newScript);
		//document.getElementById('opaquetext').innerHTML = htmlscript[0];
		//document.getElementById('opaquetext').innerHTML = htmlscript[0];
		//document.getElementById('buttonArea').innerHTML = generateFooter();
		//document.getElementById('opaquetext').style.height = "70%";
		//document.getElementById('buttonArea').style.height = "20%";
		//document.getElementById('topbuttonArea').innerHTML = generateHeader();
		
			if (!document.getElementById('describe')) {
				  var ni = document.getElementById('mapwrapper');
				  var newdiv = document.createElement('div');
				  var divIdName = 'describe';
				  newdiv.setAttribute('id',divIdName);
				  newdiv.setAttribute('class','png');
				  ni.appendChild(newdiv);
			}
			
			// put the black background
		 	if (!document.getElementById('mapoverlay')) {
				    var ni = document.getElementById('mapwrapper');
				    var overlaydiv = document.createElement('div');
				   var divIdName = 'mapoverlay';
				   overlaydiv.setAttribute('id',divIdName);
				   overlaydiv.setAttribute('class','png');
				   ni.appendChild(overlaydiv);
			}
		
			
			document.getElementById('describe').innerHTML = htmlscript[0]+generateFooter();


	   }
}
/*function showPreviousLookup(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("showpreviouslookupnewparent");
	
	// in this case, the child record should be deleted from the database first
	// this is a PROPER delete as opposed to a 'delete' requested by the user / moderator, whic
	// only flags the data as deleted

	// so the CANCEL button should only appear for an 'add new' operation


	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	var postdata = formData("userDataCapture");
	var poststring = stripNonValidXMLCharacters(postdata);
	poststring = poststring.substr(0,poststring.length - 1);

	poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
	poststring = poststring + "&lookuptablename="+lookuptablename+"&lookupid="+lookupid;
	poststring = poststring + "&action=showPreviousChildExistingParent";
	
		//var sPath = window.location;
		//var paths = String(sPath).split("=");
		//minisitename = paths[1];
		//minisitename = minisitename.replace("#","");
		minisitename = getMinisiteName();
		poststring = poststring+ "&minisitename="+minisitename

	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = getPreviousLookup;

	 //
	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	//alert(poststring);
	xhReq.send(poststring);
}*/
function showPreviousLookupNewParent(lookuptablename, lookupid, parenttablename, parentid) {
	//alert("showpreviouslookup");
	
	// in this case, the child record should be deleted from the database first
	// this is a PROPER delete as opposed to a 'delete' requested by the user / moderator, whic
	// only flags the data as deleted

	// so the CANCEL button should only appear for an 'add new' operation


	xhReq = createXMLHttpRequest();
	// remove any dodgy characters
	var postdata = formData("userDataCapture");
	var poststring = stripNonValidXMLCharacters(postdata);
	poststring = poststring.substr(0,poststring.length - 1);

	poststring = poststring + "&parenttablename="+parenttablename+"&parentid="+parentid;
	poststring = poststring + "&lookuptablename="+lookuptablename+"&lookupid="+lookupid;
	poststring = poststring + "&action=showPreviousChildNewParent";
	
		//var sPath = window.location;
		//var paths = String(sPath).split("=");
		//minisitename = paths[1];
		//minisitename = minisitename.replace("#","");
		minisitename = getMinisiteName();
		poststring = poststring+ "&minisitename="+minisitename;

	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = getPreviousLookup;

	 //
	 try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	//alert(poststring);
	xhReq.send(poststring);
}


function saveToServer(tablename) {

	//alert("all data correct");
	
	xhReq = createXMLHttpRequest();
	poststring = formData("userDataCapture");
	
	
	
	// remove any dodgy characters
	
	//poststring = poststring.replace("\'"," ");
	poststring = stripNonValidXMLCharacters(poststring);
	//poststring = escape(poststring);
	// remove any single quotes ..
	
	poststring = poststring.substr(0,poststring.length - 1);




	// check if there is any information about a photo that has been uploaded
	// this will be held on a separate form as photos need separate handling
	if (document.getElementById('photoname')) {
		photoname = getPhotoName(document.getElementById('photoname').value);
		poststring = poststring + "&photoname="+ photoname;
	}
	// now add the tablename
	poststring = poststring + "&tablename="+tablename;
	// now add the user id
	poststring = poststring + "&userID="+myUsername;


	// now add the minisite information ...
	 minisitename = getMinisiteName();
	poststring = poststring + "&minisitename="+minisitename;
	//alert(selectedGeometryType);
	// if this is a geometry, then add coordinate information
	if (pts.length > 0) { 
		poststring = poststring + "&hasgeometry=true";
		// now add the coordinate information 
		poststring = poststring + "&geometrytype="+ selectedGeometryType;  

		// now iterate through the points and add to the push statement
		var pointsstring = "&points=";
	
		for (var i=0;i< pts.length ; i++) {
			pt = pts[i];
			pointsstring = pointsstring + pt.x +" "+pt.y +",";
		}
		//remove the last comma from pointstring
		pointsstring = pointsstring.substr(0,pointsstring.length -1);
		poststring = poststring + "&"+pointsstring;
	} // has pts.length > 0
	else {
		poststring = poststring + "&hasgeometry=false";
	} // pts.length = 0
	 
	 poststring = poststring +"&action=saveParent";
	 //alert(poststring);
	 xhReq.open("POST", "processAddNewData.php", true);
	 xhReq.onreadystatechange = processed;
	try {
	   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	 //alert(poststring);
	xhReq.send(poststring);
}

function deleteNewCapture(tablename,id) {
	// this is used where a record is first being created ...
	if (confirm("Cancel Data Capture?  You will lose all changes.")) {
		// delete the record from the server ...
			// in this case, the child record should be deleted from the database first
			// this is a PROPER delete as opposed to a 'delete' requested by the user / moderator which 
			// only flags the data as deleted
			
			// so the CANCEL button should only appear for an 'add new' operation
			
			xhReq = createXMLHttpRequest();
			// remove any dodgy characters
			poststring = "";
			poststring = poststring + "&tablename="+tablename+"&id="+id;
			poststring = poststring + "&action=clearParent";
			 xhReq.open("POST", "processEditData.php", true);
			 xhReq.onreadystatechange = processCancelNewCapture;
			 //
			 try {
			   xhReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			   //xhReq.setRequestHeader('Content-Type','text/html')
			 }
			 catch (e) {
			 	// this only works in internet explorer
			 }
			//alert(poststring);
		xhReq.send(poststring);
	}

}
function processCancelNewCapture() {
if (xhReq.readyState != 4)  {
   		return;
   	}
	var result = xhReq.responseText;
	clearAllAddNewValues();
	
	//alert("in cancel capture");
	addContentText3 = document.getElementById('controlcontent').innerHTML;
	document.getElementById('controlcontent').innerHTML = addContentText1; 	

	// remove the black div
	removeDiv('mapoverlay','mapwrapper');
		
}


function processed() {

	// wait for the request to be ready
   if (xhReq.readyState != 4)  {
   		return;
   	}
	var result = xhReq.responseText;
	alert(result);
	startCapture = false;
	// clear all values if there has been a geometry captured ...
	if (pts.length > 0) {
		// note that this calls another response and invalidates the current response
		clearAllAddNewValues();
	}
	
	// now reset to step 1 ...
	
	addContentText3 = document.getElementById('controlcontent').innerHTML;
	document.getElementById('controlcontent').innerHTML = addContentText1;

	removeDiv('mapoverlay','mapwrapper');
	
}



//=====================================
function setupAddContentTab3() {
	
	//alert("setup add content tab 3");
	 // capture the geometry type first
	 

	 processStep3Map();

	 minisitename = getMinisiteName();

	 xhReqContent3= createXMLHttpRequest();
	 xhReqContent3.open("POST", "addContentStep3.php",true);

	 xhReqContent3.onreadystatechange = completeAddContentTab3;
	try {
	   xhReqContent3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	 xhReqContent3.send("minisitename="+minisitename);	
	
}

function completeAddContentTab3() {
   if (xhReqContent3.readyState != 4)  { 
   		return;
   	}
	
	var serverResponse = xhReqContent3.responseText;

	addContentText3 = serverResponse;
	
}



function setupAddContentTab2() {
	
	
	var themeSelected = contentLayer;
	minisitename = getMinisiteName();
	
	 xhReqContent2 = createXMLHttpRequest();
	 xhReqContent2.open("POST", "addContentStep2.php",true);

	 xhReqContent2.onreadystatechange = completeAddContentTab2;
	try {
	   xhReqContent2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 }
	 catch (e) {
		// this only works in internet explorer
	 }
	 xhReqContent2.send("minisitename="+minisitename+"&theme="+themeSelected+"&displayname="+contentLabel);

}

function completeAddContentTab2() {
   if (xhReqContent2.readyState != 4)  { 
   		return;
   	}
	var serverResponse = xhReqContent2.responseText;
	
	addContentText2 = serverResponse;
	
	// save the previous HTML
	addContentText1 = document.getElementById('controlcontent').innerHTML;
	
	document.getElementById('controlcontent').innerHTML = addContentText2;	 	

	// also enable the data capture process
	startDataCapture();
}
function setupStep3() {
	
	// generate the content of the form
	// also need to change the content of controlcontent!
	
	generateForm();


}


var xhReqContent3;
var xhReqShowForm;

function generateForm(){


	minisitename = getMinisiteName();
	//processStep3Map();
	
	// Yang 
	 
	 if (processStep3Map() == true)
		{
			setupStep4();	
		}
		
		else 
		{
			try { 
				exit();
			} catch (e) {}
			
			// make sure there are no data points left from step 3
			try {
				clearCaptureOverlays();
	
			} catch (e) {}
		}
	// Yang ends
 
}

//function showEmptyForm() {
//
//
// if (xhReqShowForm.readyState != 4)  { 
//   		return;
//   	}
//	var serverResponse = xhReqShowForm.responseText;
//	alert(serverResponse);
//	
	// split the javascript out
	
// temporary test to show a div ..
//}


function updateControlContentStep3() {
	
		var themeSelected = contentLayer;
		minisitename = getMinisiteName();
		 //alert("control step 3");
		 xhReqContent3 = createXMLHttpRequest();
		 xhReqContent3.open("POST", "addContentStep3.php",true);
	
		 xhReqContent3.onreadystatechange = showStep3Content;
		try {
		   xhReqContent3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 }
		 catch (e) {
			// this only works in internet explorer
		 }
	
	
	xhReqContent3.send("minisitename="+minisitename+"&theme="+themeSelected+"&displayname="+contentLabel);
}
function showStep3Content(){
	if (xhReqContent3.readyState != 4)  { 
   		return;
   	}
	var serverResponse = xhReqContent3.responseText;
	//alert(serverResponse);
	addContentText2 = document.getElementById('controlcontent').innerHTML;
	document.getElementById('controlcontent').innerHTML = serverResponse;	 	
}

function backToStep2() {

	addContentText3 = document.getElementById('controlcontent').innerHTML;
	
	document.getElementById('controlcontent').innerHTML = addContentText2;
	
	// but also need to remove the form div!!!
	



}

function backToStep1() {
	
	// get the content for the first step
	

	// store the previous values
	addContentText2 = document.getElementById('controlcontent').innerHTML;
	
	document.getElementById('controlcontent').innerHTML = addContentText1;	
	
	// clear anything that has been drawn on the map
	clearCaptureOverlays();
}

function clearAllAddNewValues() {

	doCloseInfoWindow();
	doCloseFormWindow();
	
	startCapture = false;
	
	// make sure the date picker is closed
	try {
	  var pickerDiv = document.getElementById(datePickerDivID);
	  pickerDiv.style.visibility = "hidden";
	  pickerDiv.style.display = "none";
	} catch (e) {}

	
	// reset to the start of the data captuer process
	
	clearCaptureOverlays(); // this gets rid of any geometry and also of any values in pts[]
	
	// reset the cursor on the map just in case!
	document.getElementById("mapinterface").style.cursor="hand";	
	
	// clear all the hidden values
	
	// then setup the first step again
	setupStep1();
	
}

