// JavaScript Document

var Jiggle = Class.create();
Jiggle.prototype = {
	
	currentFrame: 0,
	element: null,
	
	frames: null,
	
	returningToFirstFrame: false,
	jiggling: null,
	
	initialize: function(element, frames, options) {
		this.element = $(element);
		this.frames = frames;
		this.options = options || {};
		
		if (!('frameDelay' in this.options)) {
			this.options.frameDelay = 20;
		}
		
		this.showFrame(0);
		
		var preloadImage = null;
		for (var i = 0; i < this.frames.length; i++) {
			var preloadImage = document.createElement('img');
			preloadImage.setAttribute('src', this.frames[i]);
		}
		preloadImage = null;
		
	},
	
	setFrames: function(frames) {
		this.frames = frames;
		this.showFrame(this.currentFrame);
	},
	
	showFrame: function(number) {
		this.element.setAttribute('src', this.frames[number]);
		this.currentFrame = number;
	},
	
	showNextFrame: function() {

		// stop if we're back to the first frame after looping through once
		if ((this.currentFrame == 0) && this.returningToFirstFrame) {
			this.reset();
			return;
		}
		
		//if we're on the last frame start heading back to the first
		if (this.currentFrame == this.frames.length - 1) {
			this.returningToFirstFrame = true;
		}
		
		var nextFrameNumber = this.currentFrame;
		
		if (this.returningToFirstFrame) {
			nextFrameNumber--;
		} else {
			nextFrameNumber++;
		}
		
		this.showFrame(nextFrameNumber);
	},
	
	start: function() {
		if(!this.jiggling) {
			this.jiggling = setInterval(this.showNextFrame.bind(this), this.options.frameDelay);
		}
	},
	
	stop: function() {
		clearInterval(this.jiggling);
		this.jiggling = null;
	},
	
	reset: function() {
		this.stop();
		this.returningToFirstFrame = false;
		this.element.setAttribute('src', this.frames[0]);
	}
	
}
