// main.js (c) Copyright 5/1/2008 Carl Gorringe, www.gotalift.com
var geocoder, from_ready, to_ready;

function updateFrom(response) {
  if (!response || response.Status.code != 200) {
  //    alert("\"" + address + "\" not found");
  }
  else {
    var place = response.Placemark[0];
    document.frm.f.value = place.address;
    document.frm.flat.value = place.Point.coordinates[1];
    document.frm.flon.value = place.Point.coordinates[0];
    from_ready = true;
  }
}
function updateTo(response) {
  if (!response || response.Status.code != 200) {
  //    alert("\"" + address + "\" not found");
  }
  else {
    var place = response.Placemark[0];
    document.frm.t.value = place.address;
    document.frm.tlat.value = place.Point.coordinates[1];
    document.frm.tlon.value = place.Point.coordinates[0];
    to_ready = true;
  }
}

function lookupFrom() {
  var from_addr = document.frm.f.value;
  document.frm.flat.value = '';
  document.frm.flon.value = '';
  geocoder.getLocations(from_addr, updateFrom);
}
function lookupTo() {
  var to_addr = document.frm.t.value;
  document.frm.tlat.value = '';
  document.frm.tlon.value = '';
  geocoder.getLocations(to_addr, updateTo);
}

function submitEvenLater() {
  document.frm.submit();
}
function submitLater() {
  if (!from_ready || !to_ready) {
    setTimeout("submitEvenLater()", 1000);
  }
  else {
    document.frm.submit();
  }
}
function submitForm() {
  if (document.frm.flat.value == "") {
    from_ready = false;
    lookupFrom();
  }
  if (document.frm.tlat.value == "") {
    to_ready = false;
    lookupTo();
  }
  if (!from_ready || !to_ready) {
    setTimeout("submitLater()", 750);
    return false;
  }
  return true;
}

function initMain() {
  geocoder = new GClientGeocoder();
  // geocoder.setBaseCountryCode("us");
  document.frm.f.onchange = lookupFrom;
  document.frm.t.onchange = lookupTo;
  document.frm.onsubmit = submitForm;
}
