/*
	JavaScript animator class V1.1
	Self-contained animation object DOM1+ browsers
	multliple cell, variable frame delay, setable event handlers,  
	toggle or trip once animation, self-attaching events.
	Note: OBJECT.init() must be called after target image is loaded, or if done 
	with window.onload gcreate a wrapper function that calls OBJECT.init()
	
	©2006 Jonathan Little
	update 1.1 4/26/06 added clearTimout to kill instance in toggle mode with long  
					   delay in animation could cause multiple instances
*/
function AniFrame(cellNo,delayMS){
	this.cell=cellNo;
	this.delay=delayMS;
}

function AniObj(objName,targetId,eventList){
	this.self=objName;					//Object Var name for self reference
	this.target=targetId;				//ID of target image
	this.handle;						//reference to actual target element 
	this.events=eventList||'onclick';	//comma separated list of events to attach 'start'
	this.cells=new Array;				//image cache
	this.frames=new Array;				//animation frame loop
	this.ptr=0;							//frame ptr
	this.last=0;						//last frame in loop
	this.timer;							//timeout 
	this.running=false;
	this.toggle=false;					//set to true if you want toggle on and off
	this.cell=addCell;
	this.frame=addFrame;
	this.init=initAni;
	this.start=startAni;
	this.run=runAni;	
}

function addCell(img){
	var me=this;
	var i=me.cells.length;
	me.cells[i]=new Image;
	me.cells[i].src=img;
}

function addFrame(cellNo,delay){
	var me=this;
	var i=me.frames.length;
	var check=me.cells.length;
	if(cellNo>check) alert("ERROR: cell #" + cellNo + " > " + check);
	me.frames[i]=new AniFrame(cellNo,delay);
	me.last=i;
}

function initAni(){
	var me=this;
	var el=document.getElementById(me.target);
	var events=me.events.split(',');
	for(var i=0; i<events.length; i++){
	//	MSIE doesn't support: el.addEventListener(events[i], me.start);
		el[events[i]]=me.start;	
	}
	me.handle=el;		//attach img element to var object
	el.handle=me;		//now attach var object to img element
}

function startAni(){
	var me=this;					//this is the target image
	var obj=me.handle;				//get var obj from attached handle
	if(obj.running && obj.toggle){
		obj.running=false;			//when toggle is true 'toggle' animation off'
		clearTimeout(obj.timer);	//clear timer	
	}
	else if(!obj.running){
		obj.running=true;
		obj.run();					//start animation object if off
	}
}

function runAni(){
	var me=this;
	if(me.running){
		me.ptr++;
		if(me.ptr>me.last ) me.ptr=0;
		me.handle.src=me.cells[me.frames[me.ptr].cell].src;
		me.timer=setTimeout(me.self + ".run()", me.frames[me.ptr].delay);
	}
}



