
/* ______________________________________________________________________

	Sprite Class
	This class creates an animated Sprite for image animation.

	Requires: Mootools 1.2

	License: MIT License

	Author:
	eneko.alonso@gmail.com
	http://enekoalonso.com
   ______________________________________________________________________
*/


var Sprite = new Class({
	ClassName: 'Sprite',
	Implements: Options,

	options: {
		frames: 1,
		sequence: [0],
		frameIntervals: [0],
		destroyOnComplete: false,
		hideOnComplete: false,
		hideSpeed: 400,
		loop: false,
		position: {x:0, y:0},
		size: {x:1, y:1},
		opacity: 1,
		orientation: 'vertical'
	},
	currentFrame: 0,
	bgPosition: {x:0,y:0},

	initialize: function(options) {
		this.setOptions(options);
		this.element = new Element('div', {'class': 'sprite'});
		this.element.setStyles({
			position: 'absolute',
			opacity: this.options.opacity,
			width:  this.options.size.x,
			height: this.options.size.y,
			background: 'url(' + this.options.image + ') no-repeat'
		});
		this.element.inject(document.body);

		this.animate(this);
	},

	destroy: function() {
		this.element.destroy();
		delete this;
	},

	animate: function(self) {
		if (self.options.loop) self.currentFrame %= self.options.frames;
		
		if (self.currentFrame < self.options.frames) {
			self.draw();
			if (self.options.frames > 1) {
				if (typeof self.options.frameIntervals === 'number') {
					self.setTimer(self.options.frameIntervals);
				} else {
					self.setTimer(self.options.frameIntervals[self.currentFrame]);
				}
				self.currentFrame++;
			}
		} else {
			if (self.options.hideOnComplete) {
				new Fx.Morph(self.element, {duration: self.options.hideSpeed}).start({opacity: 0});
			}
			if (self.options.destroyOnComplete) {
				self.destroy();
			}
		}
	},
	
	setTimer: function(timeout) {
		if (timeout) {
			var self = this;
			self.timer = setTimeout(function() {
				self.animate(self);
			}, timeout);
		}
	},

	draw: function() {
		if (this.options.orientation == 'vertical') {
			this.bgPosition.y = this.currentFrame * this.options.size.y;
		} else {
			this.bgPosition.x = this.currentFrame * this.options.size.x;
		}
		
		this.element.setStyles({
			left: Math.round(this.options.position.x),
			top:  Math.round(this.options.position.y),
			'background-position': (-this.bgPosition.x) + 'px ' + (-this.bgPosition.y) + 'px'
		})
	},
	
	moveTo: function(x, y) {
		this.options.position = {x: x, y: y}
		this.animate(this);
	},
	
	setImage: function(image) {
		this.options.image = image;
		this.element.setStyles({
			background: 'url(' + this.options.image + ') no-repeat'
		});
	}
});

