module jg {
	export class FrameSprite extends Sprite {
		sep: number;
		frame: number[];
		fno: number;
		animation: bool;
		wait: number;
		loop: bool;
		frameEnded:Trigger;

		constructor(image:any, srcWidth:number, srcHeight:number, wait?:number) {
			super(image, srcWidth, srcHeight);
			this.sep = Math.floor(this.image.width / this.width);
			var frameCnt = Math.ceil(image.width * image.height) / (srcWidth * srcHeight);
			this.frame = [];
			for (var i=0; i<frameCnt; i++)
				this.frame.push(i);
			this.fno = 0;
			this.animation = false;
			this.wait = wait === undefined ? 200 : wait;
			this.loop = true;
		}	

		changeFrame() {
			this.srcX = (this.frame[this.fno] % this.sep) * this.srcWidth;
			this.srcY = Math.floor(this.frame[this.fno] / this.sep) * this.srcHeight;
			this.updated();
		}

		startTimer(noClear?:bool) {
			if (this.animation)
				return true;
			if (! noClear)
				this.fno = 0;
			this.animation = true;
			super.startTimer(this.wait);
		}

		stopTimer() {
			if (!this.animation)
				return;
			super.stopTimer(this.wait);
			this.animation = false;
		}

		interval() {
			this.fno++;
			if (this.fno >= this.frame.length) {
				if (this.loop) {
					this.fno = 0;
				} else {
					if (this.frameEnded) {
						this.stopTimer();
						this.frameEnded.fire();
						return;
					}
				}
			}
			this.changeFrame();
		}
	}
}