///////////////////////////////////////////////////////////////////////////
//University of Illinois Extension                                       //
//Office of Web Development                                              //
//Alessandro Bellina - bellina@uiuc.edu                                  //
//Copyright 2007 - Board of Trustees                                     //
//                                                                       //
//This code is not open source, and is protected by copyright law.       //
//Any use other than in U of I Extension websites is strictly prohibited.//
///////////////////////////////////////////////////////////////////////////

//Include TinyMCE source
document.write ("<script src=\"/htmlEditor/tinymce/jscripts/tiny_mce/tiny_mce_src.js\"></script>");

//CONSTANTS
var Editor_PUBLIC = 0;
var Editor_ADMIN = 1;
var Editor_EXACT = 0;
var Editor_TEXTAREAS = 1;
////////////////

//parent deprecated, pass at least null for the right order of the arg array
function HTMLEditor (parent, editorType, editorMode){
	this.parent = document.getElementById (parent);
	this.tinyMCEPtr = tinyMCE;	
	this.editorType = editorType || Editor_PUBLIC;
	this.editorMode = editorMode || Editor_EXACT;
	this.elementArray = new Array();
	this.resize = false;
	this.reduced = false;
	//initial size, -1 seems to make tinymce take the original textarea/div size.
	this.size = new Array (-1,-1);
	this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");	
	this.notFix = false;
	this.controlArray = [];
}
HTMLEditor.prototype.addControl = function (StringID){
	for (var i=0;i<this.controlArray.length; i++){
		if (StringID == this.controlArray[i])
			return;
	}
	var ptr = document.getElementById(StringID);
	this.tinyMCEPtr.addMCEControl (ptr,false,document);
	this.controlArray.push (StringID);
	this.setEditable (ptr);
}
HTMLEditor.prototype.removeControl = function (StringID){
	this.tinyMCEPtr.execCommand ("mceRemoveControl",false,document.getElementById (StringID));
}
HTMLEditor.prototype.setEditable = function (domObj){
	this.elementArray.push (domObj);
}
HTMLEditor.prototype.triggerSave = function (i){

	try{
		var instance = tinyMCE.getInstanceById ("mce_editor_"+i);
		if (instance){

			var content = CleanWordHTML (instance.getHTML());
			if (content > ""){
				tinyMCE.execInstanceCommand("mce_editor_"+i, "mceFocus");
				tinyMCE.setContent(content);
				instance.triggerSave();
			}
		}else{
			return;	
		}
	}catch (e){
		return;	
	}

}
HTMLEditor.prototype.saveToTextAreas = function (){
	for (var i=0; i<this.elementArray.length; i++){	
		var instance = tinyMCE.getInstanceById ("mce_editor_"+i);
		if (instance){
			var content = CleanWordHTML (instance.getHTML());
			tinyMCE.execInstanceCommand("mce_editor_"+i, "mceFocus");
			tinyMCE.setContent(content);
			instance.triggerSave();
		}
	}
}
HTMLEditor.prototype.setType = function (editorType){
	this.editorType = editorType;
}
HTMLEditor.prototype.setMode = function (mode){
	this.editorMode = mode;
}
HTMLEditor.prototype.setSize = function (coords){
	this.size = coords;	
}
HTMLEditor.prototype.setHeight = function (height){
	this.size = new Array (this.size[0], height);
	var ptr = document.getElementById("mce_editor_0");
	if (ptr)
		ptr.style.height = height+"px";
}
HTMLEditor.prototype.lite = function (){
	this.reduced = true;
}
HTMLEditor.prototype.setResizable = function (bool){	
	this.resize = bool;
}
HTMLEditor.prototype.resetAllEditors = function (){
	i=0;
	while (true){
			
		var instance = tinyMCE.getInstanceById ("mce_editor_"+i);
	
		if (!instance) return;
		
		tinyMCE.removeMCEControl (instance);
		i++;
	}
}
HTMLEditor.prototype.getContent = function (domObj){
	var content = "";
	if (this.elementArray.length > 0){
		content = "didn't find it";
		for (var i=0;i<this.elementArray.length;i++){
			if (this.elementArray[i].id==domObj.id){
				content = this.tinyMCEPtr.getContent ("mce_editor_"+i);
				content = CleanWordHTML (content);
				break;
			}
		}
		
	}else{
		var instance = this.tinyMCEPtr.getInstanceById (domObj);
		if (!instance) return;
		content = CleanWordHTML (instance.getHTML());
		tinyMCE.execInstanceCommand(domObj, "mceFocus");
		tinyMCE.setContent(content); //*check out
	}
	
	//instance.setHTML (content);
	return content;
}
HTMLEditor.prototype.setContent = function (domObj,content){
	var instance = this.tinyMCEPtr.getInstanceById (domObj);
	instance.execCommand('mceSetContent', false, content);
	try{instance.execCommand('removeformat',false);}catch (emall){}
}
HTMLEditor.prototype.start= function (notFix, mode){
	this.notFix = notFix || false;
		
	if (this.elementArray.toString() == "")
		this.elementStr = "none";
	else
		this.elementStr = this.elementArray.toString();
	
	var formatting_icons = "bold,italic,link,unlink,removeformat,charmap";
	var textcontrol_icons = "indent,outdent,bullist,numlist";
	var plugins_to_call= "spellchecker,table";
	var fn_icons = "fullscreen, spellchecker,iespell";
	var secondline_icons = "formatselect,tablecontrols,iespell";
	
	if (this.reduced){
		var plugins_to_call= "spellchecker";
		var fn_icons = "spellchecker";	
		var secondline_icons = "";
		var formatting_icons = "bold,italic,link,unlink";
	}
	
	if (this.editorType == Editor_ADMIN)
		plugins_to_call += ",paste";
		 
	if (this.editorType == Editor_PUBLIC)
		var admin_icons = "";
	else
		var admin_icons = "code,pastetext,separator,";
		
	if (this.editorMode == Editor_EXACT)
		this.modeStr = "exact";
	else if (this.editorMode == Editor_TEXTAREAS)
		this.modeStr = "textareas";
	
	
	//overwrite the mode if needed
	this.mode = mode || this.modeStr;
	
	this.tinyMCEPtr.init({
		theme : "advanced", 
		mode : this.mode, 
		elements: this.elementStr, 
		plugins:plugins_to_call,
		spellchecker_languages : "+English=en,Spanish=es",
		theme_advanced_buttons1 : admin_icons+fn_icons+",separator,"+formatting_icons+",separator,"+textcontrol_icons+",separator,undo,redo",
		theme_advanced_buttons2 : secondline_icons,
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top", 
		theme_advanced_toolbar_align : "left", 
		theme_advanced_path_location : "bottom",
		theme_advanced_resizing : this.resize,
		remove_linebreaks : true,
		apply_source_formatting: true,
		cleanup:false,
		width:this.size[0],
		height:this.size[1],
		accessibility_focus : false,
		editor_deselector : "mceNoEditor"
	});

}



