window.onunload = GUnload;

// Create a directions object and register a map and DIV to hold the resulting computed directions
var newdirections;
var myMap;
var searchControl;
var localSearch;

DURATION_ARRAY_SIZE = 7;
var durationArray = [];
var searchResults = [];
var polyLineArray = [];
var boundsArray = [];
var townArray =[];
var townArrayIndex = 0;
var geocoder;

var centerLatitude = 51.488251;
var centerLongitude = -0.080724;
var startZoom = 2;
var inbetwixtLat = 0;
var inbetwixtLng = 0;
var searchTerm = "";
var searchObject;
var arrayIndex = 0;
var currentPolyline = 999; // dummy number;

var firstPoint;
var firstMarker=0;
var secondPoint;
var secondMarker=0;
var townArray =[];

//Get our browser specific XmlHttpRequest object.
var receiveReq = getXmlHttpRequestObject();

function reportAlert(alertMessage)
{
	document.getElementById('intro-message').innerHTML += "Message: "+ alertMessage;
}

var postCodesearch = new GlocalSearch();
function usePointFromPostcode(postcode, callbackFunction) {
	
	postCodesearch.setSearchCompleteCallback(null, 
		function() {
			
			if (postCodesearch.results[0])
			{		
				var resultLat = postCodesearch.results[0].lat;
				var resultLng = postCodesearch.results[0].lng;
				townArray[townArrayIndex] =postCodesearch.results[0].city;
				townArrayIndex++;
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);
			}else{
				reportAlert("Address not found!");
				document.getElementById('firstBox').style.display = 'none';
				document.getElementById('secondBox').style.display = 'none';
				document.getElementById('thirdBox').style.display = 'none';
				document.getElementById('decisionBox').style.display = '';
				document.getElementById('region_radios').style.display = 'none';
				document.getElementById("decisionBox").innerHTML = "Couldn't find address: "+postcode;
				document.getElementById('go-again').style.display = '';
			}
		});	
	
	var addressString = postcode;
	if(document.radiosForm.region[0].checked === true){addressString+= ", USA";}
	if(document.radiosForm.region[1].checked === true){addressString+= ", UK";}

	postCodesearch.execute(addressString);
}

//catch a directions creation error
function erralert(){
reportAlert("error");
}

