Native.implement([Element], {
	limit: function(n) {
		if (['INPUT', 'TEXTAREA'].contains(this.tagName) === false) return null;
		new Limit(this, n, this.retrieve('limit'));
		return this;
	}
});

var Limit = new Class({
	
	Implements: Options,
		
	options: {
		//onLimit: function() {}
	},
	
	initialize: function(element, n, options) {
		this.element = element;
		this.n = n;
		this.setOptions(options);
		this.attach();
	},
	
	attach: function() {
		this.element.addEvent('keyup', this.onKeyUp.bindWithEvent(this));
		if (typeof this.options.onLimit === 'function')
			this.addEvent('onlimit', this.options.onLimit.bindWithEvent(this.element));
	},
	
	onKeyUp: function() {
		if (this.element.get('value').length > this.n) {
			this.element.set('value', this.element.get('value').substr(0, this.n));
			this.element.fireEvent('onlimit');
		}
	}
	
});

