try {
	document.execCommand("BackgroundImageCache", false, true);
	/* IE6 flicker hack from http://dean.edwards.name/my/flicker.html */
} catch(err) {}

function AnimatedImage(seq, elementid) {
	this.seq = seq;
	this.element = $(elementid);
	this.element.setStyle({ 
		backgroundImage: "url("+this.seq.file+")",
		backgroundRepeat: "no-repeat",
		backgroundPosition: "0 0",
		height: this.seq.height+"px",
		width: this.seq.width+"px"
	});
	this.element.observe("mouseover",this.handlerMouseOver.bindAsEventListener(this));
	this.element.observe("mouseout",this.handlerMouseOut.bindAsEventListener(this));
	this.seqIdx = 0;
	this.render();
}


AnimatedImage.sequences = {
	hand: {
		file: "hand.jpg",
		height: 267,
		width: 213,
		loop: [ [0,100000], [1,200], [2,200], [3,200], [4,100000], [3,200], [2,200], [1,200]]
	}
};

AnimatedImage.prototype = {
		
	getFrameParams: function() {
		return this.seq.loop[this.seqIdx];
	},
	
	nextFrame: function() {
		this.seqIdx = (this.seqIdx+1)%this.seq.loop.length;
	},
	
	render: function() {
		var p = this.getFrameParams();
		this.element.style.backgroundPosition = "0 -"+ (this.seq.height * p[0]) + "px";
		var timeout = p[1];
		if (timeout<0) {
			timeout = Math.round(-timeout + (Math.random()*1000-500));
		}
		this.timer = window.setTimeout(this.render.bind(this), timeout);
		if ($("animdebug")) {
			var t = "Frame: "+this.seqIdx+"<br />"+timeout+"ms";
			if (p[1]<0) {
				t += "*";
			}
			$("animdebug").update(t);
		}
		this.nextFrame();
	},
	
	clearTimer: function() {
		window.clearTimeout(this.timer);
	},
	
	handlerMouseOver: function() {
		this.clearTimer();
		this.seqIdx = 1;
		this.render();
	},
	
	handlerMouseOut: function() {
		this.clearTimer();
		this.seqIdx = 5;
		this.render();
	}
	
	
	
};
