var step2html="Step 2";
var step1html="Step 1";
var step3postcodehtml="Step 3 postcode";
var step3maphtml="Step 3 map";
var step4html="Step 4";
var captureUserDatahtml = "capture userdata";
//var localSearch = new GlocalSearch();
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 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 gotoLoginPage() {
	// switch the user back to the map legend tab ..
	//ManageTabPanelDisplay('tab1ready','tab2focus','tab3ready','content2','tab4ready');
	// then call the login page in a separate window ...
	
	window.open("http://www.london21.org/user/login");
}

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) {
		//	alert("pop");
			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(document.forms["processdata"].selected_data_type.value);
	var linecolour = getColour(document.forms["processdata"].selected_data_type.value);
	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);
			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);
				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);
				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";
	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 removeCoordinate() {
	// clear all overlays and start again !
	// don't remove just the one coordinate
	clearCaptureOverlays();	
}

function checkPostcode(postcode) {
      postcode = postcode + " " + "UK";
      if (geocoder) {
        geocoder.getLatLng(
          postcode,
          function(point) {
            if (!point) {
              alert("Postcode and Streetname were not matched -  please try again.");
            } 
            else {
		//document.forms["processdata"].selected_postcode.value = document.forms["processdata"].postcode.value;
		// this is a point data type
		//document.forms["processdata"].selected_geometrytype.value = "point";
		// add the point to the list of points
		//pts.push(point);
		// draw the point on screen
		//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(document.forms["processdata"].selected_data_type.value);
		//var linecolour = getColour(document.forms["processdata"].selected_data_type.value);
		//var pointIcon = new GIcon(bicon, pointIconLocation, null, null );

		//thePoint = new GMarker(point, {icon:pointIcon, draggable: false});
		//map.addOverlay(thePoint);
		//tempPts.push(thePoint);
		map.setCenter(point, 15);
            }
          }
        );
      }
}

function processClearMapData() {
	// we are starting step 3 map again
	startCapture = false;
	GEvent.removeListener(dataCaptureListener);
	clearCaptureOverlays();
	setupStep3Map();
	

}
function processUndoMapData() {
	clearCaptureOverlays();

}

function processStep3Map() {
	//alert(pts.length);
	if (pts.length == 0) {
		alert("Please draw on the map");
		return 0;
	}
	if (document.forms["processdata"].feature_type[0].checked ) {
		document.forms["processdata"].selected_geometrytype.value = "point";
		// capturing a point
		if (pts.length != 1) {
			alert("Please draw a single point on the map");
			return 0;
		}
	}
	if (document.forms["processdata"].feature_type[1].checked ) {
		document.forms["processdata"].selected_geometrytype.value = "line";
		// capturing a line
		
		if (pts.length < 2) {
			alert("Please draw a line on the map - you need at least 2 points");
			return 0;
		}
	}
	if (document.forms["processdata"].feature_type[2].checked ) {
		document.forms["processdata"].selected_geometrytype.value = "polygon";
		// capturing a polygon
		if (pts.length < 3) {
			alert("Please draw a polygon on the map - you need at least 3 points");
			return 0;
		}
		// add the first point again to close the polygon
		pts.push(pts[0]);
	}
	
	document.getElementById("map-canvas").style.cursor="hand";
	setupStep4();
}


function processStep3Postcode() {
	
	/*if (document.forms["processdata"].postcode.value.length == 0) {
		alert("Please type in a postcode");
	}
	if (document.forms["processdata"].streetname.value.length == 0) {
		alert("Please type in a street name");
	}*/
	
	//else {
	if (document.getElementById("postcode").value.length == 0) {
		alert("Please type in a postcode");
		return;
	}
	if (document.getElementById("streetname").value.length == 0) {
		alert("Please type in a street name");
		return;
	}

	//+ " " + document.forms["processdata"].streetname.value
		//var postcodeString = document.forms["processdata"].postcode.value + " " + document.forms["processdata"].streetname.value
		var postcodeString = document.getElementById("postcode").value + " " + document.getElementById("streetname").value
		checkPostcode(postcodeString);
		
	//}
}



