// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// FIXME: cleaner handling of errors? -- use JSON for errors instead of innerHTML...
// Dynamic valdiation?

var _lookupWindow;

// this handles XHR Requests for when forms in #add_form have been submitted
function handleXhrRequest(request, field_id)
{
  var target;

  // special exception: locations
  if(request.status == 200 && field_id == 'location_id')
  {
    locationLookup.selectLocation(request.responseText);
    hideForm();
    return;
  }

  // if 200, it's okay
  if (request.status == 200)
  {
    target = $(field_id + '_container');
    hideForm();
  }
  else if(request.status == 210)
  {
    // if 210, HTTP request is okay, but there were RoR validation errors
    target = $('add-form');
  }
  else
  {
    // error!
    target = $('add-form');
    request.responseText = '<p>There was an error processing your request.  Please try again shortly...</p>';
  }

  target.innerHTML = request.responseText;
}

// check for id before initiating certain requests
function checkId(field_id)
{
  var a = $F(field_id);
  if(!a || a == "")
  {
    return false;
  }
  else
  {
    return true;
  }
}

// check location search field before doing lookup
function checkLocation(field_id)
{
  var v = $F(field_id);
  if(!v || v == "" || v.length < 3)
  {
    return false;
  }
  else
  {
    return true;
  }
}

// select location
function selectLocation(id)
{
  locationLookup.selectLocation(id);
  // locationLookup is a LocationChooser; it is declared in _form.html.erb
}

// class to handle event location selection
var LocationChooser = Class.create({
initialize: function(lookupFieldId,resultsFieldId,locIdField,locationId)
  {
    if(!locationId)
    {
      locationId = '';
    }

    this.lookupFieldId = lookupFieldId;
    this.resultsFieldId = resultsFieldId;
    this.locIdField = locIdField;

    // show initial event if event is specified
    if(locationId && locationId != '' && !isNaN(locationId))
    {
      this.selectLocation(locationId);
    }

    Event.observe(this.lookupFieldId,'focus',this.start.bindAsEventListener(this));
    Event.observe(this.lookupFieldId,'blur',this.stop.bindAsEventListener(this));
  },

start: function()
  {
    this.lookupValue = $F(this.lookupFieldId);
    this.timer = setInterval(this.doLookup.bindAsEventListener(this),2000);
  },

stop: function()
  {
    clearInterval(this.timer);
  },

doLookup: function()
  {
    // do not do look up if field has not changed
    if($F(this.lookupFieldId) == this.lookupValue)
    {
      return;
    }

    // clear results if doing new lookup
    this.clearResults();

    this.lookupValue = $F(this.lookupFieldId);

    // don't do lookup unless the length is at least 3
    if(!this.lookupValue || this.lookupValue == "" || this.lookupValue.length < 3)
    {
      return;
    }

    var url = '/locations/lookup?q=' + encodeURIComponent(this.lookupValue);
    new Ajax.Request(url,
      {
        method : 'get',
        onSuccess : this.showResults.bindAsEventListener(this)
      }
    );
  },

showResults: function(response)
  {
    $(this.resultsFieldId).innerHTML = response.responseText;
  },

clearResults: function()
  {
    $(this.resultsFieldId).innerHTML = '';
  },

selectLocation: function(id)
  {
    $(this.locIdField).value = id;
    var url = '/locations/lookup?id=' + encodeURIComponent(id);
    new Ajax.Request(url,
      {
        method : 'get',
        onSuccess : this.showSelected.bindAsEventListener(this)
      }
    );
  },

showSelected: function(response)
  {
    $(this.lookupFieldId).style.display = 'none';
    $(this.lookupFieldId).value = '';

    html = '<div class="lookup-item selected"><p>' + response.responseText + '</p><p class="alt-link" id="lookup-alt-link"><a>[pick another location]</a></div>';

    $(this.resultsFieldId).innerHTML = html;
    Event.observe('lookup-alt-link','click',this.cancelSelected.bindAsEventListener(this))
  },

cancelSelected: function()
  {
    // removes the selected location id and shows search field again
    $(this.locIdField).value = '';
    $(this.lookupFieldId).style.display = 'block';
    $(this.resultsFieldId).innerHTML = '';
  }

})

