var Qiro = Class.create();
// jQuery integration
var j$ = jQuery.noConflict();
var $j = jQuery.noConflict();

// AUTOCOMPLETER
Qiro.Autocompleter = Class.create();
Qiro.Autocompleter.User = Class.create();
Object.extend(Object.extend(Qiro.Autocompleter.User.prototype, Ajax.Autocompleter.prototype), {

  initialize: function(element, options) {
    this.baseInitialize(element, this.renderCompletion(element), options);
    this.options.method        = 'get';
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = "/users/autocomplete/nick";
  },

  getUpdatedChoices: function() {

    this.startIndicator();

    if(this.options.defaultParams) {
      this.options.parameters += '&' + this.options.defaultParams;
    }

    var url = this.url;

    if (this.getToken() != null) {
      url = url + "/" + encodeURIComponent(this.getToken());
    }

    new Ajax.Request(url, this.options);

  },

  onComplete: function(request) {

    var list = "<ul>";
    var size = this.options.size || "tiny";

    eval(request.responseText).each(function(nick) {
      list = list + "<li>";
      list = list + "<img src='/users/" + nick + "/avatars/" + size + ".png'/>";
      list = list + nick.escapeHTML();
      list = list + "</li>";
    });

    list = list + "</ul>";

    this.updateChoices(list);

  },

  renderCompletion: function(element) {
    var autocompletion = new Element('div', { 'class': 'autocomplete user' });
    $(element).insert({ after: autocompletion });
    return autocompletion;
  }

});
