Event.observe(window, 'load', init);

function init() {
  if ($('get_coordinates_button')) {
    Event.observe('get_coordinates_button', 'click', function(event) {
      get_coordinates($F('location_street_address') + ', ' + $F('location_city') + ', ' + $F('location_state'), populate_coordinates);
    });
  }

  if ($('dropoff_search_form')) {
    Event.observe('dropoff_search_form', 'submit', function(event) {
      Event.stop(event);
      get_coordinates($F('address'), search_form);
    });
  }
}


function search_form(locations) {
  $('dropoff_search_results').innerHTML = '<p><strong>Searching...</strong></p>';
  if (locations.Status.code == 200) {
    new Ajax.Updater('dropoff_search_results', '/dropoff_locations/closest_locations?longitude=' + locations.Placemark[0].Point.coordinates[0] + '&latitude=' + locations.Placemark[0].Point.coordinates[1] + '&' + $('dropoff_search_form').serialize(), {asynchronous:true, evalScripts:true});
  } else {
  $('dropoff_search_results').innerHTML = 'Could not translate the City and State or ZIP Code. Please try again.';
  }
}


function get_coordinates(address, callback) {
  var geocoder = new GClientGeocoder();
  geocoder.getLocations(address, callback);
}

function populate_coordinates(locations) {
  $('location_latitude').value = locations.Placemark[0].Point.coordinates[1];
  $('location_longitude').value = locations.Placemark[0].Point.coordinates[0];
}
