var Imagr = Class.create({
  initialize: function(elem) {
    this.elem = elem;
    this.previous = 0;
    this.current = 0;
    this.images = elem.select('img');

    // Don't continue if there are no images.
    if (this.images.length == 0) return;

    // Make sure elem has a height as images are floated.
    this.elem.insert('<div class="clear"></div>')

    this.container = elem.wrap('div', { 'class': 'imagr-container' });

    // Copy other classNames to the container.
    var className = elem.className.sub(/\bimagr\b/, '').strip();
    if (!className.blank()) this.container.addClassName(className);

    // Add dot container.
    this.container.insert('<div class="dots"></div>');
    var dot_container = this.container.down('.dots');

    // Add image cycling functionality.
    this.images.each(function(img, i) {
      img.observe('click', this.cycle.bind(this, i));
      dot_container.insert('<span class="dot"></span>');
    }.bind(this));

    // Make dots clickable.
    this.dots = dot_container.select('.dot');
    this.dots.each(function(dot, i) {
      dot.observe('click', this.select.bind(this, i));
    }.bind(this));
    this.dots.first().addClassName('selected');
  },

  cycle: function(index) {
    this.previous = this.current;
    this.current = (index == this.images.length - 1 ? 0 : index + 1);
    this.show(this.current);
  },

  select: function(index) {
    this.previous = this.current;
    this.current = index;
    this.show(index);
  },

  show: function(index) {
    this.dots[this.previous].removeClassName('selected');
    this.dots[index].addClassName('selected');
    var elem = this.images[index];
    var x = elem.positionedOffset()[0];
    var myEffect = new Effect.Move(this.elem, {
      duration: 0.3, mode: 'absolute', x: -x
    });
  }
});