function processStep1() {
	// for now, this will depend on whether the website is an mcsc site or archway ...
	var sPath = window.location.pathname;
	if (sPath.indexOf("Archway") > 0) {
		if (document.forms["processdata"].data_type1.checked ) {
			document.forms["processdata"].selected_data_type.value = "classes";
		}
		if (document.forms["processdata"].data_type2.checked ) {
			document.forms["processdata"].selected_data_type.value = "reuserecycle";
		}
		if (document.forms["processdata"].data_type3.checked ) {
			document.forms["processdata"].selected_data_type.value = "greenareas";
		}
		if (document.forms["processdata"].data_type4.checked ) {
			document.forms["processdata"].selected_data_type.value = "madeinarchway";
		}
		if (document.forms["processdata"].data_type5.checked ) {
			document.forms["processdata"].selected_data_type.value = "events";
		}
		if (document.forms["processdata"].data_type6.checked ) {
			document.forms["processdata"].selected_data_type.value = "organisations";
		}

	} else {
		if (document.forms["processdata"].data_type[0].checked ) {
			document.forms["processdata"].selected_data_type.value = "events";
		}
		if (document.forms["processdata"].data_type[1].checked ) {
			document.forms["processdata"].selected_data_type.value = "organisations";
		}
		if (document.forms["processdata"].data_type[2].checked ) {
			document.forms["processdata"].selected_data_type.value = "user_datas";
		}
		if (document.forms["processdata"].data_type[3].checked ) {
			document.forms["processdata"].selected_data_type.value = "large_projects";
		}
	}
	if (sPath.indexOf("Hackney") > 0) {
		if (document.forms["processdata"].data_type[0].checked ) {
			document.forms["processdata"].selected_data_type.value = "events";
		}
		if (document.forms["processdata"].data_type[1].checked ) {
			document.forms["processdata"].selected_data_type.value = "organisations";
		}
		if (document.forms["processdata"].data_type[2].checked ) {
			document.forms["processdata"].selected_data_type.value = "user_datas";
		}
		if (document.forms["processdata"].data_type[3].checked ) {
			document.forms["processdata"].selected_data_type.value = "large_projects";
		}
		if (document.forms["processdata"].data_type[4].checked ) {
			document.forms["processdata"].selected_data_type.value = "historical";
		}
	}	
	if (document.forms["processdata"].selected_data_type.value == "notselected") {
		alert("Please select the type of data you wish to capture");
	}
	else {
		document.forms["processdata"].selected_capture_type.value = "drawonmap";
		setupStep3Map();
	}
}

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() {
	// 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
	}




	document.getElementById('step1').style.color ="red";
	document.getElementById('step1').style.fontWeight ="normal";
	
	//document.getElementById('step2').style.color ="#808080";
	//document.getElementById('step2').style.fontWeight ="normal";
	
	document.getElementById('step3').style.color ="#808080";
	document.getElementById('step3').style.fontWeight ="normal";
	document.getElementById('step4').style.color ="#808080";
	document.getElementById('step4').style.fontWeight ="normal";
	
	// this will depend on whether the map is community maps or archway
	var sPath = window.location.pathname;
	if (sPath.indexOf("Archway") > 0) {
		document.getElementById('currentStep').innerHTML = step1Archwayhtml;
	} else  {
		document.getElementById('currentStep').innerHTML = step1html;
	}
	if (sPath.indexOf("Hackney") > 0) {
		document.getElementById('currentStep').innerHTML = step1Hackneyhtml;
	}
}
 
function doLogin() {
	
	theUsername = document.getElementById("username").value;
	thePassword = document.getElementById("password").value;
	if (theUsername.length == 0) {
		alert("Please type in your username");
		return;
	}
	if (thePassword.length == 0) {
		alert("Please type in your password");
		return;
	}
	
	 xhReq = createXMLHttpRequest();
	 xhReq.open("POST", "processUserLogin.php", true);
	 xhReq.onreadystatechange = isLoggedIn;

	 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("username="+theUsername+"&password="+thePassword);
}

