;(function($){
	/**
	  * Converts jQuery selector textarea into a nicEditor field
	  * 
	  * Arguments:
	  *		options		Same as nicEditor constructor options http://nicedit.com/demos.php?demo=2
	  *
	  * You must first set the base path of nicEditor via:
	  * 	$.fn.nicEditor.defaults.path = '/base/path/to/nicEdit' (e.g., /js);
	  */
	
	$.fn.nicEditor = function(options) {
		var o = $.extend({}, $.fn.nicEditor.defaults);
		
		if (o.path == null) {
			console.error("nicEditorPluginPath not specified.");
			return;
		}
		
		// Initialization
		if (! $.fn.nicEditor.state.loaded ) {
			var scriptPath = o.path + "/" + o.js;
			var that = this;

			// This will result in multiple load calls...
			// But alternative is to wait and stall
			$.getScript(scriptPath, function(data, textStatus) {
				if (data.indexOf("nicEditorConfig") < 0) {
					console.error("Error loading nicEditor plugin at " + scriptPath + ". Please check the path argument of nicEditor().");
				}
				$.fn.nicEditor.state.loaded = true;
				$(that).nicEditor(options);
			});
			
			return this;
		}
		
		// Now let's bind the nicEditors to this
		// First assign an arbitruary id to the selected if they don't have one. 
		// Ids are needed because that's currently how nicEditor works.
		var opts = $.extend({}, {iconsPath:o.path + "/" + o.icon}, options);
				
		if ($(this).is("textarea")) {
			var id = $(this).attr('id');
			
			if (id == undefined) {
				id = 'nicEdit-' + $.fn.nicEditor.state.elementIdCounter++;
				$(this).attr('id', id);
			}

			try {
				// IE will fail here with an unknown exception when nicEditor 
				// is being applied on a textarea that was retrieve
				// via AJAX that's nested inside a form inside an outter form.
				// So..
				//  <form id="outter">
				// 	  <div id="innerAjaxForm">
				//      <!-- contents retrieve via AJAX -->   
				//      <form>
				//        <textarea class="rtf" />
				//      </form>
				//    </div>
				//  </form> 
				var editor = new nicEditor(opts).panelInstance(id);

				
				editor.addEvent('blur', function() {
					try {
						editor.instanceById(id).saveContent();
					} catch(e) {
						// there's a leak as a result of ajax loads
						// TODO find a way to unload old destroyed editor fields 
						// console.debug(e);
					}
				})
			} catch (e) {
				$(this).prev().remove();
				$(this).prev().remove();
				$(this).show();
			}
		}
		
		return this;
	};

	$.fn.nicEditor.state = {
		loaded: false,
		elementIdCounter: 0
	};

	$.fn.nicEditor.defaults = {
		path: null,
		icon: 'nicEditorIcons.gif',
		js: 'nicEdit.js'
	};
})(jQuery);