//CleanWordHTML
function CleanWordHTML(oStr) {

	var myRegExp = new RegExp ("\\<\\!--\\[.*\\]--\\>", "gim");
	oStr=oStr.replace(myRegExp, "");
	var myRegExp = new RegExp ("\\<\\!--\\[.*\\]>", "gim");
	oStr=oStr.replace(myRegExp, "");
	var myRegExp = new RegExp ("\\<\\!\\[.*\\]-->", "gim");
	oStr=oStr.replace(myRegExp, "");

	myRegExp = new RegExp ("<xml(.|\n)*?</xml>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<?xml:(.|\n)*?</xml>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?xml[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<head(.|\n)*?</head>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?script[^>]>*", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?tt[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<style>[^>]*", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("</style[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?font[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?div[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?span[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<v:[^>]*>(.*?)</v>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?v:[^>]*>(.*?)", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?w:[^>]*>(.*?)", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<w:[^>]*>(.*?)</w>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<o:[^>]*>(.*?)</o:[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?st1:[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<\/?html[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<tr[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<tr>");
	myRegExp = new RegExp ("<p[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<p>");
	myRegExp = new RegExp ("<br[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<br>");
	myRegExp = new RegExp ("<li[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<li>");
	myRegExp = new RegExp ("<i[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<i>");
	/*myRegExp = new RegExp ("<td[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<td>");*/
	myRegExp = new RegExp ("<ul[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<ul>");
	myRegExp = new RegExp ("<ol[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<ol>");
	
	myRegExp = new RegExp ("<h2[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<h2>");
	myRegExp = new RegExp ("<h3[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<h3>");
	myRegExp = new RegExp ("<h4[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<h4>");
	myRegExp = new RegExp ("<h6[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<p>");
	
	myRegExp = new RegExp ("class=\"(.*?)\"", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("style=\"(.*?)\"", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<b [^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<strong>");
	myRegExp = new RegExp ("<\/?body[^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("<u [^>]*>", "gi");
	oStr=oStr.replace(myRegExp, "<u>");
	myRegExp = new RegExp ("<u>", "gi");
	oStr=oStr.replace(myRegExp, "<strong>");
	myRegExp = new RegExp ("</u>", "gi");
	oStr=oStr.replace(myRegExp, "</strong>");
	myRegExp = new RegExp ("<p[^>]*>&nbsp;</p>", "gi");
	oStr=oStr.replace(myRegExp, "");
	myRegExp = new RegExp ("&nbsp;", "gi");
	oStr=oStr.replace(myRegExp, " ");
	myRegExp = new RegExp ("<b>", "gi");
	oStr=oStr.replace(myRegExp, "<strong>");
	myRegExp = new RegExp ("</b>", "gi");
	oStr=oStr.replace(myRegExp, "</strong>");
	myRegExp = new RegExp ("<i>", "gi");
	oStr=oStr.replace(myRegExp, "<em>");
	myRegExp = new RegExp ("</i>", "gi");
	oStr=oStr.replace(myRegExp, "</em>");
	try{
		myRegExp = new RegExp ("“", "gi");
		oStr=oStr.replace(myRegExp, "\"");
		myRegExp = new RegExp ("”", "gi");
		oStr=oStr.replace(myRegExp, "\"");
		myRegExp = new RegExp ("’", "gi");
		oStr=oStr.replace(myRegExp, "'");
		myRegExp = new RegExp ("‘", "gi");
		oStr=oStr.replace(myRegExp, "'");
		myRegExp = new RegExp ("–", "gi");
		oStr=oStr.replace(myRegExp, "-");
		myRegExp = new RegExp ("—", "gi");
		oStr=oStr.replace(myRegExp, "&ndash;");
		myRegExp = new RegExp ("…", "gi");
		oStr=oStr.replace(myRegExp, "...");
	}catch (ioe){}
		
	// Various typographical marks; handy tool: http://slayeroffice.com/tools/unicode_lookup/
    oStr=oStr
	.replace(/&nbsp;/gi, " ")           // IE chokes on the below characters, hence the escapes:
    .replace(/\u201c/gi, "\"")          // “
    .replace(/\u201d/gi, "\"")          // ”
    .replace(/\u2019/gi, "'")           // ’
    .replace(/\u2018/gi, "'")           // ‘
    .replace(/\u2013/gi, "&ndash;")     // –
    .replace(/\u2014/gi, "&mdash;")     // —
    .replace(/\u2026/gi, "&hellip;")    // …

    // Condense multiple redundant tags into one:
    //      <strong>foo</strong> <strong>bar</strong> -> <strong>foo bar</strong>
    .replace(/<\/strong>(\s*)<strong>/gi, "$1")

    // Just to make the markup a little prettier: <p > becomes <p>
    .replace(/ >/gi, ">")

    ; // Done with the chain of replacements

    // Convert higher, non-ASCII characters to Unicode entity escapes
    var badChars=/[\u0256-\uFFFF]/;
    var match=badChars.exec(oStr);
    while(match && (i=match.index)) {
        oStr=oStr.substring(0,i)+"&#"+oStr.charCodeAt(i)+";"+oStr.substring(i+1,oStr.length)
        match=badChars.exec(oStr);
    }

    return(oStr);

}


if (Event == "undefined"){
	//Event Handler
	var Event = new EventHandler();
	function EventHandler (){}
	EventHandler.prototype.bind = function (src, eventName, target, fn){
		helper = function () {fn.apply (target);} ;
		if (eventName == "load")
			src.onload = helper;
		if (eventName == "change")
			src.onchange = helper;
	}
}