var http;
var map;
var gdir;
var geocoder = null;
var addressMarker;
var mouseX = 0;
var mouseY = 0;
// Multibrowser mouse location
if (document.layers) 
{
	// Netscape 
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
}
else if (document.all) 
{ 
	// Internet Explorer
    document.onmousemove = captureMousePosition;
}
else if (document.getElementById) 
{
	// Netscape 6 
    document.onmousemove = captureMousePosition;
}

function captureMousePosition(e) 
{
    if (document.layers)
	{
        mouseX = e.pageX;
        mouseY = e.pageY;
    } 
	else if (document.all) 
	{
		// In case the page hasn't loaded yet
		if (window.event && document.body) 
		{
        	mouseX = window.event.x + document.body.scrollLeft;
        	mouseY = window.event.y + document.body.scrollTop;
        }
    } 
	else if (document.getElementById) 
	{
        mouseX = e.pageX;
        mouseY = e.pageY;
    }
}

function initialize() 
{
	if (GBrowserIsCompatible()) 
	{      
		map = new GMap2(document.getElementById("map_canvas"));
		map.setUIToDefault();
		gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
		
		setDirections(
			defaultStart, defaultStartCountry, 
			defaultTo, 	  defaultToCountry, 
			defaultVia,   defaultViaCountry, 
			"en_GB");
	}

	document.getElementById("fromAddress").value = defaultStart;
	document.getElementById("toAddress").value = defaultTo;
	document.getElementById("viaAddress").value = defaultVia;
}

function setDirections(fromAddress, fromAddressCountry, toAddress, toAddressCountry, viaAddress, viaAddressCountry, locale) 
{
	var directionRequest = "from: " + fromAddress + ", " + fromAddressCountry + " to: " + toAddress + ", " + toAddressCountry;
	if (viaAddress != "")
	{
		directionRequest = "from: " + fromAddress + ", " + fromAddressCountry + " to: " + viaAddress + ", " + viaAddressCountry + " to: " + toAddress + ", " + toAddressCountry;
	}
	gdir.load(directionRequest, { "locale": locale });		
}