function isLoggedIn() {
   if (xhReq.readyState != 4)  { 
   		return;
   	}
   
	var serverResponse = xhReq.responseText;
	// if the user is logged in then actually switch to the tab!
	//alert(xhReq.responseText);
	if (serverResponse.indexOf("User") > -1) { 
	//	alert("user found");
		myUsername =  serverResponse.replace("User","");
	//	alert(myUsername);
		document.getElementById('captureinstructions').style.display = "inline"; 
		var sPath = window.location.pathname;
		if (sPath.indexOf("Archway") > 0) {
			document.getElementById('currentStep').innerHTML = step1Archwayhtml;
		} else  {
			document.getElementById('currentStep').innerHTML = step1html;
		}
		if (sPath.indexOf("Hackney") > 0) {
			document.getElementById('currentStep').innerHTML = step1Hackneyhtml;
		}
	}
	if (serverResponse == "Join") { 
		document.getElementById('captureinstructions').style.display = "none"; 
		joinHTML = "You must be a member of Community Maps to add data";
		joinHTML = joinHTML + "<br><br>";
		joinHTML = joinHTML + "You can do this by clicking on <br><a href\"#\" onclick=\"javascript:gotoLoginPage()\">My Account<\a> ";
		joinHTML = joinHTML + " and clicking on My Subscriptions";
		
		document.getElementById('currentStep').innerHTML = joinHTML;
	}
	if (serverResponse == "Login") { 
		document.getElementById('captureinstructions').style.display = "none"; 
		joinHTML = "You must log in to Community Maps to add data";
		joinHTML = joinHTML + "<br><br>";
		joinHTML = joinHTML + "If you are not registered as a London21 user, click <br><a href=\"#\" onclick=\"javascript:gotoLoginPage()\">here</a>";
		joinHTML = joinHTML + " to register.  You can add data once your registration is activated.";
		joinHTML = joinHTML + "<br><br>";
		joinHTML = joinHTML + "<table>";
		joinHTML = joinHTML + "<tr><td>User e-mail:" + "</td><td><input id=\"username\" type=\"text\"></td></tr>";
		joinHTML = joinHTML + "<tr><td>Password: "+ "</td><td><input id=\"password\" onkeypress=\"checkEnterUserLogin(event)\" type=\"password\"></td></tr>";
		joinHTML = joinHTML + "<tr><td colspan = 2><button id=\"dologin\" type=\"button\" name=\"dologin\"  onclick=\"doLogin()\">Login</button></td></tr>";
		joinHTML = joinHTML + "</table>";
		document.getElementById('currentStep').innerHTML = joinHTML;
	}
	if (serverResponse == "Login failed") { 
		document.getElementById('captureinstructions').style.display = "none"; 
		joinHTML = "Incorrect Username and/or Password - please try again";
		joinHTML = joinHTML + "<br><br>";
		joinHTML = joinHTML + "If you are not registered as a London21 user, click <br><a href=\"#\" onclick=\"javascript:gotoLoginPage()\">here</a>";
		joinHTML = joinHTML + " to register.  You can add data once your registration is activated.";
		joinHTML = joinHTML + "<br><br>";
		joinHTML = joinHTML + "<table>";
		joinHTML = joinHTML + "<tr><td>User e-mail:" + "</td><td><input id=\"username\" type=\"text\"></td></tr>";
		joinHTML = joinHTML + "<tr><td>Password: "+ "</td><td><input onkeypress=\"checkEnterUserLogin(event)\" id=\"password\" type=\"password\"></td></tr>";
		joinHTML = joinHTML + "<tr><td colspan = 2><button id=\"dologin\" type=\"button\" name=\"dologin\" onclick=\"doLogin()\">Login</button></td></tr>";
		joinHTML = joinHTML + "</table>";
		document.getElementById('currentStep').innerHTML = joinHTML;
	}
	



	ManageTabPanelDisplay('tab1ready','tab2ready','tab3ready','tab4focus','content4')
 }