//when the directions are loaded
function onDirectionsLoad(){
  	//get the route object for the directions
  	var route = newdirections.getRoute(0);
  	//the route object consists of a total duration and distance
  	var distance = route.getDistance().meters;
    var duration = route.getDuration().seconds;
    //write the results to the log
    //~~GLog.write("Distance: "+ distance);
    //~~GLog.write("Duration: "+ duration);
    //~~GLog.write(".inbetwixt.: "+ duration/2);
    //the route object also consists of a series of steps each with an index, duration, distance and a series of vertexs
    var stepNumber = route.getNumSteps();
    var midStep = stepNumber/2;
    //~~GLog.write("Number of Steps "+stepNumber);
    //find the duration of each step
    //the midway point will occur in the middle of a step - this needs to be noted
    //the calcualtion is easy as the speed with in each step is assumed to be constant 
    var totalDuration = 0;
    var durationHolder = 0;
    var increment = -1;
    var step;
    while (totalDuration < (duration/2)) {
        increment++;
        step = route.getStep(increment);
        stepDuration = step.getDuration().seconds;
        durationHolder = totalDuration;
        totalDuration += stepDuration;
        //GLog.write("Step "+increment+" Duration: "+ stepDuration+" total duration "+totalDuration);
    }
    //~~GLog.write("the .inbetwixt. route step is "+increment);
    //the over run represents a percentage of the polyline
    var polyPercentage = (stepDuration-(totalDuration - (duration/2)))/stepDuration;
    //~~GLog.write("the .inbetwixt. is "+polyPercentage*100+"% of the "+increment+" step polyline");
    
  	//get the polyline object for the directions
    var polyline = newdirections.getPolyline();
    //get the number of vertexs in the polyline
    var numOfPoints=polyline.getVertexCount();
    //~~GLog.write("numOfPoints:" +numOfPoints);
    //what is the index number for the first vertex in each step
    //for(var increment2 = 0; increment2 < stepNumber; increment2++) {
        //load the individual step
        //var step2 = route.getStep(increment2);
        var stepStart = route.getStep(increment);
        var stepStop = route.getStep(increment+1);
        //what is the number of the vertex that starts off this step of the route? 
        var indexStart = stepStart.getPolylineIndex();
        var indexStop = stepStop.getPolylineIndex();
        //if(index<0) index = 0;
        //~~GLog.write("step "+increment+" of this route starts with vertex "+indexStart+" and ends with vertex "+indexStop);
    //}
    //get the start and end point of each vertex in the polyline
    var indexDistance = stepStart.getDistance().meters;
    var indexPercentage = indexDistance*polyPercentage;
    var indexTotal = 0;
    var indexHolder = 0;
    var increment3 = indexStart-1;
    //~~GLog.write("step distance "+indexDistance+" inbetwixt distance "+indexPercentage);
    var pointStart;
    var pointEnd;    
    while (indexTotal < indexPercentage) {
        increment3++;
        pointStart = polyline.getVertex(increment3);
        pointEnd = polyline.getVertex(increment3+1);
        indexHolder = indexTotal;
        indexTotal += pointStart.distanceFrom(pointEnd);
        //GLog.write("vertex "+increment3+" starts at "+pointStart+" and ends at "+pointEnd);
    }
    //~~GLog.write("the inbetwixt vertex is "+increment3+" somewhere inbetwixt "+pointStart+" and "+pointEnd);
    var indexLeftover = (indexPercentage - indexTotal);
    var indexLeftoverPercentage = indexLeftover/pointStart.distanceFrom(pointEnd);
    inbetwixtLat = pointEnd.lat() + ((pointEnd.lat() - pointStart.lat())*indexLeftoverPercentage);
    inbetwixtLng = pointEnd.lng() + ((pointEnd.lng() - pointStart.lng())*indexLeftoverPercentage);
    
    
    document.getElementById("IBTLat").value = inbetwixtLat;
    document.getElementById("IBTLng").value = inbetwixtLng;
    document.getElementById("HAddress1").value = document.getElementById('address1').value;
    document.getElementById("HAddress2").value = document.getElementById('address2').value;
    for (i=0; i<4; i++)
    {
	if(document.radiosForm.region[i].checked === true)
	{
		document.getElementById("regRadios").value = i;
	}
    }
    document.getElementById("FPFlag").value = 1;
    var pathAdornment = townArray[1];
    if(pathAdornment == "")
    {
		pathAdornment = document.getElementById("address2").value;
    }
    document.thirdBoxForm.action= document.getElementById("filePath").innerHTML+"index.php" + "/"+pathAdornment;
    document.thirdBoxForm.submit();
    
    //~~GLog.write("the left over inbetwixt is "+indexLeftover+" "+indexLeftoverPercentage);
    //~~GLog.write("inbetwixtLat "+inbetwixtLat+" inbetwixtLng "+inbetwixtLng);	
	
}

function doCalculateInbetwixt(point) {
		secondPoint = point;
		document.getElementById("lat1").value = firstPoint.lat();
		document.getElementById("lng1").value = firstPoint.lng();
		document.getElementById("lat2").value = secondPoint.lat();
		document.getElementById("lng2").value = secondPoint.lng();

		queryHolder = firstPoint.lat()+" "+firstPoint.lng()+" to "+point.lat()+" "+point.lng();
		//alert(queryHolder);
		other_DirectionsPanel = document.getElementById("otherDirections");
		//create a route directions object and tell it where to send the polyline and the text
		//you don't need to send the result anywhere if you don't want to
		newdirections = new GDirections("", "");
		//newdirections = new GDirections("map", "other_DirectionsPanel");
		newdirections.load(queryHolder, {getSteps:true, getPolyline:true});
		//newdirections.load(queryHolder);
		//add some events handlers to allow the results to be created before you try to calculate anything
		GEvent.addListener(newdirections, "load", onDirectionsLoad);
		GEvent.addListener(newdirections, "error", erralert);
}
    
