var Mbsw = { };

Mbsw.Autocompleter = Class.create(Autocompleter.Base, {

  initialize: function($super, element, update, url, context, options) {
    this.baseInitialize(element, update, options);
    this.url     = url;
    this.context = $w(context);
    
    this.element.on('focus', this.mbswOnFocus.bindAsEventListener(this));
  },

  getUpdatedChoices: function() {
    this.startIndicator();
    var ret = $H();
    ret.set($('acfield').name, this.element.id);
    ret.set(this.element.name, this.element.value);
    this.context.each(function(elemId) {
  		ret.set($(elemId).name, $(elemId).value);
    });
    new Ajax.Request(this.url, {
      parameters: ret.toQueryString(),
      asynchronous: true,
      onComplete: this.getUpdatedChoicesCompleted.bind(this)
    });
  },

  getUpdatedChoicesCompleted: function(request) {
    this.updateChoices(request.responseText);
  },

  onObserverEvent: function($super) {
    this.options.minChars = this.options.minCharsIfNoContextDefined;
    this.context.each(function (elemId) {
      if ($(elemId).value) this.options.minChars = 0;
    }.bind(this));
    $super();
  },

  mbswOnFocus: function(event) {
    this.changed = false;
    this.hasFocus = true;
    if (this.observer) clearTimeout(this.observer);
    this.observer = setTimeout(this.onObserverEvent.bind(this), this.options.frequency * 1000);
  }

});

