function geoCodeError(field, location)
{
  var msgWin = document.getElementById("messages");
  msgWin.style.visibility = "visible";
  msgWin.innerHTML = "<div style = \"font-weight: bold; font-size: 18px; text-align: center; padding-bottom: 5px;\">"+field+" Location Error!</div>";
  msgWin.innerHTML+= "The location you entered in the <span style = \"font-style: italic;\">"+field+"</span> field, <span style = \"font-weight: bold;\">\""+location+"\"</span> could not be found.<br /><br />Please check for spelling and typing errors and try again.";
  msgWin.innerHTML+= "<div style = \"text-align: center;\"><input type = \"button\" value = \"OK\" style = \"width: 60px;\" onclick = \"document.getElementById('messages').style.visibility = 'hidden';\" /></div>";

}

function getCost()
  {
      // check to make sure a car has been selected
      if(document.getElementById("car").value < 0)
      {
          alert("Please select your car.");
          return;
      }



      // get the from and to locations from the form
      var from = document.getElementById("from").value;
      var to = document.getElementById("to").value;

      // make sure the from and to addresses have been entered
      if(from == "" || from == " " || to == "" || to == " ")
      {
          alert("Please enter your starting and finishing locations.");
          return;
      }


      // get the urban fuel economy ratin
      var urban = document.getElementById("urban").value;

      // get the extra urban fuel economy rating
      var extra = document.getElementById("extra").value;

      // get the cost of fuel
      var fuel = document.getElementById("fuel").value;

      // make sure a fuel cost has been entered and is a positive number
      if(isNaN(fuel) || fuel < 0)
      {
          alert("Please enter a positive number for the fuel cost");
          return;
      }
      
      // -------------- LOADING SCREEN ---------------------- //
      var msgWin = document.getElementById("messages");
      msgWin.style.visibility = "visible";
      msgWin.innerHTML = "<div style = \"font-weight: bold; font-size: 18px; text-align: center; height: 80px; padding-top: 60px;\">Calculating Trip Cost...</div>";

                  
      // define a div to display the journey steps in
      panel = document.getElementById("dirList");
      
      // create a directions object
      var direct = new GDirections(map, panel);
      
      // geocode to and from
      var fromGeoCode = new GClientGeocoder();
      var toGeoCode = new GClientGeocoder();

      fromGeoCode.getLatLng(from, function(fromLatLng)
      {
        if(fromLatLng == null) geoCodeError("From", from);
        else toGeoCode.getLatLng(to, function(toLatLng)
        {
          if(toLatLng == null) geoCodeError("To", to);
          // load the start and end points into the directions object
          direct.load(fromLatLng.lat() + ', ' + fromLatLng.lng() + ' to ' + toLatLng.lat() + ', ' + toLatLng.lng());//, { "avoidHighways": true });
        });
      });
      
      // on error handler called when the directions object encounters and error
      GEvent.addListener(direct, "error", function()
      {
          var code = direct.getStatus().code;

          switch(code)
          {
              case 602: // G_GEO_UNKOWN_ADDRESS
              alert("The address you entered could not be found, this maybe because it is too vague, please try again.");
              break;
          }
      });


      // on load handler, called once the directions object has finished mapping the route and displayed it
      GEvent.addListener(direct, "load", function()
      {

          // remove any existing point, lines or windows on the map
          map.clearOverlays();
          
          // clear directions panel
          document.getElementById("dirList").innerHTML = "";
          
          // move directions panel
          panel.style.visibility = "visible";
          panel.style.position = "absolute";
          panel.style.top = "50px";
          panel.style.left = "280px";
          resize();

          var xmlHttp = ajaxStart();

          xmlHttp.onreadystatechange=function()
          {
              if(xmlHttp.readyState==4)
              {
                  // trip cost calculated - hide loading window
                  msgWin.style.visibility = "hidden";

                  
                  eval(xmlHttp.responseText);
                  var totalCost = totalFuel * (fuel / 100);
                  var totalDist = direct.getDistance().meters;
                  var totalMiles = totalDist * 0.000621371192;
                  var milesPerPound = totalMiles / totalCost;
                  var totalTime = (direct.getDuration().seconds) / 60;
                  var pencePerMin = (totalCost / totalTime) * 100;

                  if(saving > 0) var maxSaving = totalCost - (totalCost / saving);
                  else if(saving == 0) var maxSaving = totalCost;

                  var details = document.getElementById("details");
                  details.style.top = "50px";
                  details.style.left = "280px";
                  details.style.visibility = "visible";
                  var detailsHTML = "<div id = \"detailsTitle\" style =\"\">Jouney Details</div>";
                  detailsHTML += "<table id = \"detailsTab\"><tr id = \"costRow\"><td>Journey Cost:</td><td><span>£"+totalCost.toFixed(2)+"</span></td></tr>";
                  detailsHTML += "<tr id = \"tipRow\"><td colspan = \"2\"><div>Fuel-saving tip: <a href = \"tips.php\">[more tips]</a></div>"+tip;
                  if(saving > -1) detailsHTML +="<div class = \"maxSaving\">This tip could save you <span>£"+maxSaving.toFixed(2)+"</span> on this journey";
                  detailsHTML +="</td></tr>";
                  detailsHTML += "<tr id = \"othersTitle\"><td colspan = \"2\">Other Journey Statistics</td></tr>";
                  detailsHTML += "<tr class = \"detailsRow\"><td>Fuel Used:</td><td>"+totalFuel.toFixed(2)+" litres</td></tr>";
                  detailsHTML += "<tr class = \"detailsRow\"><td>Miles per Pound(£):</td><td>"+milesPerPound.toFixed(2)+"</td></tr>";
                  detailsHTML += "<tr class = \"detailsRow\"><td>Pence per Minute:</td><td>"+pencePerMin.toFixed(0)+"p</td></tr></table>";
                  details.innerHTML = detailsHTML; //"Estimated fuel used: "+totalFuel.toFixed(2)+" litres<br />Estimated Cost: £"+totalCost.toFixed(2);


              }
          }

          /*    INFO TO SEND TO CALCULATION SCRIPT    */
          // urban fuel economy rating
          // extra urban fuel economy rating
          // number of journey steps
          // distance of each step
          // time of each step

          // _GET info string
          var get = "";

          // update _GET string
          get+= "?urban="+urban+"&extra="+extra;

          // retrieve the route object from the directions object
          var route = direct.getRoute(0);

          // get the number of steps for the route
          var stepCount = route.getNumSteps();

          // add stepCount to the _GET string
          get+= "&stepCount="+stepCount;

          // loop through each step of the journey and add the distance and time of
          // each step to the _GET string
          for(var i = 0; i < stepCount; i++)
          {
              var sDist = route.getStep(i).getDistance().meters;
              var sTime = route.getStep(i).getDuration().seconds;

              get+= "&dist"+i+"="+sDist+"&time"+i+"="+sTime;
          }

          // send info to server side calculator
          xmlHttp.open("GET","getCost.php"+get,true);
          xmlHttp.send(null);

      });
    }