var imgAnimate = new Class({
	options: {
		container:"imgAnimateContainer",
		image:false,
		baseClass:"imgAnimate",
		frames:8,
		frameSize:{w:64, h:64},
		framesPerRow:4,
		delay:1000
	},
	image:false,
	frame:0,
	loopCount: 0,
	isStopped: true,
	isLooping: false,
	loopMethod: false,

	initialize: function(options){
		this.setOptions(options);
		this.image = new Element('span').addClass( this.options.baseClass ).injectInside($(this.options.container));
		this.image.setStyle("background-image","url("+this.options.image+")");
		this.setLoop(this.runAnimation, this.options.delay);
		this.startLoop();
	},

	runAnimation : function(){
		if( this.frame >= this.options.frames ) {
			this.frame = 0;
		}
		var xx = -(this.frame % this.options.framesPerRow) * this.options.frameSize.w;
		var yy = -Math.floor(this.frame / this.options.framesPerRow) * this.options.frameSize.h;
		this.image.setStyle("background-position", xx+"px "+yy+"px");
		this.frame++;
	},
	
	setLoop: function(fn,delay){
		if(this.isLooping) {
			this.stopLoop();
			var wasLooping = true;
		} else {
			var wasLooping = false;
		}
		this.loopMethod = fn;
		this.loopDelay = delay || 3000;
		if(wasLooping) this.startLoop();
		return this;
	},

	stopLoop: function() {
		this.isStopped = true;
		this.isLooping = false;
		$clear(this.periodical);
		return this;
	},

	startLoop: function(delay) {
		if(this.isStopped){
			var delay = (delay) ? delay : this.loopDelay;
			this.isStopped = false;
			this.isLooping = true;
			this.periodical = this.looper.periodical(delay,this);
		};
		return this;
	},

	resetLoop: function(){
		this.loopCount = 0;
		return this;
	},

	looper: function(){
		this.loopCount++;
		this.loopMethod(this.loopCount);
		return this;
	}
});
imgAnimate.implement(new Options);