function OnSearchComplete(sc, searcher) {
    //alert(searcher.results.length);
	
      if ( searcher.results && searcher.results.length > 0) {
	    searchResults = searcher.results;
	    //~~GLog.write("result number "+searcher.results.length);
	    var timerCount = 0;
	    var timerStep = 500;
	    //global variable
            for (var i = 0; i < searcher.results.length; i++)
	    {
		  var result = searcher.results[i];
		if (result.GsearchResultClass == GlocalSearch.RESULT_CLASS ) {
			var index1=i*2;
			var index2=index1+1;
			var getDir1 = setTimeout('calculateInbetwixt('+index1+')', timerCount);
			timerCount += timerStep;
			var getDir2 = setTimeout('calculateInbetwixt('+index2+')', timerCount);
			timerCount += timerStep;
		}
        }	
      }
      else
      {
		reportAlert("No Results Found");
	}
    }


function OnLoad() {
    
      myMap = null;
      
      if(document.getElementById("fromPreviousFlag").innerHTML === "1")
      {
		document.getElementById('firstBox').style.display = 'none';
		document.getElementById('secondBox').style.display = 'none';
		document.getElementById('thirdBox').style.display = 'none';
		document.getElementById('decisionBox').style.display = '';
		document.getElementById('region_radios').style.display = 'none';
		document.getElementById('go-again').style.display = '';
		document.getElementById("map-box-holder").style.display='';
		
		// Create a search control
		searchControl = new GSearchControl();
		// Add in a full set of searchers
		localSearch = new GlocalSearch();
		var options = new GsearcherOptions();

		inbetwixtLat = document.getElementById("fromPreviousIBTLat").innerHTML;
		inbetwixtLng = document.getElementById("fromPreviousIBTLng").innerHTML;
		firstPoint = new GLatLng(document.getElementById("fromPreviousLat1").innerHTML, document.getElementById("fromPreviousLng1").innerHTML);
		secondPoint = new GLatLng(document.getElementById("fromPreviousLat2").innerHTML, document.getElementById("fromPreviousLng2").innerHTML);
		places = document.getElementById("fromPreviousPlaces").innerHTML;
		document.getElementById("address1").value = document.getElementById("fromPreviousAddress1").innerHTML;
		document.getElementById("address2").value = document.getElementById("fromPreviousAddress2").innerHTML;
		document.radiosForm.region[document.getElementById("fromPreviousregRadios").innerHTML].checked = true;

		var messageString = "<p>Let's meet <b>inbetwixt</b> "; 
		messageString += document.getElementById('address2').value + " and ";
		messageString += document.getElementById('address1').value;
		document.getElementById('intro-message').innerHTML = messageString;


		  // Set the Local Search center point
		myMap = new GMap2(document.getElementById("mapDiv"));
		myMap.setCenter(new GLatLng(inbetwixtLat, inbetwixtLng), 12);
		// create a map
		myMap.addControl(new GSmallMapControl());
		myMap.addControl(new GMapTypeControl());

		// Create a search control
		searchControl = new GSearchControl();
		// Add in a full set of searchers
		localSearch = new GlocalSearch();
		var options = new GsearcherOptions();
		localSearch.setCenterPoint(myMap);
		localSearch.setNoHtmlGeneration();
		options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
		options.setRoot(document.getElementById("searchResultsPanel"));
		searchControl.addSearcher(localSearch, options);
		//searchControl.addSearcher(new GvideoSearch());
		// tell the searcher to draw itself and tell it where to attach
		searchControl.draw(document.getElementById("searchcontrol"));
		// tell the search control to call be on start/stop
		searchControl.setSearchCompleteCallback(myMap, OnSearchComplete);


		// Create our "tiny" marker icon
		var inbetwixtIcon = new GIcon(G_DEFAULT_ICON);
		inbetwixtIcon.image = "http://www.google.com/mapfiles/markerX.png";

		// Set up our GMarkerOptions object
		markerOptions = { icon:inbetwixtIcon };

		var marker = new GMarker(new GLatLng(inbetwixtLat, inbetwixtLng), markerOptions);
		myMap.addOverlay(marker);
		searchControl.execute(places);

      }
      else
      {
	      //document.getElementById("sponsor-panel").innerHTML = document.getElementById("instruction-content").innerHTML;
	      document.getElementById("map-box-holder").style.display='none';
	      document.firstBoxForm.address_1.focus();
       }
}

    
    function showMarker(i)
{
    //add a marker for the recommended place
    var point = new GLatLng(searchResults[i].lat, searchResults[i].lng);//was an error here!
     
    var firstIcon = new GIcon(G_DEFAULT_ICON);
    firstIcon.image = "http://www.google.com/mapfiles/markerA.png";
   var secondIcon = new GIcon(G_DEFAULT_ICON);
    secondIcon.image = "http://www.google.com/mapfiles/markerB.png";
   var thirdIcon = new GIcon(G_DEFAULT_ICON);
    thirdIcon.image = "http://www.google.com/mapfiles/markerC.png";
   var fourthIcon = new GIcon(G_DEFAULT_ICON);
    fourthIcon.image = "http://www.google.com/mapfiles/markerD.png";
   
   // Set up our GMarkerOptions object
   
    if (i === 0) {
       
        markerOptions = { icon:firstIcon };
        
    } else if (i == 1) {
    
        markerOptions = { icon:secondIcon };

    } else if (i == 2) {
    
        markerOptions = { icon:thirdIcon };

    } else if (i == 3) {
    
        markerOptions = { icon:fourthIcon };

    }
    var marker = new GMarker(point, markerOptions);
    //introduce market id
    //marker.value = i;
    
    //var marker = new GMarker(point);
    //myMap.setCenter(point);
    myMap.addOverlay(marker);
    marker.show();
    marker.openInfoWindowHtml(searchResults[i].title+"<br>"+searchResults[i].streetAddress+", "+searchResults[i].city);
    marker.bindInfoWindowHtml(searchResults[i].title+"<br>"+searchResults[i].streetAddress+", "+searchResults[i].city);

}
    
