// requires prototype.js
/*
Event.observe(window, 'load', function() {
  var myPlayer = new AnimationPlayer($('productnew'));
  myPlayer.addFrame('http://seagrave.com/images/fdic2010banner01.jpg', 120);
  myPlayer.addFrame('http://seagrave.com/images/fdic2010banner02.jpg', 120);
  myPlayer.stop();
  myPlayer.play();
});
*/

var AnimationPlayer = Class.create({
/*
  AnimationPlayer v1.0 by Juan Carlos Ospina Gonzalez (www.piterwilson.com) Feb 28,2009
  v1.1 update by Juan Carlos Ospina Gonzalez (www.piterwilson.com) march 23,2009
*/
  initialize : function(targetDiv, frames) {
    this.frameImages = new Array();
    this.frameDurations = new Array();
    this.frameRate = 100;
    this.timeOut = null;
    this.currentFrame = 1;
    this.currentImg = null;
    this.targetDiv = targetDiv;
    if (frames != null)
    {
      for (var i = 0; i < frames.length; i++)
      {
        var img = new Element('img', {
          src : frames[i]
        });
        this.frameImages.push(img);
        this.frameDurations.push(this.frameRate);
      }
    }
  },
  addFrame : function(url, timing) {
    var img = new Element('img', {
      src : url
    });
    this.frameImages.push(img);
    if (timing == null)
    {
      this.frameDurations.push(this.frameRate);
    }
    else
    {
      this.frameDurations.push(timing);
    }
//  alert("there are "+this.frameImages.length+" images");
  },
  setSize : function(w, h) {
//  alert("setSize");
    for (var i = 0; i < this.frameImages.length; i++)
    {
      this.frameImages[i].width  = w;
      this.frameImages[i].height = h;
//    alert(this.frameImages);
    }
  },
  setFrameRate : function(duration) {
    for (var i = 0; i < this.frameDurations.length; i++)
    {
      this.frameDurations[i] = duration;
    }
  },
  play : function() {
    if (this.frameImages.length > 0)
    {
      this.goToFrame(this.currentFrame);
      clearTimeout(this.timeOut);
      this.timeOut = setTimeout(this.goToNextFrame.bind(this), this.frameDurations[this.currentFrame - 1]);
    }
  },
  stop : function() {
    if (this.playing)
    {
      this.pause();
      this.gotoFrame(1);
    }
  },
  goToFrame : function(num) {
//  alert("go to frame "+this.currentFrame);
    if (num > 0 && num <= this.frameImages.length)
    {
      this.currentFrame = num;
      this.targetDiv.innerHTML = "";
      this.currentImg = this.frameImages[this.currentFrame - 1];
      this.targetDiv.appendChild(this.currentImg);
    }
  },
  goToNextFrame : function() {
    if (this.currentFrame < (this.frameImages.length))
    {
      this.currentFrame++;
      this.goToFrame(this.currentFrame);
    }
    else
    {
      this.currentFrame = 1;
      this.goToFrame(this.currentFrame);
    }
    this.play();
  },
  pause : function() {
    clearTimeout(this.timeOut);
  }
});

