var TextLengthCounter = new Class({
	initialize: function(textarea, maxLength, threshold) {
		this.textarea = textarea;
		this.maxLength = maxLength;
		this.threshold = threshold;
		
		this.counter = new Element("div", { "class": "textLengthCounter" })
			.setStyles({
				"left": 0,
				"top": 0,
				"opacity": 0
			})
			.set("tween", { "duration": "short" })
			.inject(document.body);
		this.visible = false;
		this.update();

		var tlc = this;
		window.addEvent("resize", function() {
			tlc.update();
		});

		this.textarea.addEvent("keyup", function() {
			tlc.update();
		});
	},
	
	update: function() {
		var show = (this.textarea.value.length >= (this.maxLength - this.threshold));

		// update opacity (fade out)
		if (!show && this.visible) {
			this.counter.fade("out");
			this.visible = false;
		} else if (show) {
			// reposition
			var coords = this.textarea.getCoordinates();
			var scroll = this.textarea.getScroll();
			this.counter.setStyles({
				"left": coords.right + scroll.x + 3,
				"top": coords.top + scroll.y
			});
			
			// update text
			this.counter.set("text", this.textarea.value.length + "/" + this.maxLength);
			
			// update style
			if (this.textarea.value.length <= this.maxLength) {
				this.counter.removeClass("warn");
			} else {
				this.counter.addClass("warn");
			}
			
			// update opacity (fade in)
			if (!this.visible) {
				this.counter.fade("in");
				this.visible = true;
			}
		}
	}
});