function handleErrors()
{
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	{
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	{
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	{
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	{
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	{
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	}
	else 
	{
		alert("An unknown error occurred.");
	}
}

function onGDirectionsLoad()
{ 
	document.getElementById("trip_output").innerHTML = '<br /><br /><img src="images/waiting_image_1.gif" />';
	document.getElementById("trip_output").style.textAlign = 'center';
	
	updateData();
}

function updateData() 
{
	var myurl = "journey_details.php";
	
	var fromAddress = "?fromAddress=" + document.getElementById("fromAddress").value;
	var fromCountry = "&fromCountry=" + document.getElementById("fromCountry").value;
	var toAddress = "&toAddress=" + document.getElementById("toAddress").value;
	var toCountry = "&toCountry=" + document.getElementById("toCountry").value;
	var viaAddress = "&viaAddress=" + document.getElementById("viaAddress").value;
	var viaCountry = "&viaCountry=" + document.getElementById("viaCountry").value;
		
	var consumption = "&consumption=" + document.getElementById("consumption").value;
	var consumptionMethod = "&consumptionMethod=" + document.getElementById("consumptionMethod").value; 
	var fuelCost = "&fuelCost=" + document.getElementById("fuelCost").value;
	var fuelCostCurrency = "&fuelCostCurrency=" + document.getElementById("fuelCostCurrency").value;
	var fuelCostUnit = "&fuelCostUnit=" + document.getElementById("fuelCostUnit").value;
	var meters = "&meters=" + gdir.getDistance().meters; 
	var expenseAmount = "&expenseAmount=" + document.getElementById("expenseAmount").value;
	var expenseMileKm = "&expenseMileKm=" + document.getElementById("expenseMileKm").value;
	var expenseCurrency = "&expenseCurrency=" + document.getElementById("expenseCurrency").value;
	var cacheBuster = "&cacheBuster=" + parseInt(Math.random()*99999999);
	
	var query = fromAddress + fromCountry + toAddress + toCountry + viaAddress + viaCountry; 
	query += consumption + consumptionMethod + fuelCost + fuelCostCurrency + fuelCostUnit + meters + expenseAmount + expenseMileKm + expenseCurrency;
	query += cacheBuster
	
//alert(myurl + query);
	
	http = getHTTPObject();
	http.open("GET", myurl + query, true);
	http.onreadystatechange = useHttpResponse;
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.send(null);
}		

function useHttpResponse() 
{
	if (http.readyState == 4) 
	{
		if (http.status == 200)
		{
			var textout = http.responseText;
			//document.write.textout;
			
			var key = textout.substring(0, textout.indexOf('\n'));
			var message = textout.substring(textout.indexOf('\n') + 1);

			document.getElementById("trip_output").innerHTML = message;		
			document.getElementById("trip_output").style.textAlign = 'left';
			
			document.getElementById("getLink").value = key;
		}
	}
}		

function getHTTPObject() 
{ 
    var req = null;
    if(window.ActiveXObject)
    {
          req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //for Firefox
    else if(window.XMLHttpRequest)
    {
          req = new XMLHttpRequest();
    }
    return req;
}		


function show_help(message)
{
var help_messages = new Array();
help_messages['help_from'] = "\
(Compulsary)<br />\
This is the starting point of your journey. You can specify<br />\
place names, postal/zip codes or in some cases landmarks.<br />\
You must choose the right country from the dropdown box.<br />";

help_messages['help_to'] = "\
(Compulsory)<br />\
This is the end point of your journey. You can specify<br />\
place names, postal/zip codes or in some cases landmarks.<br />\
You must choose the right country from the dropdown box.<br />";

help_messages['help_via'] = "\
(Optional)<br />\
This is the mid point of your journey. You can specify<br />\
place names, postal/zip codes or in some cases landmarks.<br />\
You must choose the right country from the dropdown box.<br />";

help_messages['help_consumption'] = "\
(Compulsory)<br />\
This is the fuel consumption for you car. You can specify<br />\
this in MPG (either Imperial or US) or in L/100km (Litres per<br />\
hundred kilometres<br />\
<br />\
If you are unsure about this then you can try to find your<br />\
car using the search in the \"Make\" section at the bottom<br />\
of the form. If you car isn't listed then we're working on<br />\
a way to add cars in from users. This will come soon.<br />";

help_messages['help_cost'] = "\
(Compulsory)<br />\
This is to say how much you pay for the fuel. Either in gallons<br />\
(Imperial or US) or litres. <br />\
<br />\
You can also set the currency you use to pay. This setting has<br />\
no effect on the calculation but is used in the output of your<br />\
results.<br />";

help_messages['help_expenses'] = "\
(Optional)<br />\
If this is a business trip and you claim expenses or charge a<br />\
customer then you can say what the charge will be.<br />\
<br />\
Simply select the currency (which has no implication on the <br />\
results), then how much you charge. Finally select whether <br />\
this is per mile or per Km<br />";

help_messages['help_make'] = "\
(Optional)<br />\
If you don't know the fuel consumption rate of the vehicle you<br />\
drive then this feature intends to look this up for you.<br />\
<br />\
Type in words and a list of possible cars will appear, simply<br />\
click of the car you wish and it will use this car's fuel<br />\
values.<br />\
<br />\
You can use whole words, if you wish for a word to be forced to<br />\
be included in the results put a + in front of it. If you wish<br />\
for a term to be excluded then put a - in front. To search for<br />\
phrases then enclose the term in quotes.<br />\
<br />\
e.g.<br />\
<br />\
ford +mondeo -petrol \"4 speed\"<br />\
<br />";

	var popHelp = document.getElementById("popHelp"); 
	//alert(mouseX + " - " + mouseY);
	popHelp.style.left = mouseX + "px";
	popHelp.style.top = mouseY + "px";
	popHelp.style.display = "block";
	popHelp.style.visibility = "visible";
	
	if (help_messages[message])
	{
		popHelp.innerHTML = help_messages[message];
	}
	else
	{
		popHelp.innerHTML = "No help available for this item (coming soon). " + message;
	}
}


function hide_help(message)
{
	var popHelp = document.getElementById("popHelp");
	popHelp.style.visibility = "visible";
	popHelp.style.display = "none";
}