var directionsIndexArray = [];

function sortDurations()
{
	directionsIndexArray = [0,1,2,3,4,5,6,7];

	var swaps = 1; // not zero so the loop will run once
	var durationDifferenceArray = [];
	for (i = 0; i<4; i++)
	{
		durationDifferenceArray[i] = Math.abs(durationArray[2*i] - durationArray[(2*i)+1]);
	}
	
		
	while(swaps > 0)
	{
		swaps = 0;
		for(i=1; i<4;i++)
		{
			if(durationDifferenceArray[i-1] > durationDifferenceArray[i])
			{
				// swap these two around
				var temp;
				temp = searchResults[i];
				searchResults[i] = searchResults[i-1];
				searchResults[i-1] = temp;
				
				temp = durationDifferenceArray[i];
				durationDifferenceArray[i] = durationDifferenceArray[i-1];
				durationDifferenceArray[i-1] = temp;
				swaps++;
				// swap the directions around
				//document.getElementById("swapLog").innerHTML+= "Swapping "+ i +" and " + (i-1) + "<br>";
				
				var index1 = i*2;
				var index2 = index1 + 1;
				var index3 = (i-1)*2;
				var index4 = index3 + 1;
				
				temp = directionsIndexArray[index1];
				directionsIndexArray[index1] = directionsIndexArray[index3];
				directionsIndexArray[index3] = temp;
				temp = directionsIndexArray[index2];
				directionsIndexArray[index2] = directionsIndexArray[index4];
				directionsIndexArray[index4] = temp;
				
				//document.getElementById("swapLog").innerHTML+= directionsIndexArray;
				
			}
		}
	}
	document.getElementById("decisionBox").innerHTML="";
	//write a message
	for(i=0; i<4; i++)
	{
		var sychronicityString = "at the same time";
		
		if(durationDifferenceArray[i] < 60)// 0 to 1
		{
			sychronicityString = "at the same time";
		} else if((durationDifferenceArray[i] >= 60)&&(durationDifferenceArray[i] < 120))// 1 to 2
		{
			sychronicityString = "only 2 minutes apart";
		} else if((durationDifferenceArray[i] >= 120)&&(durationDifferenceArray[i] < 300))// 2 to 5
		{
			sychronicityString = "only 5 minutes apart";
		} else if((durationDifferenceArray[i] >= 300)&&(durationDifferenceArray[i] < 600))// 5 to 10
		{
			sychronicityString = "only 10 minutes apart";
		} else if((durationDifferenceArray[i] >= 600)&&(durationDifferenceArray[i] < 900))// 10 to 15
		{
			sychronicityString = "just 15 minutes apart";
		} else if((durationDifferenceArray[i] >= 900)&&(durationDifferenceArray[i] < 1200))// 15 to 20
		{
			sychronicityString = "20 minutes apart";
		} else if((durationDifferenceArray[i] >= 1200)&&(durationDifferenceArray[i] < 1800))// 20 to 30
		{
			sychronicityString = "30 minutes apart";
		} else if((durationDifferenceArray[i] >= 1800)&&(durationDifferenceArray[i] < 2700))// 30 to 45
		{
			sychronicityString = "45 minutes apart";
		} else if((durationDifferenceArray[i] >= 2700)&&(durationDifferenceArray[i] < 3600))// 45 to 60
		{
			sychronicityString = "within an hour of each other";
		} else if (durationDifferenceArray[i] >= 3600)
		{
			sychronicityString = "over an hour apart";
		}
		
		//the browser reads the divs wrong in the following
		
		var timeString = "(If you and your companion set off now, you&#39;ll arrive "+ sychronicityString +")";
		
		document.getElementById("decisionBox").innerHTML += "<div class=\"orderedResults\" id=\"orderedResult"+i+"\"><b>&#" + (i+65) +";<\/b>. "+searchResults[i].title+", "+searchResults[i].streetAddress+", "+searchResults[i].city;
		
		document.getElementById("decisionBox").innerHTML += "<div id=\"sychronicityString\">" + timeString + "<\/div>";
		
		document.getElementById("decisionBox").innerHTML += "<div><a href=\"javascript:showMarker("+i+
		");\">Show on the map<\/a> &#45; <a href=\"javascript:showDirections("+(2*i)+");\">Your Companion&#39;s Directions<\/a> &#45;"+
		"<a href=\"javascript:showDirections("+((2*i)+1)+");\">Your Directions<\/a></div>";
		
		document.getElementById("decisionBox").innerHTML += "</div>";
		}
	
	//add a marker for the recommended place
	showMarker(0);
	document.getElementById('decisionBox').style.display = '';
	var messageString;
	if (
	(document.getElementById('placeSelect').value.charAt(0).toLowerCase() == "a")||
	(document.getElementById('placeSelect').value.charAt(0).toLowerCase() == "e")||
	(document.getElementById('placeSelect').value.charAt(0).toLowerCase() == "i")||
	(document.getElementById('placeSelect').value.charAt(0).toLowerCase() == "o")||
	(document.getElementById('placeSelect').value.charAt(0).toLowerCase() == "u")
	) {
	messageString = "We have found an "+ document.getElementById('placeSelect').value + " <b>inbetwixt<\/b> ";
	} else {
	messageString = "We have found a "+ document.getElementById('placeSelect').value + " <b>inbetwixt<\/b> ";
	}
	
	messageString += document.getElementById('address2').value + " and ";
	messageString += document.getElementById('address1').value;
	document.getElementById('intro-message').innerHTML = messageString;
	
	document.getElementById("top-box-holder").style.height="140px";//+20
	document.getElementById("top-mid-holder").style.height="120px";//+20
	document.getElementById("connecting-edges-holder").style.top="160px";//+20
	document.getElementById("bottom-box-holder").style.top="170px";//+20
	document.getElementById("bottom-box-holder").style.height="340px";//+200
	document.getElementById("bottom-mid-holder").style.height="320px";//+200
	document.getElementById("map-box-holder").style.top="577px";//+220
	document.getElementById("map-box-holder").style.height="510px";//+200
	document.getElementById("map-mid-holder").style.height="490px";//+200
	document.getElementById("mapDiv").style.height="440px";//+200
	document.getElementById("directionsDisplay").style.top="1117px";

}

