var MiniSlideshow = Class.create();
MiniSlideshow.prototype = {
  images: [],
  paused: false,
  timeout_id: 0,
  last_index: -1,
  initialize: function(prefix, controls, container, name) {
    this.prefix = prefix;
    this.controls = controls;
    this.container = container;
    this.name = name;
  },
  add: function(slide) {
    var img = new Image();
    img.src = slide;
    this.images.push(slide);
  },
  setup: function() {
//    $(this.container).style.height = Element.getHeight($(this.container)) + "px";
    this.length = this.images.length;
    for (var i=0; i<this.length; i++) {
      $(this.prefix + i).style.position = 'absolute';
//		$(this.prefix + i).setStyle({
//			'position': 'absolute'
//		});
      $(this.prefix + i).clonePosition(this.container, { setWidth:false, setHeight:false });
    }
		
		if (this.length > 1) {
	    var html = '<li id="prev"><a href="#" onclick="' + this.name + '.slide(-1);return false;">Previous</a></li><li id="pause"><a href="#" onclick="' + this.name + '.pause();return false;">Pause</a></li><li id="next"><a href="#" onclick="' + this.name + '.slide(1);return false;">Next</a></li>';
	    this.index = 0;
	    new Insertion.Top(this.controls, html);
			this.timeout_id = setTimeout(this.advance.bind(this), 5000);
		}
  },
  slide: function(dir) {
    if (this.paused && this.timeout_id != 0) {
      clearTimeout(this.timeout_id);
      this.timeout_id = 0;
    } else {
      if (this.last_index >= 0) {
        this.last_fade.cancel();
        this.last_appear.cancel();
        Element.hide(this.prefix + this.last_index);
      }
      this.last_index = this.index;
      var old_d = this.prefix + this.index;
      this.index = ( this.index + this.images.length + dir ) % this.images.length;
      var new_d = this.prefix + this.index;
      this.last_fade = Effect.Fade(old_d);
      this.last_appear = Effect.Appear(new_d);
	  $(new_d).setStyle({
			'top': '0px',
			'left': '0px'
		});
      if (this.timeout_id != 0) {
        clearTimeout(this.timeout_id);
        this.timeout_id = 0;
      }
      if (!this.paused) this.timeout_id = setTimeout(this.advance.bind(this), 5000);
    }
  },
  pause: function() {
    Element.addClassName("pause", "play");
    $("pause").innerHTML = '<a href="#" onclick="' + this.name + '.play();return false;">Play</a>';
    this.paused = true; 
    clearTimeout(this.timeout_id);
    this.timeout_id = 0;
  },
  play: function() {
    Element.removeClassName("pause", "play");
    $("pause").innerHTML = '<a href="#" onclick="' + this.name + '.pause();return false;">Pause</a>';
    this.paused = false;
    this.slide(1);
  },
  advance: function() {
    this.timeout_id = 0
    this.slide(1);
  }
}
