var MeMooEditable = new Class ({
	Implements: [Options, Events],
	
	options: {
		max: 1000,
		textarea: null,
		actions : 'bold italic underline | createlink unlink',
		counter: null,
		counterText: null
	},
	
	mooEditable: null,
	submit: null,
	
	initialize: function (options) {
		this.setOptions(options);
		
		if(this.options.counter != null) {
			this.submit = this.options.counter.getParent('form').getElement('input[type=submit]');
		}
		
		this.mooEditable = new MooEditable(this.options.textarea, {
			actions: this.options.actions,
			externalCSS: '/css/sheets/memoree-tinymce.css',
			paragraphise: false,
			rootElement: null,
			onRender: this.manageRender.bind(this),
			onEditorKeyUp: this.manageEditorKeyUp.bind(this)
		});
	},
	
	manageRender: function(e) {
		if(this.options.counter != null)
			this.manageCounter(e.textarea.value);
	},
	
	manageEditorKeyUp: function(e) {
		if(this.options.counter != null)
			this.manageCounter(this.mooEditable.getContent());
	},
	
	manageCounter: function(text) {
		var c = this.count(text);
		if(c < 10 && c >= 0) {
			this.options.counter.setStyle('color', '#dd6901');
		} else if(c < 0){
			this.options.counter.setStyle('color', 'red');
		} else if(c == 1000) {
			// Do nothing
		} else {
			this.options.counter.setStyle('color', '');
		}
		var text = c <= 1 ? this.options.counterText[2] : this.options.counterText[0];
		this.options.counter.set('text', c < 0 ? this.options.counterText[1] : (c + ' ' + text));
	},
	
	toElement: function(el) {
		var div = new Element('div');
		div.set('html', el);
		return div;
	},
	
	count: function(text) {
		return this.options.max - this.toElement(text).get('text').clean().length;
	},
	
	getContent: function() {
		return this.mooEditable.getContent();
	},
	
	setContent: function(text) {
		return this.mooEditable.setContent(text);
	}
});