function GetXmlHttpObject()
	{
	    var objXMLHttp=null
	    if (window.XMLHttpRequest)
	    {
	        objXMLHttp=new XMLHttpRequest()
	    }
	    else if (window.ActiveXObject)
	    {
	        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	    }
	    return objXMLHttp
	}

	//Use the GClientGeocoder class and its method getLatLng(address:String, callback:function):

	dist = 0;
	function initialize() 
	{ 
		logActivity();
      	if (GBrowserIsCompatible()) 
	  	{ 
    	    map = new GMap2(document.getElementById("map_canvas")); 
			map.setCenter(new GLatLng(54.86, -1.597), 6); 

			document.getElementById("map_canvas").style.cursor = "Crosshair";

		}
	
		map.addControl(new GLargeMapControl());
		
//		getSpeedCameras();
			
		GEvent.addListener(map, 'click', function(overlay, point)
		{
			if(point)
			{
				userLat = point.lat();
				userLng = point.lng();
				
				document.coordinates.lastCoordinate.value = document.coordinates.currentCoordinate.value;
				document.coordinates.currentCoordinate.value = userLat +"," + userLng;
				
				startPoint = document.coordinates.lastCoordinate.value;
				
				if(startPoint != "")
				{
					lastPoint = document.coordinates.currentCoordinate.value;
					
				 	startPointsArray = startPoint.split(",");
					lastPointsArray = lastPoint.split(",");
					
					var points = [   
		   				new GLatLng(startPointsArray[0], startPointsArray[1]),
						new GLatLng(lastPointsArray[0], lastPointsArray[1])];
					
					var polyline = new GPolyline(points, '#ff0000', 5, 0.7);   
								
					try
					{
						polylineArray.push(polyline);						
					}
					catch(ex)
					{
						
					}	
					coordinatesArray.push(lastPoint);					
					completeCoordinates.push(document.coordinates.lastCoordinate.value + " " + document.coordinates.currentCoordinate.value);
					//alert(document.coordinates.lastCoordinate.value + " " + document.coordinates.currentCoordinate.value);
					map.addOverlay(polyline);
					dist = dist + polyline.getLength();
			
					document.getElementById('distance').value = Math.round(calculateMiles()*100)/100;
					//alert(document.coordinates.lastCoordinate.value+"\n"+document.coordinates.currentCoordinate.value)
				}
				else
				{

				}
			}
		});
    } 
