Event.observe(window, 'load', function(e) {
	$$('textarea.codemirror_css').each(function(item) {
		new FCSCodeMirror(item.id, 'css');
	});

	$$('textarea.codemirror_javascript').each(function(item) {
		new FCSCodeMirror(item.id, 'javascript');
 	});	
});


function FCSCodeMirror(elementid, mode) {
	this.elementid = elementid;
	this.element = document.getElementById(this.elementid);
	this.editor = CodeMirror.fromTextArea(this.element, {
		mode			: mode,
		lineNumbers		: true
	});;

	this.lastPos = null;
	this.lastQuery = null;
	this.marked = [];


	if (!FCSCodeMirror.instances) FCSCodeMirror.instances = {};
	FCSCodeMirror.instances[elementid] = this;

	FCSCodeMirror.getinstance = function (elementid) {
		return FCSCodeMirror.instances[elementid];
	};

	FCSCodeMirror.searchkeypress = function (elementid, e) {
		var keycode;
		if (window.event) keycode = window.event.keyCode;
			else if (e) keycode = e.which;
				else return true;
		if (keycode == 13) {
			FCSCodeMirror.getinstance(elementid).search();
			return false;
		}

		return true;
	};


	this.unmark = function () {
		for (var i = 0; i < this.marked.length; ++i) this.marked[i]();
		this.marked.length = 0;
	};

	this.search = function () {
		this.unmark();  
	  
		var text = document.getElementById(this.elementid + '_search').value;
		if (!text) return;

		for (var cursor = this.editor.getSearchCursor(text); cursor.findNext(); )
			this.marked.push(this.editor.markText(cursor.from(), cursor.to(), "searched"));

		if (this.lastQuery != text) lastPos = null;
		var cursor = this.editor.getSearchCursor(text, this.lastPos || this.editor.getCursor());
		if (!cursor.findNext()) {
			cursor = this.editor.getSearchCursor(text);
			if (!cursor.findNext()) return;
		}
		this.editor.setSelection(cursor.from(), cursor.to());
		this.lastQuery = text; this.lastPos = cursor.to();
	};

	this.replace = function () {
		this.unmark();

		var text = document.getElementById(this.elementid + '_search').value;
		var replace = document.getElementById(this.elementid + '_replace').value;
		if (!text) return;

		for (var cursor = this.editor.getSearchCursor(text); cursor.findNext();)
			cursor.replace(replace);
	};

	this.debug = function (what) {
		alert(this.elementid + ': ' + what);
	};
}
