var ImageLoader = Class.create({
  initialize: function(elements, callback) {
    var that = this;

    this.callback = callback;
    this.images = [];
    this.pending = 0;

    if (typeof elements === 'string') {
      elements = $$(elements);
    }

    elements.each(function(element, index) {
      var image = new Image;

      that.images.push(image);
      that.pending++;
      image.onload = that.checkCompleted.bindAsEventListener(that);

      if (element.src) {
        image.src = element.src;
      }
      else if (element.href) {
        image.src = element.href;
      }
      else {
        throw 'Need to provide elements to load as images.';
      }
    });
  },

  checkCompleted: function(event) {
    this.pending--;

    if (!this.callback) {
      return;
    }

    // Checking for images.complete breaks on IE6 as it repeatedly returns
    // false, even for the image actually triggering the event.
    if (this.pending === 0 || this.images.all(function(image) {
      return image.complete;
    })) {
      this.callback();
      this.callback = null;
    }
  }
});
