$.fn.spriteGrid = function(options){
	sprite = $(this);
	var image = new Image();
	image.src = options.spriteImage;

	var placeholder = $(this);

	placeholder.addClass('sprite').css({
		"position": "absolute",
		"background-image": "url('"+options.spriteImage+"')"
	});


	image.onload = function(){
		placeholder.width(image.width/options.gridX);
		placeholder.height(image.height/options.gridY);
		var frames = new Array();
		var x = 0; var y = 0; var f = 0;
		for(frame=0; frame<options.nFrames; frame++){
			if(x == Math.floor(image.width/placeholder.width())){
				x=0; y++;
				if(y == Math.floor(image.height/placeholder.height())){
					y=0;
				}
			}
			frames[frame] = [-(placeholder.width()*x), -(placeholder.height()*y)]; x++;
		}
		$.fn.play = function(loop, callbackPlay){
			f = 0;
			placeholder.stopTime();

			placeholder.everyTime(1000/options.fps, function(){

				if(f == options.nFrames-1){
					placeholder.stopTime();
					if(typeof(callbackPlay) == "function") callbackPlay();
				} else { 
					f++;
				}
			$(this).css("background-position", frames[f][0]+"px "+frames[f][1]+"px");
			});
			return $(this);
		}
		$.fn.reverse = function(loop, frame, callbackReverse){
			placeholder.stopTime();
			placeholder.everyTime(1000/options.fps, function(){
				$(this).css("background-position", frames[f][0]+"px "+frames[f][1]+"px");
				if(f == 0){
					if(loop){
						f = options.nFrames-1;
					} else {
						placeholder.stopTime();
					}
				} else {
					f--;
				}
			});
			if(typeof(callbackReverse) == "function") callbackReverse();
			return $(this);
		}
		if(typeof(options.callback) == "function") options.callback();
	}
	return $(this);
}
