/* 
 * The NZOS.Autocompleter simply overrides the some of the functionality
 * of the Scriptaculous autocompleter
 * 
 */

var NZOS = {}
NZOS.Autocompleter = Class.create();
Object.extend(Object.extend(NZOS.Autocompleter.prototype, Ajax.Autocompleter.prototype), {
  
  /* pass through relevant form, so that we can submit() it later on */
  initialize: function(element, update, url, options, formId) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
    this.form                  = $(formId);    
  },
  
  /* allows form submission when enter key is pressed*/
  selectEntry: function() {
    
    this.active = false;
    try {
        this.updateElement(this.getCurrentEntry());
    } catch (err) {
        //do nothing
    }

    this.form.submit();
  },

	/* We override this function so we can comment out the scrollIntoView line, which causes jerking and other issues*/
  markPrevious: function() {
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
    // this.getEntry(this.index).scrollIntoView(true);
  },
  
  /* don't automatically select first suggestion */
  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());      
      if(this.update.firstChild && this.update.down().childNodes) {       
        this.entryCount = 
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else { 
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = -1;
      
      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  }
});
  