function showForm(request)
{
  $('add-form').innerHTML = request.responseText;
  $('add-form-container').style.display = 'block';
}

function hideForm()
{
  $('add-form').innerHTML = "";
  $('add-form-container').style.display = 'none';
}

// geocoding - for locations forms only

// link user to Google Maps to look up street address
function lookupAddress()
{
  var base = 'http://maps.google.com/maps?q=';
  var d = Form.serialize('add-form',true);

  // do not proceed if no location is entered
  if(d['location[location]'] == "" || d['location[city]'] == "" || d['location[state]'] == "")
  {
    alert('Please enter a location, city, and state first.');
    return;
  }
  else
  {
    var q = d['location[location]'];

    if(d['location[city]'] != "")
    {
      q += ", " + d['location[city]']
    }

    if(d['location[state]'] != "")
    {
      q += ", " + d['location[state]'];
    }
  }
  var url = base + encodeURIComponent(q);
  openGMapWindow(url);
}

function checkLatLng()
{
  var lat = $F('location_latitude');
  var lng = $F('location_longitude');

  if(lat == "" || lng == "")
  {
    alert("Please enter the latitude and longitude before doing this check.");
    return;
  }

  var base = 'http://maps.google.com/maps?q=';
  var q = lat + "," + lng;
  url = base + encodeURIComponent(q);
  openGMapWindow(url);
}

function openGMapWindow(url)
{
  _lookupWindow = window.open(url, "lookupWindow",'resizable,scrollbars');
  _lookupWindow.focus();
}

// get geocoding information
function getGeocode()
{
  var base = '/locations/geocode/'; // this action uses the Google Maps HTTP Geocoder to get geocoding

  /*
  $('location_address_line1').value = $('location_address_line1').value.replace(ex,"");
  $('location_city').value = $('location_city').value.replace(ex,"");
  $('location_state').value = $('location_state').value.replace(ex,"");
  */

  // then serialize the form
  var d = Form.serialize('add-form', true);

  // must have address, city, and state to do geocode lookup
  if(d['location[address_line1'] == '' || d['location[city]'] == '' || d['location[state]'] == '')
  {
    alert('You must enter an address and the city and state to do this lookup.');
    return;
  }

  // strip periods from the address fields; they cause errors with the backend action
  var ex = /\./g;
  var address_line1 = d['location[address_line1]'].replace(ex,"");
  var city = d['location[city]'].replace(ex,"");
  var state = d['location[state]'].replace(ex,"");


  var q = encodeURIComponent(address_line1 + ", " + city + ", " + state);
  var url = base + q;

  new Ajax.Request(url,
    {
      method : 'get',
      onSuccess : function(transport)
        {
          addGeocodeInfo(transport.responseJSON);
        }
    }
  );
}

function addGeocodeInfo(response)
{
  // response is JSON

  if(!response || response.Status.code != 200)
  {
    alert('Could not find the address specified.');
    return false;
  }
  else if(response.Placemark[0].AddressDetails.Accuracy < 7)
  {
    // 7 is street intersection level accuracy.  Anything less should not be used here.
    alert('The results returned were not accurate enough to use.  Please try again with the full address.');
    return;
  }

  var place = response.Placemark[0];


  var localPlace;
  if(place.AddressDetails.Country.AdministrativeArea.Locality != null)
  {
    localPlace = place.AddressDetails.Country.AdministrativeArea.Locality;
  }
  else if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null)
  {
    localPlace = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality;
  }

  if(localPlace.PostalCode != null) // not all responses will return a zip code
  {
    $('location_zip_code').value = localPlace.PostalCode.PostalCodeNumber;
  }

  $('location_latitude').value = place.Point.coordinates[1];
  $('location_longitude').value = place.Point.coordinates[0];
}

function toggleLocationForm(status)
{
  if(!status)
  {
    status = '';
  }

  btn = $('location_submit_button');
  txt = $('location_submit_message')

  if (btn.disabled == true)
  {
    btn.disabled = false;
    if (status == 'error')
    {
      txt.innerHTML = 'An error occurred - please try again.';
    }
    else
    {
    txt.innerHTML = '';
    }
  }
  else
  {
    btn.disabled = true;
    txt.innerHTML = 'Loading...';
  }
}
