/** 
	Takes a tiled image and steps through each tile based off
	its idim and jdim.
*/
function AnimatedSprite(img,idim,jdim){
	var currentFrame = 0; 
	var fadeStep =0;
	var frameWidth = img.width / idim;
	var frameHeight = img.height / jdim;
	var sprites = new Array(idim*jdim);	
	var pos = 0; 
	
	for (var j =0; j < jdim; j++){
		for (var i =0; i < idim; i++){
			sprites[j*idim+i] = {
				x:i*frameWidth,
				y:j*frameHeight
			}
		}
	}

	
	return {
		/** 
			Draw the current frame in this animated sprite and increment the frame counter
		*/
		drawNext:function(ctx,x,y){
			var sprite = sprites[currentFrame++]; 
			ctx.drawImage(
				img,
				sprite.x,sprite.y,
				frameWidth,frameHeight,
				x,y,
				frameWidth,frameHeight
			);
			if (currentFrame == sprites.length)
				currentFrame=0; 
		},
		
		/** 
			Fade the current frame in a given number of steps, then increment the frame counter 
		*/
		fadeInNext:function(ctx,x,y,numSteps){
			if (numSteps == undefined) numSteps = 10; 
			ctx.globalAlpha = 1/numSteps;
			var sprite = sprites[currentFrame]; 
			
			//ctx.rotate(2 * Math.PI / 18);
			ctx.drawImage( img,
				sprite.x,
				sprite.y,
				frameWidth,
				frameHeight,
				x,y,
				frameWidth,
				frameHeight
			);
			
			//ctx.rotate(-2 * Math.PI / 18);			
			ctx.globalAlpha = 1;
			if (fadeStep < 10) 
				fadeStep++; 
			else{
				fadeStep =0;
				currentFrame++;
				if (currentFrame == sprites.length)
					currentFrame=0;
			}
		},
		/** Create a copy of this sprite */
		copy:function(){
			return new AnimatedSprite(img,idim,jdim);
		},
		width:frameWidth,
		height:frameHeight
	}
}

var img = new Image(); 
var ctx = document.getElementById('water').getContext('2d');
img.src="/images/water/caustics.jpg";
img.onload = function(){
	var sprite = new AnimatedSprite(img,4,4); 
	setInterval(function(){
		if (img.complete){
			sprite.fadeInNext(ctx,0,0,10);
		}
	},10);
}





