var geocoder = new google.maps.Geocoder();
var nearest_slug = '';
var nearest_distance = 10000;
var latlon = 0;

function getBaseAddress() {
    var address = $('postal_code').value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        latlon = new LatLon(results[0].geometry.location.lat(), results[0].geometry.location.lng());
        getNearestLocation();
        window.location = nearest_slug.replace(' ', '-').toLowerCase()+'/?my_postal_code=' + $('postal_code').value.replace(' ', '-').toLowerCase();
      } else {
        alert(general_postalcode_error_message);
      }
    });
}
function getNearestLocation(){
    for(var i = 0; i < gm_addresses.length; i++)
    {
        var point = {_lat:gm_addresses[i].lat, _lon:gm_addresses[i].lng};
        var d = latlon.distanceTo(point);
        if (parseFloat(d) < parseFloat(nearest_distance)) {
            nearest_distance = d;
            nearest_slug = gm_addresses[i].slug;
        }
    }
}

window.addEvent('domready', function() {

  var postal_code_default = $('postal_code').value;
  var validation_message = general_postalcode_error_message;//($(document.body).hasClass('nl'))?'Voer een postcode in!':'Please fill in a postcode';
    $('postal_code').addEvent('focus', function()
    {
        if ($('postal_code').value == postal_code_default)
        {
            $('postal_code').set('value', '');
        }
    });
    $('postal_code').addEvent('blur', function()
    {
        if ($('postal_code').value == '')
        {
            $('postal_code').set('value', postal_code_default);
        }
    });
    $('id_nearest_location').addEvent('submit', function(el)
    {
        el.stop();
        if ($('postal_code').value == postal_code_default || $('postal_code').value == '')
        {
            alert(validation_message);
        } else {
            getBaseAddress();
        }
    });


});


