/**
 * @author Nityanand Ojha
 * @sprite animation
 */

window.requestAnimFrame = (function(callback) {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

function animate() {
	context.clearRect(0, 0, context.canvas.width, context.canvas.height);
	spriteMap.draw(context, 0, 0); // Draw the sprite
	requestAnimFrame(animate); // Run the animation loop
}

var cStat = "";
var feedbackVid = {
	
	init: function (){
		var __main = document.getElementById(spriteOBJ.parentDiv);
		var canvas = document.createElement("canvas");
		__main.appendChild(canvas);
		canvas.width = spriteOBJ.frameW;
		canvas.height = spriteOBJ.frameH;
		canvas.style.position = "absolute";
		canvas.style.top = spriteOBJ.animTop+"px";
		canvas.style.left = spriteOBJ.animLeft+"px";
		context = canvas.getContext('2d');
		
		var animNo = 0;
		var animNames = ['ideal', 'right', 'wrong'];
	
		// Initialize the SpriteMap
		spriteMap = new SpriteMap(
			spriteOBJ.imagePath,
			spriteOBJ.animSequence,
			{
			  frameW: spriteOBJ.frameW,
			  frameH: spriteOBJ.frameH,
			  projectedW: spriteOBJ.frameW, // Displayed width
			  projectedH: spriteOBJ.frameH, // Displayed height
			  interval: 50, // Switch frames every 50ms
			  useTimer: false, // Rely on requestAnimFrame to update frames instead of setInterval
			  
			  postInitCallback: function (sprite) {
				spriteMap.start('ideal'); // Start running the animation
				animate();
				
			  }
			  
			}
		);
	},
		
	playCorrectFeedback: function (func)
	{
		fun = func;
		spriteMap.runOnce(onFinish, 'right');
		cStat = "postRt"
	},

	playWrongFeedback: function (func)
	{
		fun = func;
		spriteMap.runOnce(onFinish, 'wrong');
		cStat = "postWr"
	},
	
	doReset: function (){
		spriteMap.use("ideal");
	}
};

function onFinish(){
	//console.log(spriteMap.activeLoop, " finish");
	spriteMap.use(cStat);
	
	try{
		fun();
	}catch(Err)
	{
		console.log("Error:  ", Err);
	}
}

