// Animator - class for playing a sequence of images
//
// methods
// ----------------------------------------------------------------------------
// CONSTRUCTOR
// object creation - new Animator(imid,fps, sequence,runtype)
// params:
// imid - string : the id of img tag which will be used for the animation
// fps - integer : the frames per second (1000 = 1 second)
// sequence - array : an array of image urls that will make up the animation
// runtype - boolean : false to play once and stop, true to loop endlessly
//
// START
// starts playing animation - Animator.play()
// params: none
//
// STOP
// stops animation - Animator.stop()
// params: none
// NOTE: stop method gets called automaticaly by _displayNext inner function if
// runtype is set to true and last image has been displayed.

function Animator(imid,fps, sequence, runtype) {
    this.timer = null;
    this.loaded = true;
    this.loadedFrames = 0;
    this.startOnLoad =true;
    this.frameNumber = 0;
    this.frame = null;
    this.pace = fps;
    this.imageid = imid;
    this.flist = sequence;
    this.container = document.getElementById(this.imageid);
    this.endless = runtype;
    var looper = this;
   
   //this gets called by setInteval in start method
   //calls stop method when last image is encountered  if runtype is set to true
    this._displayNext = function() {
        looper.frameNumber = (looper.frameNumber+1)%looper.flist.length;
        looper.container.src = looper.flist[looper.frameNumber].src;
        if((looper.frameNumber >= (looper.flist.length -1)) &&  !looper.endless ){
            looper.stop();
        }
    };
}


Animator.prototype.start = function() {
    //if animation running abort
    if(this.timer != null) return;
    if(!this.loaded) {
        this.startOnLoaded = true;   
    } else {
        if(!this.container) this.container = document.getElementById(this.imageid);
        
        //animate sqeuence by using setInterval to call inner function _displayNext
        this.timer = setInterval(this._displayNext, this.pace);
    }
};

Animator.prototype.stop =  function(){
	if(this.timer) clearInterval(this.timer);
	
	//reset timer to insure proper start
	this.timer= null;
};
