/* animation.js -- simple javascript-based animations.
   by Evan Martin <martine@danga.com>
   http://neugierig.org/software/javascript/animation

The author disclaims copyright to this source code.  In place of
a legal notice, here is a blessing:
  May you do good and not evil.
  May you find forgiveness for yourself and forgive others.
  May you share freely, never taking more than you give.

ChangeLog:
2005-07-08  Safari fix (thanks Mihai!).
2005-07-05  Initial release.

*/

// man, javascript's closures suck so much
function MethodClosure(f, method, arg) {
  return function() { f[method](arg); };
}

function Animation(args) {
  if (args.target) {
    this.target   = args.target;
  } else {
    this.target   = document.getElementById(args.targetId);
  }
  this.imageBase  = args.imageBase;
  this.imageExt   = args.imageExt;
  this.imageCount = args.imageCount;
  this.frameDelay =
    (typeof(args.frameDelay) != 'undefined') ? args.frameDelay : 200;

  this.loadedCount = 0;
  this.curImage = 0;

  // start the images preloading
  for (var i = 0; i < this.imageCount; ++i) {
    var img = document.createElement('img');
    img.src = this.imageBase + i + this.imageExt;
    img.onload = MethodClosure(this, 'OnLoaded');
  }
  this.loadedCount = args.imageCount;
  this.OnLoaded();
}

Animation.prototype.OnLoaded = function() {
  if (++this.loadedCount < this.imageCount) {
    this.UpdateDisplay();
  } else {
    this.target.innerHTML = '';
    this.image = document.createElement('img');
    this.target.appendChild(this.image);
    this.StepAnimation(0);
  }
}

Animation.prototype.UpdateDisplay = function() {
  this.target.innerHTML =
    "<br/>Loading images... (" + this.loadedCount + "/" + this.imageCount + ")";
}

Animation.prototype.StepAnimation = function(i) {
  this.image.src = this.imageBase + i + this.imageExt;
  setTimeout(MethodClosure(this, 'StepAnimation', (i+1) % this.imageCount),
             this.frameDelay);
}

