/* REQUIRES: Colour.class.js */
/* usage: Highlighter.start(Node) */
var Highlighter = {
	startCol : 0xffcccc,
	endCol : 0xffffff,

	frameRate : 20,
	idCounter : 0,

	items : {},

	// some 'constants'. these must be negative so that we
	// know that they're special values and not a decimal
	// representation of a colour.
	HOLD : -1,
	REVERT : -2,

	start : function(el, startCol, endCol, afterCol, length, frameRate, onfinish) {
		this.stop(el);
		if (startCol == undefined || startCol == null) startCol = this.startCol;
		if (endCol == undefined || endCol == null) endCol = this.endCol;
		if (length == undefined || length == null) length = 1;
		if (frameRate == undefined || frameRate == null) frameRate = this.frameRate;
		if (onfinish == undefined) onfinish = null;
		if (afterCol == this.HOLD) {
			afterCol = (new Colour(endCol)).toHTML();
		} else if (typeof afterCol == "number" && afterCol >= 0) {
			afterCol = (new Colour(afterCol)).toHTML();
		} else {
			afterCol = el.style.backgroundColor;
		}

		el = $(el);

		if (!el.id) {
			el.id = 'highlightEl' + this.idCounter++;
		}

		if (this.items[el.id]) {
			this.stop(el, false); // false so that it doesn't clear it and flash to a different colour.
		}

		var numFrames = length * frameRate;

		startCol = new Colour(startCol);
		endCol = new Colour(endCol);
		//afterCol = new Colour(afterCol);

		var step = [];
		for (var i = 0; i < 3; i++) {
			step[i] = (endCol.get(i) - startCol.get(i)) / numFrames;
		}

		this.items[el.id] = {
			el : el,
			colour : startCol,
			endCol : endCol,
			step : step,
			timeout : setInterval('Highlighter.doIt("' + el.id + '")', 1000 / frameRate),
			onfinish : onfinish,
			afterCol : afterCol
		};

		el.style.backgroundColor = startCol.toHTML();
	},

	doIt : function (el) {
		el = $(el);
		this.items[el.id].colour.add(this.items[el.id].step);
		el.style.backgroundColor = this.items[el.id].colour.toHTML();

		var curr = this.items[el.id].colour.toArray();
		var target = this.items[el.id].endCol.toArray();
		var ready = true;


		for (var i = 0; i < 3; i++) {
			var s = this.items[el.id].step[i];
			if (!((s >= 0 && curr[i] >= target[i]) || (s < 0 && curr[i] <= target[i]))) {
				ready = false;
				break;
			}
		}


		if (ready) {
			if (this.items[el.id].onfinish) this.items[el.id].onfinish(el);
			this.stop(el);
		}
	},

	stop : function (el, clear) {
		el = $(el);
		if (this.items[el.id] != undefined) {
			clearInterval(this.items[el.id].timeout);
			if (clear == undefined || clear == true) el.style.backgroundColor = this.items[el.id].afterCol;
			delete(this.items[el.id]);
		}
	}
};