$(document).ready(function() {
  $(".autocomplete").locationAutocomplete();
});

jQuery.fn.locationAutocomplete = function(type) {
  var type = type || 'all';
  var x_offset = true;
  return jQuery.each(this,function() {
    if($(this).attr('class').indexOf('neighbourhood')!=-1) type = 'neighbourhood';
    if($(this).attr('class').indexOf('street')!=-1) type = 'street';
    if($(this).attr('id').indexOf('from')!=-1) x_offset = false;

    $(this).autocomplete('/locations/search',
      { delay:400, minChars:2, matchContains:1, xOffset:x_offset, extraParams:{'type':type} }
    );

    // cancel the enter button from submitting the form when autocomplete is in use.
    $(this).keypress(function(key) {
      if($('.ac_results:visible').length && (key.which==23||key.which==13)) {
        // set a timeout so that focus gets handed back to the input field
        var completeField = $(this);
        setTimeout(function() { completeField.focus()},100);
        return false;
      }
    });
  });
};