hare.site.tinymce = {
	numWords : {},
	countWords: function(rawTxt) {
		var txt = rawTxt.replace(/(<([^>]+)>)/ig,"");
	    txt = txt.replace(/&nbsp;/g," ");
	    txt = $.trim(txt.replace(/\n/g," "));
	    // split on spaces, count words
	    return txt.split(" ").length;
	},
	processWordCount: function(ed, maxWords) {
        var numWords = hare.site.tinymce.countWords(ed.getContent());
        hare.site.tinymce.numWords[ed.id] = numWords;
        tinymce.DOM.setHTML(tinymce.DOM.get(ed.id + '_path_row'), hare.site.tinymce.numWords[ed.id] + " Words ("+maxWords+" max) ");  
	},
	setTabIndex : function () {
		$(".mceToolbar *").attr("tabIndex", "-1");
	},	
	setupTinyMCE: function(maxWords, height, width) {
		if (typeof(maxWords) == "undefined") {
			maxWords = 500;
		}
		if (typeof(height) == "undefined") {
			height = 200;
		}
		if (typeof(width) == "undefined") {
			width = 570;
		}
		tinyMCE.init({		
		    mode : "textareas",
		    theme : "advanced",
		    editor_selector : "tinymce",
		    plugins : "paste",
		    width: ""+width,
		    content_css : "/resources/2805/css/tinymce.css",
			//encoding : "xml",
		    init_instance_callback: "hare.site.tinymce.setTabIndex",
				
		    // paste options
		    paste_auto_cleanup_on_paste : true,
		    paste_remove_styles: true,
		    paste_remove_styles_if_webkit: true,
		    
		    // Theme options
		    theme_advanced_buttons1 : "bold,italic,underline,|,bullist,numlist,|,undo,redo",
		    theme_advanced_buttons2 : "",
		    theme_advanced_buttons3 : "",
		    theme_advanced_toolbar_location : "top",
		    theme_advanced_toolbar_align : "left",
		    theme_advanced_statusbar_location : "bottom",
		    theme_advanced_resizing : false,
		    theme_advanced_path : false,
		    setup : function(ed) {
		        ed.onKeyUp.add(function(ed, e) {
		        	hare.site.tinymce.processWordCount(ed, maxWords);
		        });
		        ed.onPaste.add(function(ed, e) {
		        	hare.site.tinymce.processWordCount(ed, maxWords);
		        });
		        ed.onChange.add(function(ed, e) {
		        	hare.site.tinymce.processWordCount(ed, maxWords);
		        });
		        ed.onInit.add(function(ed) {
		            var e = tinymce.DOM.get(ed.id + '_tbl'), ifr = tinymce.DOM.get(ed.id + '_ifr'), w = ed.getWin(), dh;
		            var h = height; //new height of edit area
		            dh = e.clientHeight - ifr.clientHeight; //get the height of the toolbars
		            ed.theme.resizeTo(width, h + dh);

		            hare.site.tinymce.processWordCount(ed, maxWords);
		        });
		    },
		    handle_event_callback : function(e) {
		    	var id = tinyMCE.activeEditor.id;
		        if (e.type == "keydown" && hare.site.tinymce.numWords[id] > maxWords) {
		            if (e.keyCode == 8 || e.keyCode == 46) {
		                return true;
		            }
		            return false;
		        }
		    }   
		});     
	},
	getEditorContent: function(editorId) {
		return tinyMCE.get(editorId).getContent();
	}
}