function calculateInbetwixt(localArrayIndex) {
		var result = searchResults[Math.floor(localArrayIndex/2)];
		if(localArrayIndex%2 === 0)
		{
			//This is an even number
			point = firstPoint;
		}
		else
		{
			point = secondPoint;
		}
		var queryHolder= point.lat()+" "+point.lng()+" to "+parseFloat(result.lat)+" "+parseFloat(result.lng);
		//var queryHolder= point.lat()+" "+point.lng()+" to "+result.streetAddress+", "+result.city+" ,"+result.region;
		var directions_Panel = document.getElementById("directionsDisplay"+localArrayIndex);
		var mydirections = new GDirections("", directions_Panel);
		mydirections.load(queryHolder, {getSteps:true, getPolyline:true});
		GEvent.addListener(mydirections, "load", function (directionObject){
								var ourroute = directionObject.getRoute(0);
								var duration = ourroute.getDuration().seconds;
								polyLineArray[localArrayIndex] = directionObject.getPolyline();
								boundsArray[localArrayIndex] = directionObject.getBounds();
								polyLineArray[localArrayIndex].hide();
								//~~GLog.write("Duration : "+resultTitle+"  "+duration);
								//~~GLog.write("Array Index" + arrayIndex);
								//alert(arrayIndex);
								durationArray[localArrayIndex] = duration;
									if(localArrayIndex >= DURATION_ARRAY_SIZE)
									{
										sortDurations();
									}
								}
		);
                GEvent.addListener(mydirections, "error", erralert);
}