//This function is used to draw the rideout
    function initialize2(roid) 
	{ 
      	if (GBrowserIsCompatible()) 
	  	{ 
    	    map = new GMap2(document.getElementById("map_canvas")); 
			map.setCenter(new GLatLng(54.86, -1.597), 5); 

			document.getElementById("map_canvas").style.cursor = "Crosshair";

		}
	
		map.addControl(new GLargeMapControl());
		
//		getSpeedCameras();
		
		drawRideout(roid);
    } 
    function removePolyline()
	{
	 	try
	 	{
			//startPoint = document.coordinates.lastCoordinate.value;
			if(startPoint != "")
			{
				//alert(polylineArray.length);
				var polyline = polylineArray[polylineArray.length - 1];		
				map.removeOverlay(polyline);
				polylineArray.pop();
				coordinatesArray.pop();
				completeCoordinates.pop();
					
				if(coordinatesArray.length > 0)
				{
			
					var newLast = coordinatesArray[coordinatesArray.length - 1];	
					document.coordinates.currentCoordinate.value = newLast;
					
				}
				else
				{
					var newLast = "";
				}
		
				if(coordinatesArray.length != 0)
				{
					document.coordinates.currentCoordinate.value = newLast;
				}
				else
				{
					document.coordinates.currentCoordinate.value = "";
				}
				
				dist -= polyline.getLength();
				
				document.getElementById('distance').value = Math.round(calculateMiles()*100)/100;
				alert(dist);
	//			document.coordinates.currentCoordinate.value = userLat +"," + userLng;
	
			}
			else
			{
				alert("nothing to remove");
				routeStartPoint = "";
			}	
			
			
		}
		catch(ex){}
	}

	function validateForm()
	{
	 	var returnVal = true;

		var rideoutType = document.getElementById("newRoute").selectedIndex;
		
 	
		document.getElementById("titleError").style.display = "none";
	 	
		document.getElementById("addressError").style.display = "none";

		document.getElementById("difficultyLevelError").style.display = "none";
		document.getElementById("pcError").style.display = "none";
		document.getElementById("rangeError").style.display = "none";
	
			
		document.getElementById("roTitleError").style.display = "none";
	
		document.getElementById("meetingPointError").style.display = "none";

		document.getElementById("startDateError").style.display = "none";	
		document.getElementById("endDateError").style.display = "none";
		document.getElementById("startTimeError").style.display = "none";

		if(rideoutType == 0)
		{
			//validate as a new route
			if(document.coordinates.title.value == "")
	 		{ 		 
				document.getElementById("titleError").style.display = "block";
				returnVal = false;
			}
			
			if(document.coordinates.address.value == "")
			{
			 	document.getElementById("addressError").style.display = "block";
				returnVal = false;			
			}
			if(document.coordinates.difficultyLevel.selectedIndex == 0)
			{
			 	document.getElementById("difficultyLevelError").style.display = "block";
				returnVal = false;	
			}
				
		}
		else
		{
			//Validate as an existing route
			if(document.coordinates.postcodeRange.value == "")
			{
			 	document.getElementById("pcError").style.display = "block";
				returnVal = false;	
			}
			if(document.coordinates.distanceRange.selectedIndex == 0)
			{
			 	document.getElementById("rangeError").style.display = "block";
				returnVal = false;	
			}
			if(document.coordinates.existingRideout.selectedIndex == 0)
			{
			 	document.getElementById("existingROError").style.display = "block";
				returnVal = false;	
			}
			
			//document.getElementById("existingRideout").style.display = "none";
		}
		 
		if(document.coordinates.routeCoordinates.value == "")
		{
			//alert("You must plan a new route or select one from the list");
			//alert("here");
			//returnVal = false;			
		}
		if(document.coordinates.roTitle.value == "")
		{
		 	document.getElementById("roTitleError").style.display = "block";
			returnVal = false;			
		}
		if(document.coordinates.meetingPoint.value == "")
		{
			document.getElementById("meetingPointError").style.display = "block";
			returnVal = false;			
		}
		
		var pattern = new RegExp(/^[0-3][0-9]\/(0|1)[0-9]\/(19|20)[0-9]{2}$/);

		
		if(!document.coordinates.startDate.value.match(pattern))
		{
			document.getElementById("startDateError").style.display = "block";
			returnVal = false;			
		}
		var timePattern = new RegExp(/([0-1][0-9]|2[0-3]):([0-5][0-9])/);
		if(!document.coordinates.startTime.value.match(timePattern))
		{
		 	document.getElementById("startTimeError").style.display = "block";
			returnVal = false;			
		}
	
	

	 	if(returnVal == true)
	 	{
			getRouteCoordinates();			
		}
		
	}

	function getRouteCoordinates()
	{
	 	var rideoutType = document.getElementById("newRoute").selectedIndex;
	 	
	 	if(rideoutType == 0)
	 	{
		 	var stringBuilder = "";
			for(i = 0; i < completeCoordinates.length; i++)
			{
				//stringBuilder += completeCoordinates[i] + "|";	
				stringBuilder += completeCoordinates[i] + "|";
			}		
			document.coordinates.routeCoordinates.value = stringBuilder;
		
			saveNewRouteRideout();
		}
		else
		{
			saveExistingRouteRideout()
		}
		
	}
    
	function saveExistingRouteRideout()
    {
     
		var date = new Date();
	    var xmlhttp;
	
	    xmlhttp=GetXmlHttpObject()
	
	    if (xmlhttp==null)
	    {
	        alert ("Browser does not support HTTP Request");
	        return;
	    }
	
		selectedRide = document.getElementById("existingRideout").options[document.getElementById("existingRideout").selectedIndex].value;
		
		rideTitle = encodeURI(document.coordinates.title.value);
		rideAddress = encodeURI(document.coordinates.address.value);
		difficultyLevel = encodeURI(document.coordinates.difficultyLevel.value);
		info = encodeURI(document.coordinates.info.value);
		distance = encodeURI(document.coordinates.distance.value);
		completeCoordinates = encodeURI(document.coordinates.routeCoordinates.value);
		roTitle = encodeURI(document.coordinates.roTitle.value);
		meetingPoint = encodeURI(document.coordinates.meetingPoint.value);
		startDate = encodeURI(document.coordinates.startDate.value);
		
		startTime = encodeURI(document.coordinates.startTime.value);
		endDate = encodeURI(document.coordinates.endDate.value);
		roDesc = encodeURI(document.coordinates.roDesc.value);
	
	    var url="saveRideout.php";
	    
	    var parameters = "coordinates="+completeCoordinates+"&title="+rideTitle+"&address="+rideAddress+"&difficultyLevel="+difficultyLevel+"&roTitle="+roTitle+"&distance="+distance+"&meetingPoint="+meetingPoint+"&startDate="+startDate+"&startTime="+startTime+"&endDate="+endDate+"&roDesc="+roDesc+"&info="+info+"&sr="+selectedRide+"&t="+date.getSeconds();
	    
	    xmlhttp.open("GET",url+"?"+parameters,false);
	    xmlhttp.send(null);
	
		//alert(xmlhttp.responseText);
		window.location="viewrideout.php?roid=" + xmlhttp.responseText;
		//true will = readonly
		//enableDisableRouteForm(true);
		//enableDisableRideoutForm(true);
	}
	
    function saveNewRouteRideout()
    {
		var date = new Date();
	    var xmlhttp;
	
	    xmlhttp=GetXmlHttpObject()
	
	    if (xmlhttp==null)
	    {
	        alert ("Browser does not support HTTP Request");
	        return;
	    }
	
		selectedRide = document.getElementById("existingRideout").options[document.getElementById("existingRideout").selectedIndex].value;
		
		rideTitle = encodeURI(document.coordinates.title.value);
		rideAddress = encodeURI(document.coordinates.address.value);
		difficultyLevel = encodeURI(document.coordinates.difficultyLevel.value);
		info = encodeURI(document.coordinates.info.value);
		distance = encodeURI(document.coordinates.distance.value);
		completeCoordinates = encodeURI(document.coordinates.routeCoordinates.value);
		roTitle = encodeURI(document.coordinates.roTitle.value);
		meetingPoint = encodeURI(document.coordinates.meetingPoint.value);
		startDate = encodeURI(document.coordinates.startDate.value);
		
		startTime = encodeURI(document.coordinates.startTime.value);
		endDate = encodeURI(document.coordinates.endDate.value);
		roDesc = encodeURI(document.coordinates.roDesc.value);
	
	    var url="saveRideout.php";
	    
	    var parameters = "coordinates="+completeCoordinates+"&title="+rideTitle+"&address="+rideAddress+"&difficultyLevel="+difficultyLevel+"&roTitle="+roTitle+"&distance="+distance+"&meetingPoint="+meetingPoint+"&startDate="+startDate+"&startTime="+startTime+"&endDate="+endDate+"&roDesc="+roDesc+"&info="+info+"&sr="+selectedRide+"&t="+date.getSeconds();
	    
	    xmlhttp.open("GET",url+"?"+parameters,false);
	    xmlhttp.send(null);


		//true will = readonly
		//enableDisableRouteForm(true);
		//enableDisableRideoutForm(true);
		window.location="viewrideout.php?roid=" + xmlhttp.responseText;
	}
    
    function enableDisableRideoutForm(trueFalse)
    {
		document.coordinates.roTitle.readOnly = trueFalse;
		document.coordinates.meetingPoint.readOnly = trueFalse;
		document.coordinates.startDate.readOnly = trueFalse;;
		document.coordinates.endDate.readOnly = trueFalse;
		document.coordinates.roDesc.readOnly = trueFalse;
	}
    
    function enableDisableRouteForm(trueFalse)
    {
		document.coordinates.title.readOnly = trueFalse;
		document.coordinates.address.readOnly = trueFalse;
		document.coordinates.difficultyLevel.readOnly = trueFalse;
		document.coordinates.info.readOnly = trueFalse;
		document.coordinates.distance.readOnly = trueFalse;
	
	}
    
	function clearMap()
	{
	 	try
	 	{
			for(i = coordinatesArray.length; i > 0; i--)
			{
				removePolyline();		
				dist = 0;
				document.getElementById('distance').value = 0;
			}		
		}
		catch(ex){}		
	}	
	
	function getCoordinates(address)
	{
	 	//map = new GMap2(document.getElementById("map_canvas")); 
		var address = document.coordinates.address.value;
		if(address != '')
		{
			address = address + ", uk";
			geocoder.getLatLng(address, function(point){
				if(point != null)
				{
					document.coordinates.lat.value = point.lat();
					document.coordinates.lng.value = point.lng();
					
						map.setCenter(new GLatLng(point.lat(), point.lng()), 14); 
					
				}
				else
				{
					alert("location not found");
				}
			})
		}
		else
		{
			alert("enter and address");
		}
		
	}
    function calculateMiles()
    {
		var miles = dist * 0.000621371192237334;
		return miles;
	}
	
	function getSpeedCameras2(cameras)
	{
		cameras;
	}
	
	function getSpeedCameras()
	{
			var date = new Date();
		    var xmlhttp;
		
		    xmlhttp=GetXmlHttpObject()
		
		    if (xmlhttp==null)
		    {
		        alert ("Browser does not support HTTP Request");
		        return;
		    }
		
		    var url="getSpeedCameras.php";
		    var parameters = "t="+date.getSeconds();
	
		    xmlhttp.open("GET",url+"?"+parameters,false);
		    xmlhttp.send(null);
		
			//alert(xmlhttp.responseText);	
			
			camerasArray = xmlhttp.responseText.split("<br />");
	
			
			//\\var mm = new GMarkerManager(map); 

		//for(i=0; i<camerasArray.length; i++)
		var markers = [];   
		for(i=0; i<100; i++)
		{
			cameraDetailsArray = camerasArray[i].split("|");
			
			//var lat = parseFloat(cameraDetailsArray[1]);
        	//var lng = parseFloat(cameraDetailsArray[0]);
    	    //var point = new GLatLng(52.391395,-1.486848);
			var point = new GLatLng(lat, lng);
        //alert(lng);
	        var marker=new GMarker(point);

        	markers.push(marker);
        		
		}
		var markerCluster = new MarkerClusterer(map, markers);  
	  //  mm.addMarker(marker,0,17); 
		//mm.addMarkers(markers, 0, 13);
		//alert(mm.getMarkerCount(17));
//		alert(lat+", "+lng);
		//		mm.refresh();
		
	}

	function getRouteDetails()
	{	
		var routeID =  document.getElementById("existingRideout").options[document.getElementById("existingRideout").selectedIndex].value;
	
		if(routeID == 0)
		{
			map.clearOverlays();
			map.setCenter(new GLatLng(54.86, -1.597), 5); 
			document.getElementById("address").value = "";
			document.getElementById("difficultyLevel").value = "";
			document.getElementById("routeCoordinates").value = "";
			document.getElementById("distance").value = "";
			document.getElementById("info").value = "";
			
			enableDisableRouteForm(false);
			enableDisableRideoutForm(false);
		}
		else
		{
		 	map.clearOverlays();
			enableDisableRouteForm(true);
			var date = new Date();
		    var xmlhttp;
		
		    xmlhttp=GetXmlHttpObject()
		
		    if (xmlhttp==null)
		    {
		        alert ("Browser does not support HTTP Request");
		        return;
		    }
		
		    var url="getRouteDetails.php";
		    var parameters = "id="+routeID+"&t="+date.getSeconds();
	
		    xmlhttp.open("GET",url+"?"+parameters,false);
		    xmlhttp.send(null);
	
			var routeArray = xmlhttp.responseText.split("&");
			
			document.getElementById("difficultyLevel").value = routeArray[0];
			
			document.getElementById("newAddress").value = routeArray[1];
			document.getElementById("info").value = routeArray[4];
			document.getElementById("distance").value = routeArray[3];
			document.getElementById("routeCoordinates").value = routeArray[2];
			
			
			document.getElementById("title").value = routeArray[5];
			
			
			geocoder.getLatLng(routeArray[1], function(point){
	
					if(point != null)
					{
						document.coordinates.lat.value = point.lat();
						document.coordinates.lng.value = point.lng();
						
							map.setCenter(new GLatLng(point.lat(), point.lng()), 14); 
						
					}
					else
					{
						alert("location not found");
					}
				})
			
			plotRoute(routeArray[2]);
			
		}
		
	}
	
	function drawRideout(routeID)
	{	

			var date = new Date();
		    var xmlhttp;
		
		    xmlhttp=GetXmlHttpObject()
		
		    if (xmlhttp==null)
		    {
		        alert ("Browser does not support HTTP Request");
		        return;
		    }
		
		    var url="getRideoutDetails.php";
		    var parameters = "id="+routeID+"&t="+date.getSeconds();
	
		    xmlhttp.open("GET",url+"?"+parameters,false);
		    xmlhttp.send(null);

			var routeArray = xmlhttp.responseText.split("&");
			
			geocoder.getLatLng(routeArray[1], function(point)
			{
					if(point != null)
					{
						//document.coordinates.lat.value = point.lat();
						//document.coordinates.lng.value = point.lng();
						
						map.setCenter(new GLatLng(point.lat(), point.lng()), 14); 
						
						
					}
					else
					{
						alert("location not found");
					}
				})
				
			plotRoute2(routeArray[2]);
				
	}
	function plotRoute2(coordinates)
	{

		var coordinatesArray = coordinates.split("|");

		for(i=0; i<coordinatesArray.length - 1; i++)
		{
			var polylinePoints = coordinatesArray[i].split(" ");
			var coordinatesString = polylinePoints[0]+","+polylinePoints[1];
			coordinatesStringArray = coordinatesString.split(",");
			
			var points = [   
		   				new GLatLng(coordinatesStringArray[0], coordinatesStringArray[1]),
						new GLatLng(coordinatesStringArray[2], coordinatesStringArray[3])];
					
					var polyline = new GPolyline(points, '#ff0000', 5, 0.7);   
	//alert(coordinatesStringArray[0]+"\n"+coordinatesStringArray[1]+"\n"+coordinatesStringArray[3]+"\n"+coordinatesStringArray[4]);				

					//polylineArray.push(polyline);
					//alert(polyline);

					map.addOverlay(polyline);
				
		}
		
	}
	
	function plotRoute(coordinates)
	{
		var coordinatesArray = coordinates.split("|");
		
		for(i=0; i<coordinatesArray.length - 1; i++)
		{
			var polylinePoints = coordinatesArray[i].split(" ");
			var coordinatesString = polylinePoints[0]+","+polylinePoints[1];
			coordinatesStringArray = coordinatesString.split(",");
			
			var points = [   
		   				new GLatLng(coordinatesStringArray[0], coordinatesStringArray[1]),
						new GLatLng(coordinatesStringArray[2], coordinatesStringArray[3])];
					
					var polyline = new GPolyline(points, '#ff0000', 5, 0.7);   
	//alert(coordinatesStringArray[0]+"\n"+coordinatesStringArray[1]+"\n"+coordinatesStringArray[3]+"\n"+coordinatesStringArray[4]);				

					//polylineArray.push(polyline);
					//alert(polyline);

					map.addOverlay(polyline);
				
		}
		
	}
	
	function showHidePostCodeDiv()
	{
		if(document.coordinates.newRoute.selectedIndex == 1) 
		{
			document.getElementById('existingRouteDetails').style.display = "block";	
			document.getElementById('newRideoutDetails').style.display = "none";
		}
		else
		{
			document.getElementById('existingRouteDetails').style.display = "none";	
			document.getElementById('newRideoutDetails').style.display = "block";
		}				
	}
	
	function getRoutes()
	{
	 	var date = new Date();
	    var xmlhttp;
	    
		postcodeRange = encodeURI(document.getElementById('postcodeRange').value);
		distance = encodeURI(document.getElementById('distanceRange').options[document.getElementById('distanceRange').selectedIndex].value);
		
		xmlhttp=GetXmlHttpObject()
	
	    if (xmlhttp==null)
	    {
	        alert ("Browser does not support HTTP Request");
	        return;
	    }
		
		var url="getRoutes.php";
	    
	    var parameters = "pc="+postcodeRange+"&d="+distance+"&t="+date.getSeconds();

	    xmlhttp.open("GET",url+"?"+parameters,false);
	    xmlhttp.send(null);
	    document.getElementById("retrievedRoutes").innerHTML = xmlhttp.responseText;

	}
	
	function showPage(pageID)
	{	

			var distance = encodeURI(document.getElementById("hdnDistance").value);
			var postcode = encodeURI(document.getElementById("hdnPostcode").value);
			var date = encodeURI(document.getElementById("hdnDate").value);
			window.location = "?d="+distance+"&p="+postcode+"&pn="+pageID+"&da="+date;
		
	}

	function resetPageNo()
	{
		document.getElementById('pageNo').value = 1;	
	}

	function validateSearchRideouts()
	{
	 	returnVal = true;
	 	document.getElementById("rsPostCodeError").style.visibility = "hidden";
	 	document.getElementById("rsDistanceError").style.visibility = "hidden";

		if(document.rideoutSearch.distance.selectedIndex == 0)
		{
		 	document.getElementById("rsDistanceError").style.visibility = "visible";
			returnVal = false;
		}
		if(document.rideoutSearch.postcode.value == "")
		{
		 	document.getElementById("rsPostCodeError").style.visibility = "visible";	 	
			returnVal = false;			
		}
		else
		{
			returnValue = validatePostcode(document.rideoutSearch.postcode.value);
			
			if(returnValue == 0)
			{		
				document.getElementById("rsPostCodeError").style.visibility = "visible";
				returnVal = false;
			}
		}

		return returnVal;
	}
	    
	function validatePostcode(postcode)
	{
	 	var date = new Date();
	    	var xmlhttp;
	    
		
		xmlhttp=GetXmlHttpObject()
	
	    	if (xmlhttp==null)
	    	{
	        	alert ("Browser does not support HTTP Request");
	        	return;
	    	}
		
		var url="validatePostcode.php";
	    
		var parameters = "pc="+postcode+"&t="+date.getSeconds();

	    	xmlhttp.open("GET",url+"?"+parameters,false);
		xmlhttp.send(null);
		
		return xmlhttp.responseText;


	}
		

