/* loads a script file from the server and then executes the callback function */
function $with_script(src, fn) {
  new Ajax.Request(src, {
    onSuccess: function(){
      setTimeout(function(){ fn() }, 5000);
    },
    method: 'get'
  })
}

Form.Element.AfterActivity = function(element, callback, delay) {
  element = $(element);
  if (!delay) delay = 0.5;
  new Form.Element.Observer(element, delay, function(element, value) {
    // TODO: display loading indicator
    if (element.activity_timer) clearTimeout(element.activity_timer);
    element.activity_timer = setTimeout(function() {
      callback(element.value);
    }, delay * 1000 + 50);
  });
}

/**
 * Note: attaches itself to the counted element, so you can manually
 * call $(element).counter.update() if desired.
 */
Form.Element.LengthCounter = Class.create();
Form.Element.LengthCounter.prototype = {
  element: null,
  container: null,
  hide_when_empty: false,
  hidden: true,
  current: 0,

  initialize: function(element, container, hide_when_empty) {
    this.element = $(element);
    this.container = $(container);
    this.counter = this.container.down('.remaining');
    this.hide_when_empty = hide_when_empty;
    this.element.counter = this;

    new PeriodicalExecuter(this.update.bind(this), 0.5);
  },

  update: function() {
    var length = this.element.value.length;
    if (length != this.current) {
      this.counter.innerHTML = (this.element.getAttribute('maxlength') - length);
      this.current = length;
    }
    if (this.hide_when_empty) {
      if (this.element.value.length > 0) {
        if (this.hidden) this.container.show();
        this.hidden = false;
      } else {
        if (!this.hidden) this.container.hide();
        this.hidden = true;
      }
    }
  }
}