function showDirections(index)
{
	if(currentPolyline < 8)
	{
		myMap.removeOverlay(polyLineArray[currentPolyline]);
	}
	currentPolyline = directionsIndexArray[index];
	showMarker(Math.floor(index/2));
	for(var i=0; i<8; i++)
	{
		document.getElementById("directionsDisplay"+i).style.display = 'none';
	}
	//Zoom out so we can see the directions
	myMap.setZoom(myMap.getBoundsZoomLevel(boundsArray[index]));
	
	document.getElementById("directionsDisplay"+directionsIndexArray[index]).style.display = '';
	myMap.addOverlay(polyLineArray[directionsIndexArray[index]]);
	polyLineArray[directionsIndexArray[index]].show();

	var startIcon = new GIcon(G_DEFAULT_ICON);
	startIcon.image = "http://www.google.com/mapfiles/dd-start.png";
	var markerOptions = { icon:startIcon };
	if((index%2)==0)
	{
		if(secondMarker!=0){ secondMarker.hide();}
		if(firstMarker===0)
		{
			firstMarker = new GMarker(firstPoint, markerOptions);
			myMap.addOverlay(firstMarker);
		}
		firstMarker.show();
	}
	else
	{
		if(firstMarker!=0){ firstMarker.hide();}
		if(secondMarker===0)
		{
			secondMarker = new GMarker(secondPoint, markerOptions);
			myMap.addOverlay(secondMarker);
		}
		secondMarker.show();
	}
   
}

function dealWithSecondPostcode(point)
{
	firstPoint = point;
        usePointFromPostcode(document.getElementById('address2').value, doCalculateInbetwixt);
}

function getInbetwixt()
{
	//~ myMap.clearOverlays();
      //~ //create an adsmanager
      //~ var adsManagerOptions = {
      //~ maxAdsOnMap:10
      //~ };

      //~ //GAdsManager(map,  publisherId,  adsManagerOptions) 
      //~ var adsManager = new GAdsManager(myMap, "pub-0840697478056647", adsManagerOptions);
      //~ adsManager.enable();
      usePointFromPostcode(document.getElementById('address1').value,  dealWithSecondPostcode);
}