function setupStep2() {
	/*document.getElementById('step1').style.color ="blue";
	document.getElementById('step1').style.fontWeight ="normal";
	//document.getElementById('step2').style.color ="red";
	//document.getElementById('step2').style.fontWeight ="normal";
	document.getElementById('step3').style.color ="blue";
	document.getElementById('step3').style.fontWeight ="normal";
	document.getElementById('step4').style.color ="blue";
	document.getElementById('step4').style.fontWeight ="normal";
	document.getElementById('currentStep').innerHTML = step2html;*/
	
}

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() {
	doCloseInfoWindow();
	
	// close the date picker if it is open
	//try {
	//	document.getElementById('datepicker').style.display = "none";
	//} catch (e) {}
	//try {
	//	document.getElementById('datepickeriframe').style.display = "none";
	//
	//} catch (e) {}
	try {
	  var pickerDiv = document.getElementById(datePickerDivID);
	  pickerDiv.style.visibility = "hidden";
	  pickerDiv.style.display = "none";
	} catch (e) {}
	
//	if (document.forms["processdata"].selected_postcode.value == "notselected") {
		backtoStep3Map();
//	}
//	else {
//		backtoStep3Postcode();
//	}
}
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();
	
	// then select the correct setting for the selected geometry type
	if (document.forms["processdata"].selected_geometrytype.value == "point")  {
		document.forms["processdata"].feature_type1.checked = true;
	}
	if (document.forms["processdata"].selected_geometrytype.value == "line")  {
		document.forms["processdata"].feature_type2.checked = true;
	}
	if (document.forms["processdata"].selected_geometrytype.value == "polygon")  {
		document.forms["processdata"].feature_type3.checked = true;
	}
	if (document.forms["processdata"].selected_geometrytype.value == "notselected")  {
		// default value is a point!
		document.forms["processdata"].feature_type1.checked = true;
		document.forms["processdata"].selected_geometrytype.value = "point";
	}
	if (document.forms["processdata"].selected_data_type.value == "events" ||
		document.forms["processdata"].selected_data_type.value == "organisations") {
		document.forms["processdata"].feature_type2.disabled = true;
		document.forms["processdata"].feature_type3.disabled = true;
	}
}



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 validateUserData() {

	// there must be a title, description and expiry date
	
	if (document.forms["processdata_2"].userdatatitle.value.length == 0) {
		alert("Please type in a title for your data");
		return false;
	}
	if (document.forms["processdata_2"].userdatadesc.value.length == 0) {
		alert("Please type in a description for your data");
		return false;
	}
	if (document.forms["processdata_2"].ExpiryDate.value.length == 0) {
		alert("Please give an expiry date for the data");
		return false;
	}
	if (isDate(document.forms["processdata_2"].ExpiryDate.value) == false) {
		return false;
	}
	return true;
}
function setupStep3Map() {
	setupStep3instructions();
	var capturingString = "";
	if (document.forms["processdata"].selected_data_type.value == "organisations") {
		capturingString = "Organisations";
	}
	if (document.forms["processdata"].selected_data_type.value == "events") {
		capturingString = "Events";
	}
	if (document.forms["processdata"].selected_data_type.value == "user_datas") {
		capturingString = "Our Data";
	}
	if (document.forms["processdata"].selected_data_type.value == "large_projects") {
		capturingString = "Large Projects";
	}
	if (document.forms["processdata"].selected_data_type.value == "classes") {
		capturingString = "Classes";
	}
	if (document.forms["processdata"].selected_data_type.value == "reuserecycle") {
		capturingString = "Reuse/Recycle";
	}
	if (document.forms["processdata"].selected_data_type.value == "greenareas") {
		capturingString = "Green Areas";
	}
	if (document.forms["processdata"].selected_data_type.value == "historical") {
		capturingString = "Historical";
	}
	if (document.forms["processdata"].selected_data_type.value == "madeinarchway") {
		capturingString = "Made in Archway";
	}

	
	var totalHTML = "<span style=\"font-size: 140%;font-weight:bold\">Capturing: " + capturingString + "</span><BR>"+step3maphtml;	
	document.getElementById('currentStep').innerHTML = totalHTML;
	
	
	// if this is an event or an organisation, only allow point data capture for now!
	if (document.forms["processdata"].selected_data_type.value == "events" ||
		document.forms["processdata"].selected_data_type.value == "organisations") {
		document.forms["processdata"].feature_type1.checked = true;
		document.forms["processdata"].selected_geometrytype.value = "point";
		document.forms["processdata"].feature_type2.disabled = true;
		document.forms["processdata"].feature_type3.disabled = true;
		startCapture = true;
		startDataCapture();
	}
	else {
	
		// default value is a point
		document.forms["processdata"].feature_type1.checked = true;
		document.forms["processdata"].selected_geometrytype.value = "point";
		startDataCapture();
	}
	
	
	//alert("Functionality only currently implemented for Postcode entry");
	document.forms["processdata"].selected_postcode.value = "notselected";
}

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();
	 xhReqData.open("POST", "generateDataCaptureForm.php", true);
	 xhReqData.onreadystatechange = step4Html;

	 
	 try {
	   xhReqData.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   //xhReq.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	 var tablename = document.forms["processdata"].selected_data_type.value;
	 xhReqData.send("tablename="+tablename);

}

