/*** OBSERVERS ***/

function AddAddress_OnClick()
{
  address = $('NewAddress').value;
  
  if (address.length > 0)
  {
    TheMap.geocodeAddress(address, AddGeoLocation);    
  }
  else
  {
    new Effect.Highlight('NewAddress',{startcolor:'#ff5555', endcolor:'#ffffff'});
  }
  
  $('NewAddress').value = '';
  $('NewAddress').focus();  
}

function NewAddress_OnKeyUp(e)
{
  if (e.keyCode == 13)
  {
    AddAddress_OnClick();
  }
}

function SubmitAddresses_OnClick(e)
{
  $('new_map').submit();
}

/*** HELPERS ***/

var NumberAddresses = 0;

function AddGeoLocation(GLatLng)
{
  if (GLatLng)
  {
    lat = GLatLng.lat();
    lng = GLatLng.lng();

    NumberAddresses += 1;

    var add = TheMap.addAddressPoint(lat, lng, address);
    var id = add.id;
    TheMap.removeMarkers();
    TheMap.plotAddressPoints();

    new Effect.Highlight('NewAddress');

    new Insertion.Bottom('FormHelpers','<input type="hidden" id="address_point_search_query_'+id+'" name="address_point[][search_query]" value="' + address + '" />');  
    new Insertion.Bottom('FormHelpers','<input type="hidden" id="address_point_latitude_'+id+'" name="address_point[][latitude]" value="' + lat + '" />');  
    new Insertion.Bottom('FormHelpers','<input type="hidden" id="address_point_longitude_'+id+'" name="address_point[][longitude]" value="' + lng + '" />');

    if (NumberAddresses == 1)
    {
      $('NewAddress').morph('width:70%;',{queue:'end'});  
      new Effect.Appear('OneMoreAddress', {queue:'end', afterFinish:function(){if (NumberAddresses>1)$("OneMoreAddress").hide()}});  
    }
    else if (NumberAddresses == 2)
    {
      $('OneMoreAddress').hide();
      new Effect.Appear('SubmitAddresses', {queue:'end'});
      TheMap.calculateMidpoint();
      ChangeMidpoint();  
    }
    else
    {
      TheMap.calculateMidpoint();  
      ChangeMidpoint();
    }

    TheMap.zoomBounds();  
  }
  else
  {
    new Effect.Highlight('NewAddress',{startcolor:'#ff5555', endcolor:'#ffffff'});
    $('NewAddress').value = '';
  }
}

function ChangeMidpoint()
{
  $('midpoint_latitude').value = TheMap.midpoint.lat();
  $('midpoint_longitude').value = TheMap.midpoint.lng();  
}

document.observe("map:midpoint:dragend", ChangeMidpoint);

document.observe("map:addresspoint:remove", function(evt) {
  var addressPoint = evt.memo;
  var id = addressPoint.id;

  $("address_point_search_query_"+id).remove();
  $("address_point_latitude_"+id).remove();
  $("address_point_longitude_"+id).remove();

  TheMap.removeMarkers();
  TheMap.plotAddressPoints();
  if (TheMap.addressPoints.length < 2) {
    TheMap.removeMidpoint();
  }
  else {
    TheMap.calculateMidpoint();
  }
  TheMap.zoomBounds();
  ChangeMidpoint();
});