function doFirstBox()
{
	document.getElementById('firstBox').style.display = 'none';
	document.getElementById('secondBox').style.display = '';
	document.secondBoxForm.address_2.focus();
	document.getElementById('intro-message').innerHTML = "<p>Let's meet <b>inbetwixt</b> you and "+document.getElementById('address1').value;
	//document.getElementById("ukButton").disabled=true;
	//document.getElementById("usButton").disabled=true;
	//document.getElementById("worldButton").disabled=true;
}
function doSecondBox()
{
	document.getElementById('secondBox').style.display = 'none';
	document.getElementById('thirdBox').style.display = '';
	document.thirdBoxForm.go_Button.focus();
	var messageString = "<p>Let's meet <b>inbetwixt</b> "; 
	messageString += document.getElementById('address2').value + " and ";
	messageString += document.getElementById('address1').value;
	document.getElementById('intro-message').innerHTML = messageString;
	
}
function doThirdBox()
{
	//doLogging(document.getElementById('address1').value, 
		//document.getElementById('address2').value,
			//document.getElementById("placeSelect").value);
	getInbetwixt();

	//document.getElementById("ukButton").disabled=false;
	//document.getElementById("usButton").disabled=false;
	//document.getElementById("worldButton").disabled=false;
	
}
function goAgain()
{
	// clear the map
	document.getElementById('intro-message').innerHTML = "    <span id=\"intro-start\">Let&#39;s meet </span>";
	document.getElementById('intro-message').innerHTML +="<span id=\"intro-logo\"><b>inbetwixt</b>";
	document.getElementById('intro-message').innerHTML +="</span><span id=\"intro-you\"> you </span><span>";
	document.getElementById('intro-message').innerHTML +="and</span><span id=\"intro-your\"> your companion&#39;s </span>";
	document.getElementById('intro-message').innerHTML +="<span id=\"intro-end\">locations.</span>";
                            
	document.getElementById('go-again').style.display = 'none';
	document.getElementById('firstBox').style.display = '';
	document.getElementById('secondBox').style.display = 'none';
	document.getElementById('thirdBox').style.display = 'none';
	document.getElementById("decisionBox").innerHTML = "Loading, please wait.....";
	document.getElementById('decisionBox').style.display = 'none';
	if(myMap!=null)
	{
		myMap.clearOverlays();
	}

	document.getElementById("top-box-holder").style.height="120px";
	document.getElementById("top-mid-holder").style.height="100px";
	document.getElementById("connecting-edges-holder").style.top="140px";
	document.getElementById("bottom-box-holder").style.top="150px";
	document.getElementById("bottom-box-holder").style.height="120px";
	document.getElementById("bottom-mid-holder").style.height="100px";
	document.getElementById("map-box-holder").style.top="337px";
	document.getElementById("map-box-holder").style.height="310px";
	document.getElementById("map-mid-holder").style.height="290px";
	document.getElementById("mapDiv").style.height="240px";
	document.getElementById("directionsDisplay").style.top="687px";

	document.getElementById('region_radios').style.display = '';
	
	// re-initialise everything
	document.getElementById("fromPreviousFlag").innerHTML = "";
	document.getElementById("fromPreviousLat1" ).innerHTML = "";
	document.getElementById("fromPreviousLng1" ).innerHTML = "";
	document.getElementById("fromPreviousLat2" ).innerHTML = "";
	document.getElementById("fromPreviousLng2" ).innerHTML = "";
	document.getElementById("fromPreviousIBTLat" ).innerHTML = "";
	document.getElementById("fromPreviousIBTLng" ).innerHTML = "";
	document.getElementById("fromPreviousPlaces" ).innerHTML = "";
	document.getElementById("fromPreviousregRadios" ).innerHTML = "";
	document.getElementById("fromPreviousAddress1" ).innerHTML = "";
	document.getElementById("fromPreviousAddress2" ).innerHTML = "";
	
	townString="";
	currentPolyLine=999;
	firstMarker=0;
	secondMarker=0;
	//document.getElementById("ukButton").disabled=false;
	//document.getElementById("usButton").disabled=false;
	//document.getElementById("worldButton").disabled=false;
}
function centreUSA()
{
	//myMap.setCenter(new GLatLng(37.0625,-95.677068), 3);
      
}
function centreUK()
{
	//myMap.setCenter(new GLatLng(54.622978,-2.592773), 4);
}
function centreEU()
{
	//myMap.setCenter(new GLatLng(47.398349,25.136719), 3);
}
function centreWW()
{
	//myMap.setCenter(new GLatLng(24.846565,10.195313), 1);
}

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest(); //Not IE
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP"); //IE
	} else {
		//Display your error message here. 
		//and inform the user they might want to upgrade
		//their browser.
		reportAlert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade to Firefox.");
	}
}

//Initiate the asyncronous request.
function doLogging(address1, address2, placeSelect) {
	//If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call.
	//if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
		//Setup the connection as a GET call to SayHello.html.
		//True explicity sets the request to asyncronous (default).
		//receiveReq.open("GET", document.getElementById("filePath").innerHTML+"/logs/log.php?address1="+address1+"&address2="+address2+"&placeType="+placeSelect, true);
		//Set the function that will be called when the XmlHttpRequest objects state changes.
		//receiveReq.onreadystatechange = handleLogging; 
		//Make the actual request.
		//receiveReq.send(null);
	//}			
}

//Called every time our XmlHttpRequest objects state changes.
function handleLogging() {
	//Check to see if the XmlHttpRequests state is finished.
	if (receiveReq.readyState == 4) {
		//document.getElementById("swapLog").innerHTML = receiveReq.responseText;
	}
}

GSearch.setOnLoadCallback(OnLoad);
