/* Image Rotator. requires mochikit/packedsignal.js or better
 * (ie - needs MochiKit Base, DOM, Iter, and Signal)
 */

var rlist = {};

rlist.PeriodicCycler = function(items, duration, onrotate) {
  this.duration = duration * 1000;
  this.cycle = MochiKit.Iter.cycle(items);

  this.suspended = false;
  this.stopped = false;
  this.currentlyExecuting = false;
  this.intervalID = null;
  
  MochiKit.Base.bindMethods(this);
  this.onrotate = onrotate || MochiKit.Base.noop;
};

MochiKit.Base.update(rlist.PeriodicCycler.prototype, {
  __repr__: function() {
    var base = ["rlist.PeriodicCycler"];
    if(this.stopped)
      base.push("[STOPPED]");
    else if(this.suspended)
      base.push("[SUSPENDED]");
    return "[" + base.join(" ") + "]";
  },
  toString: function() {return this.__repr__();},
  
  rotate: function() {
    var next = this.cycle.next();
    this.onrotate(next);
  },

  start: function() {
    if(this.currentlyExecuting) return;
    if(this.stopped) return;

    this.intervalID = setInterval(this.onTimerEvent, this.duration);
  },
  
  pause: function() {
    if(this.intervalID != null) {
      clearInterval(this.intervalID);
    }
    this.suspended = true;
  },
  
  resume: function() {
    if(this.suspended)
      this.suspended = false;
    this.start();
  },
  
  stop: function() {
    this.pause();
    this.stopped = true;
  },
  
  restart: function() {
    this.stopped = false;
    this.resume();
  },
  
  onTimerEvent: function() {
    if (!this.currentlyExecuting && !this.suspended) {
      try {
        this.currentlyExecuting = true;
        this.rotate();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});

// TODO: Unify the signatures (and implementations?) of this and 
// `slidefade.makeSlideShow`
rlist.RotateLinked = function(linkelement, duration, images) {
  var m = MochiKit.Base, md = MochiKit.DOM, Signal = MochiKit.Signal;

  var element = md.getElement(linkelement);
  var imageElement = element.getElementsByTagName('img')[0];

  var images = m.extend(null, images);
  images.push({
    'linkURL': element.href,
    'imageURL': imageElement.src
  });

  MochiKit.Iter.forEach(images, function(rec) {
    rec.image = new Image();
    rec.image.src = rec.imageURL;
  });
  
  var cycler = new rlist.PeriodicCycler(images, duration, function(imgrec) {
    element.href = imgrec.linkURL;
    imageElement.src = imgrec.image.src;
  });
  
  Signal.connect(imageElement, 'onmouseover', function(e) {cycler.pause();});
  Signal.connect(imageElement, 'onmouseout', function(e) {cycler.resume();});
  
  cycler.start();
  return cycler;
};