function step4Html()  {

   if (xhReqData.readyState != 4)  {
   		return;
   	}
   	
	var responseText = xhReqData.responseText;

	// ============================================
	// following code moved over from the function that calls the http request
	document.getElementById('opaquetext').innerHTML = "";
	document.getElementById('container2').style.left = "0px";
	document.getElementById('container2').style.top = "0px";
	document.getElementById('container2').style.width = document.getElementById('map-canvas').style.width;
	document.getElementById('container2').style.height = "100%"; //document.getElementById('map-canvas').style.height;
	document.getElementById('container2').style.display = "block";

		
	var capturingString = "";
	if (document.forms["processdata"].selected_data_type.value == "organisations") {
		capturingString = "Organisations";
	}
	if (document.forms["processdata"].selected_data_type.value == "events") {
		capturingString = "Events";
	}
	if (document.forms["processdata"].selected_data_type.value == "user_datas") {
		capturingString = "Our Data";
	}
	if (document.forms["processdata"].selected_data_type.value == "large_projects") {
		capturingString = "Large Projects";
	}
	if (document.forms["processdata"].selected_data_type.value == "classes") {
		capturingString = "Classes";
	}
	if (document.forms["processdata"].selected_data_type.value == "reuserecycle") {
		capturingString = "Reuse/Recycle";
	}
	if (document.forms["processdata"].selected_data_type.value == "greenareas") {
		capturingString = "Green Areas";
	}
	if (document.forms["processdata"].selected_data_type.value == "madeinarchway") {
		capturingString = "Made in Archway";
	}
	if (document.forms["processdata"].selected_data_type.value == "historical") {
		capturingString = "Historical";
	}


	
	var totalHTML = "<span style=\"font-size: 140%;font-weight:bold\">Capturing: " + capturingString + "</span>";	
		
		
	document.getElementById('currentStep').innerHTML = totalHTML;
	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 ="#808080";
	document.getElementById('step3').style.fontWeight ="normal";
	document.getElementById('step4').style.color ="red";
	document.getElementById('step4').style.fontWeight ="normal";
	// ============================================

	// the basics of the popup form - which contain the close button, just in case there is a problem
	var basicHTML = "<div style=\"height:85%\">";
	basicHTML = basicHTML+"<INPUT TYPE=\"image\" SRC=\"../images/addline.png\" VALUE=\"Close\"";
	basicHTML = basicHTML+"ALT=\"Close\" NAME=\"Close\" onclick=\"cancelCapture()\" style=\"height:20px;width:20px;float:right;\">";
	basicHTML = basicHTML+"<div style=\"height:5px;width:100%\">";
	basicHTML = basicHTML+"</div>"; // end of the gap div at the top of the table

	
	
	
	//alert( xhReqData.responseText);
	var splitresult = responseText.split("||");
	//alert (splitresult[0]);
	//alert (splitresult[1]);
	//document.getElementById('newdiv').innerHTML = splitresult[0];;

	document.getElementById('opaquetext').innerHTML = basicHTML + splitresult[0];


	//now split out the text and the script parts !
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	//newScript.src = splitresult[1]; //'http://www.somedomain.com/somescript.js';
	newScript.text = splitresult[1];
	headID.appendChild(newScript);
	
	
	// if a postcode has been added then type it into the postcode field if there is one!
	if (document.forms["processdata"].selected_postcode.value != "notselected") {
		try {
			document.forms["userDataCapture"].postcode.value = document.forms["processdata"].selected_postcode.value ;
			// disable the field
			document.forms["userDataCapture"].postcode.disabled = true;
		}
		catch (e) {
			// there isnt' a postcode field
			// nb assumes that postcode is NEVER mandatory
		}
	}
}
function backtoStep2() {
	//map.clearOverlays();
	
	// we are not doing postcode so go straight back to setp 1
	backtoStep1();
	
	
	/*setupStep2();
	if (document.forms["processdata"].selected_capture_type.value == "postcode") {
		document.forms["processdata"].capture_type[0].checked = true;
	}
	if (document.forms["processdata"].selected_capture_type.value == "drawonmap") {
		document.forms["processdata"].capture_type[1].checked = true;
	}
	startCapture = false;
	updateMap(true);*/
}
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 backtoStep1() {
	setupStep1();
	reenableMap();
	var sPath = window.location.pathname;
	if (sPath.indexOf("Archway") > 0) {
		if (document.forms["processdata"].selected_data_type.value == "classes") {
			document.forms["processdata"].data_type[0].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "reuserecycle") {
			document.forms["processdata"].data_type[1].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "greenareas") {
			document.forms["processdata"].data_type[2].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "madeinarchway") {
			document.forms["processdata"].data_type[3].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "events") {
			document.forms["processdata"].data_type[5].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "organisations") {
			document.forms["processdata"].data_type[6].checked = true;
		}
		
	} else {
		if (document.forms["processdata"].selected_data_type.value == "events") {
			document.forms["processdata"].data_type[0].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "organisations") {
			document.forms["processdata"].data_type[1].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "user_datas") {
			document.forms["processdata"].data_type[2].checked = true;
		}
		if (document.forms["processdata"].selected_data_type.value == "large_projects") {
			document.forms["processdata"].data_type[3].checked = true;
		}
		// historical layer for Hackney Wick
		if (sPath.indexOf("Hackney") > 0) {
			if (document.forms["processdata"].selected_data_type.value == "historical") {
				document.forms["processdata"].data_type[4].checked = true;
			}
		}
	}
}


function drawLine() {

		var userPolylineString = "new GPolyline([";
		//alert(userPolylineString);
		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);";
	//	alert(userPolylineString);		
	//	var userPolyline1 = eval(userPolylineString);
	//	alert(userPolyline1.getLength());
	//	map.addOverlay(userPolyline1);

		var polyline = new GPolyline([new GLatLng(51.51, 0.08),new GLatLng(51.50, 0.07)], "#FF0000", 5);
		map.addOverlay(polyline);
		//alert("added ");
	
}

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) { 
	//alert("cursor");
    try { 
        object.style.cursor=cursorStyle; 
    } 
    catch(c) { 
    	//alert("catch");
         if ( cursorStyle=="pointer" ) { 
        // alert("hand");
             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();
}