// Cross-Browser Rich Text Editor
// Version 3.08b
// Written by Kevin Roth (http://www.kevinroth.com/rte/)
// Visit the support forums at http://www.kevinroth.com/forums/index.php?c=2
// License: http://creativecommons.org/licenses/by/2.5/

//init globals
var debugMode = false;
var isRichText = false;
var allRTEs = "";
var currentRTE = "";
var selectionText = "";
var rng;
var lastCommand;
var maxLoops = 20;
var loopCnt = 0;
var baseUrl = window.parent.document.location.protocol + "//" + document.domain + "/";

var imagesPath = "";
var includesPath = "";

//browser vars
var ua = navigator.userAgent.toLowerCase();
var isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
var ieVersion = parseFloat(ua.substring(ua.indexOf('msie ') + 5));
var isGecko = (ua.indexOf("gecko") != -1);
var isSafari = (ua.indexOf("safari") != -1);
//var safariVersion = parseFloat(ua.substring(ua.lastIndexOf("safari/") + 7));
var webkitVersion = get_webkit_version();
if (webkitVersion) {
	webkitVersion = webkitVersion["major"];
} else {
	webkitVersion = null;
}
var isKonqueror = (ua.indexOf("konqueror") != -1);
var konquerorVersion = parseFloat(ua.substring(ua.indexOf('konqueror/') + 10));
var isOpera = (ua.indexOf("opera") != -1);
var isNetscape = (ua.indexOf("netscape") != -1);
var netscapeVersion = parseFloat(ua.substring(ua.lastIndexOf('/') + 1));

//command vars
var toolbar1Enabled = true;
var cmdInsertHTMLEnabled = true;
var cmdCreateLinkEnabled = true;
var cmdInsertImageEnabled = true;

function $(ElementId){
	return document.getElementById(ElementId);
}

function initRTE(imgPath, incPath, css) {
	//set browser vars
	try {
		//set global vars
		imagesPath = imgPath;
		includesPath = incPath;
		
		//check to see if designMode mode is available and disable unsupported commands
		if (document.designMode) {
			if (document.getElementById && !isIE && !isSafari && !isKonqueror) {
				isRichText = true;
				if (isNetscape && netscapeVersion < 8) {
					cmdInsertHTMLEnabled = false;
				}
			} else if (isIE && ieVersion >= 5.5) {
				isRichText = true;
			} else if (isSafari) {
				if (webkitVersion >= 420) {
					isRichText = true;
				} else if (webkitVersion >= 312) {
					//Safari 1.3+ is capable of designMode, Safari 1.3 = webkit build 312
					isRichText = true;
					toolbar1Enabled = false;
					cmdInsertImageEnabled = false;
					cmdInsertHTMLEnabled = false;
					cmdCreateLinkEnabled = false;
				}
			}
		}
		if (isRichText) {
			if(isIE){
				document.onmouseover = raiseButton;
				document.onmouseout  = normalButton;
				document.onmousedown = lowerButton;
				document.onmouseup   = raiseButton;
			}
		}
		
		//for testing standard textarea, uncomment the following line
		//isRichText = false;
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function richTextEditor(id) {
	//creates a richTextEditor object
	this.rteID = id;
	
	//set defaults
	this.html = "";
	
	//add methods
	this.build = build;
}

function build() {
	with (this) {
		if (isRichText){
			var cp = '<iframe width="150" height="100" id="cp" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" style="visibility:hidden; position: absolute;"></iframe>';
			if(this.rteID == 'rte1') panel1.appendToBody(cp);
			else if(this.rteID == 'rte2') panel2.appendToBody(cp);
			else if(this.rteID == 'rte3') $('message_reply').innerHTML=$('message_reply').innerHTML+cp;

			writeRichText(this);

			if(this.rteID == 'rte1') panel1.render(document.body);
			else if(this.rteID == 'rte2') panel2.render(document.body);

			enableDesignMode(this.rteID, htmlDecode(this.html));
				
			if (isGecko) {
				//set focus on the RTE
				currentRTE = this.rteID;
				insertHTML("<br>");
				rteCommand(this.rteID, "undo");
			}
		}else{
			writePlainText(this);
		}
	}
}

function writePlainText(rte) {
	if(rte.rteID == 'rte1') panel1.appendToBody('<textarea name="' + rte.rteID + '" id="hdn' + rte.rteID + '" style="width:260px; height:508px">' + rte.html + '</textarea>');
	else if(rte.rteID == 'rte2') panel2.appendToBody('<textarea name="' + rte.rteID + '" id="hdn' + rte.rteID + '" style="width:260px; height:508px">' + rte.html + '</textarea>');
}

function rteSubmit(rteID) {
	$('panel_buttons').className = "hid"; $('panel_loading').className = "bg3";

	if(rteID == 'rte1') addProfileComment();
	else if(rteID == 'rte2') sendMessage();
	else if(rteID == 'rte3') {
		updateRTEs();
		if($('hdnrte3').value.length > 65535) {
			Alert.show(undefined, 'Error', 'Your message is too long. 65535 is the max number of characters allowed', false);

			$('panel_buttons').className = "bg3 alignL"; $('panel_loading').className = "hid";
		}
		else {
			$('message_body').value = $('hdnrte3').value;
			document.reply_message.submit();
		}
	}
}

function writeRichText(rte) {
	try {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte.rteID;

		html ='<table id=contain_' + rte.rteID + ' style="visibility:visible" align=center width="510" cellpadding="0" cellspacing="0">';
		if(rte.rteID == 'rte3')
			html+='<tr><td align=left><strong>Your Reply:</strong>';
		else
			html+='<tr><td>';
		html+='<table class=toolbar cellpadding="0" cellspacing="0" id="toolbar1_' + rte.rteID + '" width="100%">';
		html+='<tr>';
		if (toolbar1Enabled) {
			html+='<td>';
			html+='<select id="fontname_' + rte.rteID + '" onchange="selectFont(\'' + rte.rteID + '\', this.id)">';
			html+='<option value="Font" selected>[Font]</option>';
			html+='<option value="Arial, Helvetica, sans-serif">Arial</option>';
			html+='<option value="Courier New, Courier, mono">Courier New</option>';
			html+='<option value="Times New Roman, Times, serif">Times New Roman</option>';
			html+='<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>';
			html+='</select>';
			html+='</td><td>';
			html+='<select id="fontsize_' + rte.rteID + '" onchange="selectFont(\'' + rte.rteID + '\', this.id)">';
			html+='<option value="Size">[Size]</option>';
			html+='<option value="1">1</option>';
			html+='<option value="2">2</option>';
			html+='<option value="3">3</option>';
			html+='<option value="4">4</option>';
			html+='<option value="5">5</option>';
			html+='<option value="6">6</option>';
			html+='<option value="7">7</option>';
			html+='</select>';
			html+='</td>';
		}
		html+='<td><img class="rteImage" src="' + imagesPath + 'bold.gif" alt="Bold" title="Bold" onmousedown="rteCommand(\'' + rte.rteID + '\', \'bold\')"></td>';
		html+='<td><img class="rteImage" src="' + imagesPath + 'italic.gif" alt="Italic" title="Italic" onmousedown="rteCommand(\'' + rte.rteID + '\', \'italic\')"></td>';
		html+='<td><img class="rteImage" src="' + imagesPath + 'underline.gif" alt="Underline" title="Underline" onmousedown="rteCommand(\'' + rte.rteID + '\', \'underline\')"></td>';
		html+='<td><div id="forecolor_' + rte.rteID + '"><img class="rteImage" src="' + imagesPath + 'forecolor.gif" alt="Text Color" title="Text Color" onmousedown="dlgColorPalette(\'' + rte.rteID + '\', \'forecolor\', \'\'); return false;"></div></td>';
		html+='<td><div id="hilitecolor_' + rte.rteID + '"><img class="rteImage" src="' + imagesPath + 'hilitecolor.gif" alt="Background Color" title="Background Color" onmousedown="dlgColorPalette(\'' + rte.rteID + '\', \'hilitecolor\', \'\'); return false;"></div></td>';	
		html+='<td><img class="rteImage" src="' + imagesPath + 'left_just.gif" alt="Align Left" title="Align Left" onmousedown="rteCommand(\'' + rte.rteID + '\', \'justifyleft\')"></td>';
		html+='<td><img class="rteImage" src="' + imagesPath + 'centre.gif" alt="Center" title="Center" onmousedown="rteCommand(\'' + rte.rteID + '\', \'justifycenter\')"></td>';
		html+='<td><img class="rteImage" src="' + imagesPath + 'right_just.gif" alt="Align Right" title="Align Right" onmousedown="rteCommand(\'' + rte.rteID + '\', \'justifyright\')"></td>';
		if (cmdInsertHTMLEnabled || cmdCreateLinkEnabled)
			html+='<td><img id=hyperLinkButton class="rteImage" src="' + imagesPath + 'createlink.gif" alt="Insert Link" title="Insert Link" onmousedown="dlgInsertLink(\'' + rte.rteID + '\')"></td>';
		if (cmdInsertImageEnabled)
			html+='<td><img id=addImageButton class="rteImage" src="' + imagesPath + 'insertimage.gif" alt="Add Image" title="Add Image" onmousedown="addImage(\'' + rte.rteID + '\')"></td>';
		html+='<td width="100%"></td>';
		html+='</tr>';
		html+='</table>';	
		html+='</td>';
		html+='</tr>';
		html+='</table>';

		html+='<input type="hidden" id="hdn' + rte.rteID + '" name="hdn' + rte.rteID + '" value="">';

		html+='<iframe id="' + rte.rteID + '" name="' + rte.rteID + '" src="' + includesPath + 'blank.htm" frameborder="0" style="visibility:visible; width:508px; height:260px; margin: 0; padding: 0; border: 1px solid #000;"></iframe>';

		if(rte.rteID == 'rte1' || rte.rteID == 'rte2'){
			html+='<div id="panel_buttons" style="position:absolute; left:4px; bottom:6px">';
			html+='<img src="http://static.networkpiece.com/c/pixel.gif" width=52 height=22 class="btnSend" onmousedown="rteSubmit(\''+rte.rteID+'\')">&nbsp;';
			html+='<img src="http://static.networkpiece.com/c/pixel.gif" width=52 height=22 class="btnCancel" onmousedown="closePanel(';
			if(rte.rteID == 'rte1') html+='\'panel1\'';
			else if(rte.rteID == 'rte2') html+='\'panel2\'';
			html+=')">';
			html+='</div>';
			html+='<div id="panel_loading" class="hid" style="position:absolute; left:10px; bottom:8px">';
		}
		else if(rte.rteID == 'rte3'){
			html+='<div id="panel_buttons" class="bg3 alignL" style="width:502px; padding:5px; margin: 0 auto"><img src="http://static.networkpiece.com/c/pixel.gif" width=52 height=22 class="btnSend" onmousedown="rteSubmit(\''+rte.rteID+'\')"></div>';
			html+='<div id="panel_loading" class="hid" style="width:502px; padding:5px; text-align:left; margin: 0 auto">';
		}
		html+='<img src="http://static.networkpiece.com/c/LoadingGraphicSmall.gif"></div>';

		if(rte.rteID == 'rte1') panel1.appendToBody(html);
		else if(rte.rteID == 'rte2') panel2.appendToBody(html);
		else if(rte.rteID == 'rte3') $('message_reply').innerHTML=$('message_reply').innerHTML+html;

	} catch (e) {
		if (debugMode) alert(e);
	}
}

function enableDesignMode(rte, html) {
	try {
		var frameStyle = "<style type=\"text/css\">\n";
		frameStyle += "body {\n";
		frameStyle += "	background: #FFF;\n";
		frameStyle += "}\n";
		frameStyle += "</style>\n";
		
		var frameHtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
		frameHtml += "<html id=\"" + rte + "\" xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n";
		frameHtml += "<head>\n";
		frameHtml += "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n";
		frameHtml += "<base href=\"" + baseUrl + "\" />\n";
		if (!isGecko) frameHtml += frameStyle;
		frameHtml += "</head>\n";
		frameHtml += "<body style=\"margin: 0; padding: 0;\">\n";
		frameHtml += html + "\n";
		if (isGecko) frameHtml += frameStyle;
		frameHtml += "</body>\n";
		frameHtml += "</html>";
		
		var oRTE = $(rte);
		try {
			if (isGecko) {
				oRTE.contentDocument.designMode = "on";
				try {
					var oRTEDoc = oRTE.contentWindow.document;
					oRTEDoc.open("text/html","replace");
					oRTEDoc.write(frameHtml);
					oRTEDoc.close();
					oRTEDoc.addEventListener("keypress", geckoKeyPress, true);
				} catch (e) {
					alert("Error preloading content.");
				}
				loopCnt = 0;
			} else if (oRTE.contentWindow) {
				//IE 5.5+
				try {
					var oRTEDoc = oRTE.contentWindow.document;
					oRTEDoc.open("text/html","replace");
					oRTEDoc.write(frameHtml);
					oRTEDoc.close();
					if (isIE) oRTEDoc.attachEvent("onkeypress", evt_ie_keypress);
				} catch (e) {
					alert("Error preloading content.");
				}
				oRTEDoc.designMode = "on";
				loopCnt = 0;
			} else {
				//IE5 and Opera
				var oRTEDoc = oRTE.document;
				//oRTEDoc.open("text/html","replace");
				//oRTEDoc.write(frameHtml);
				//oRTEDoc.close();
				if (isIE) oRTEDoc.attachEvent("onkeypress", evt_ie_keypress);
				oRTEDoc.designMode = "on";
				loopCnt = 0;
			}
		} catch (e) {
			//some browsers may take some time to enable design mode.
			//Keep looping until able to set.
			if (loopCnt < maxLoops) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "');", 100);
				loopCnt += 1;
			} else {
				alert("Error enabling designMode.");
			}
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function updateRTE(rte) {
	try {
		if (isRichText) {
			setHiddenVal(rte);
		} else {
			return;
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function updateRTEs() {
	try {
		if (allRTEs != "") {
			var vRTEs = allRTEs.split(";");
			for (var i = 0; i < vRTEs.length; i++) {
				updateRTE(vRTEs[i]);
			}
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function rteCommand(rte, command, option) {
	//function to perform command
	try {
		var oRTE = $(rte);
		if (oRTE.contentWindow) {
			oRTE.contentWindow.focus();
			oRTE.contentWindow.document.execCommand(command, false, option);
		} else {
			oRTE.document.focus();
		  	oRTE.document.execCommand(command, false, option);
		}
		loopCnt = 0;
		
		return false;
	} catch (e) {
		if (debugMode) alert(e);
		//Keep looping until able to set.
		if (loopCnt < maxLoops) {
			setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 100);
			loopCnt += 1;
		} else {
			alert("Error executing command.");
		}
	}
}

function dlgColorPalette(rte, command) {
	//function to display or hide color palettes
	try {
		setRange(rte);
		
		//get dialog position
		var buttonElement = $(command + '_' + rte);
		var iLeftPos = findPosX(buttonElement, rte);
		var iTopPos = findPosY(buttonElement, rte) + buttonElement.offsetHeight;

		var oDialog = $('cp');
		
		oDialog.style.left = iLeftPos + "px";
		oDialog.style.top = iTopPos + "px";
		
		if ((command == lastCommand) && (rte == currentRTE)) {
			//if current command dialog is currently open, close it
			if (oDialog.style.visibility == "hidden") {
				showHideElement('cp', 'show');
			} else {
				showHideElement('cp', 'hide');
			}
		} else {
			showHideElement('cp', 'show');
		}
		
		//save current values
		lastCommand = command;
		currentRTE = rte;
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function dlgInsertLink(rte) {
	//function to open insert link dialog
	try {
		if (cmdInsertHTMLEnabled) {
			//save current values
			setRange(rte);
			currentRTE = rte;
			Alert.show($('hyperLinkButton'), 'Insert Hyperlink', '<table cellpadding="4" cellspacing="0" border="0"><tr><td align="right">URL:</td><td><input name="url" type="text" id="url" size="40"></td></tr><tr><td align="right">Text:</td><td><input name="linkText" type="text" id="linkText" size="40"></td></tr></table>', true); 

			$('hyperLinkButton').onAlertOk = function(e){
				var html = '<a href="' + $('url').value + '" target="_blank">' + $('linkText').value + '</a>&nbsp;';
				insertHTML(html);
			};
		} else {
			var url = prompt("Enter URL", "http://");
			rteCommand(rte, "createlink", url);
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function setColor(color) {
	//function to set color
	try {
		var rte = currentRTE;
		if (isSafari || isIE) {
			if (lastCommand == "hilitecolor") lastCommand = "backcolor";
			
			//retrieve selected range
			if (!isSafari) rng.select();
		}
		
		rteCommand(rte, lastCommand, color);
		showHideElement('cp', "hide");
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function addImage(rte) {
	//function to add image
	try {
		Alert.show($('addImageButton'), 'Insert Image', 'Enter Image URL:<br><input type="text" size=40 id="imageUrl" name="imageUrl"/>', true);
		$('addImageButton').onAlertOk = function(alert){
		    if($('imageUrl').value){
				rteCommand(rte, 'InsertImage', $('imageUrl').value);
		    }
		};
	} catch (e) {
		if (debugMode) alert(e);
	}
}

//positioning functions courtesy of Peter-Paul Koch - http://www.quirksmode.org/
function findPosX(obj, rte) {
	var curleft = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
		}
	}
	if(rte=='rte1') return curleft - panel1.cfg.getProperty("x");
	else if(rte=='rte2') return curleft - panel2.cfg.getProperty("x");
	return curleft;
}

function findPosY(obj, rte) {
	var curtop = 0;
	if (obj.offsetParent) {
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curtop += obj.offsetTop;
		}
	}
	if(rte=='rte1') return curtop - panel1.cfg.getProperty("y");
	else if(rte=='rte2') return curtop - panel2.cfg.getProperty("y");
	return curtop;
}

function selectFont(rte, selectname) {
	//function to handle font changes
	try {
		var idx = $(selectname).selectedIndex;
		// First one is always a label
		if (idx != 0) {
			var selected = $(selectname).options[idx].value;
			var cmd = selectname.replace('_' + rte, '');
			rteCommand(rte, cmd, selected);
			$(selectname).selectedIndex = $(selectname).selectedIndex;
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function insertHTML(html) {
	//function to add HTML -- thanks dannyuk1982
	try {
		if (document.all && !isOpera) {
			rng.pasteHTML(html);
			rng.collapse(false);
			rng.select();
		} else {
			rteCommand(currentRTE, 'inserthtml', html);
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function showHideElement(element, showHide) {
	//function to show or hide elements
	try {
		//element variable can be string or object
		if ($(element)) {
			element = $(element);
			if (showHide == "show") {
				if (element.id.substring(0,7) == "toolbar") element.style.display = "block";
				element.style.visibility = "visible";
			} else if (showHide == "hide") {
				if (element.id.substring(0,7) == "toolbar") element.style.display = "none";
				element.style.visibility = "hidden";
			}
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function setRange(rte) {
	//function to store range of current selection
	try {
		var oRTE = $(rte);
		if (oRTE.contentWindow) {
			var oRTEDoc = oRTE.contentWindow.document;
			oRTE.contentWindow.focus();
		} else {
			var oRTEDoc = oRTE.document;
			oRTEDoc.focus();
		}
		
		if (document.all) {
			sel = oRTEDoc.selection;
			rng = sel.createRange();
			selectionText = rng.text.toString();
		} else if (document.getSelection) {
			rng = oRTEDoc.createRange();
			selectionText = oRTEDoc.getSelection();
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function stripHTML(oldString) {
	//function to strip all html
	try {
		var newString = oldString.replace(/(<([^>]+)>)/ig,"");
		
		//replace carriage returns and line feeds
	   newString = newString.replace(/\r\n/g," ");
	   newString = newString.replace(/\n/g," ");
	   newString = newString.replace(/\r/g," ");
		
		//trim string
		newString = trim(newString);
		
		return newString;
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function trim(sInString) {
	//removes leading and trailing spaces from the passed string
	try {
		sInString = sInString.replace(/^\s+/g, "");
		return sInString.replace(/\s+$/g, "");
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function cleanWordContent(wordContent) {
	//found at http://blogs.speerio.net/peerio/
//	wordDiv = document.createElement("DIV");
//	wordDiv.innerHTML = wordContent;
//	for (var i = 0; i < wordDiv.all.length; i++) {
//		wordDiv.all[i].removeAttribute("className","",0);
//		wordDiv.all[i].removeAttribute("style","",0);
//	}
//	wordContent = wordDiv.innerHTML;
	
	wordContent = String(wordContent).replace(/<\\?\?xml[^>]*>/g,"");
	wordContent = String(wordContent).replace(/<\/?o:p[^>]*>/g,"");
	wordContent = String(wordContent).replace(/<\/?v:[^>]*>/g,"");
	wordContent = String(wordContent).replace(/<\/?o:[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/&nbsp;/g,"");//<p>&nbsp;</p>
//	wordContent = String(wordContent).replace(/<\/?SPAN[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?FONT[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?STRONG[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?P[^>]*><\/P>/g,"");
//	wordContent = String(wordContent).replace(/<\/?H1[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?H2[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?H3[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?H4[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?H5[^>]*>/g,"");
//	wordContent = String(wordContent).replace(/<\/?H6[^>]*>/g,"");
	
	return wordContent;
}

function setHiddenVal(rte) {
	//set hidden form field value for current rte
	try {
		var oHdnField = $('hdn' + rte);
		if (oHdnField.value == null) oHdnField.value = "";
		
		var html = getHtmlSrc(rte);
		html = cleanWordContent(html);
		
		//if there is no content (other than formatting) set value to nothing
		if (stripHTML(html.replace("&nbsp;", " ")) == "" &&
			html.toLowerCase().search("<hr") == -1 &&
			html.toLowerCase().search("<img") == -1) html = "";
		
		oHdnField.value = html;
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function getHtmlSrc(rte) {
	try {
		var oRTE = document.getElementById(rte);
		if (oRTE.contentWindow) {
			var oRTEDoc = oRTE.contentWindow.document;
		} else {
			var oRTEDoc = oRTE.document;
		}
		return oRTEDoc.body.innerHTML;
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function setHtmlSrc(rte, html) {
	try {
		var oRTE = document.getElementById(rte);
		if (oRTE.contentWindow) {
			var oRTEDoc = oRTE.contentWindow.document;
		} else {
			var oRTEDoc = oRTE.document;
		}
		if (isIE) { //fix for IE
			var output = htmlEncode(html);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
			oRTEDoc.body.innerHTML = htmlDecode(output);
		} else {
			oRTEDoc.body.innerHTML = html;
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function htmlEncode(text) {
	return text.replace(/\&/ig,  '&amp;').replace(/\</ig,  '&lt;').replace(/\>/ig,  '&gt;').replace(/\"/ig,  '&quot;');
}

function htmlDecode(text) {
	return text.replace(/\&amp\;/ig,  '&').replace(/\&lt\;/ig,  '<').replace(/\&gt\;/ig,  '>').replace(/\&quot\;/ig,  '"');
}

// webkit.org webkit detection scripts
function parse_webkit_version(version) {
	try {
		var bits = version.split(".");
		var is_nightly = (version[version.length - 1] == "+");
		if (is_nightly) {
			var minor = "+";
		} else {
			var minor = parseInt(bits[1]);
			// If minor is Not a Number (NaN) return an empty string
			if (isNaN(minor)) {
				minor = "";
			}
		}
		return {major: parseInt(bits[0]), minor: minor, is_nightly: is_nightly};
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function get_webkit_version() {
	try {
		var regex = new RegExp("\\(.*\\) AppleWebKit/(.*) \\((.*)");
		var matches = regex.exec(navigator.userAgent);
		if (matches) {
			var webkit_version = parse_webkit_version(matches[1]);    
		} 
		return {major: webkit_version['major'], minor: webkit_version['minor'], is_nightly: webkit_version['is_nightly']};
	} catch (e) {
		//if (debugMode) alert(e);
	}
}

//********************
//Gecko-Only Functions
//********************
function geckoKeyPress(evt) {
	//function to add bold, italic, and underline shortcut commands to gecko RTEs
	//contributed by Anti Veeranna (thanks Anti!)
	try {
		var rte = evt.target.id;
		
		if (evt.ctrlKey) {
			var key = String.fromCharCode(evt.charCode).toLowerCase();
			var cmd = '';
			switch (key) {
				case 'b': cmd = "bold"; break;
				case 'i': cmd = "italic"; break;
				case 'u': cmd = "underline"; break;
			};
	
			if (cmd) {
				rteCommand(rte, cmd);
				
				// stop the event bubble
				evt.preventDefault();
				evt.stopPropagation();
			}
	 	}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

//*****************
//IE-Only Functions
//*****************
function evt_ie_keypress(event) {
	try {
		ieKeyPress(event, rte);
	} catch (e) {
		if (debugMode) alert(e);
	}
} 

function ieKeyPress(evt, rte) {
	try {
		var key = (evt.which || evt.charCode || evt.keyCode);
		var stringKey = String.fromCharCode(key).toLowerCase();
		
		//the following breaks list and indentation functionality in IE (don't use)
		//	switch (key) {
		//		case 13:
		//			//insert <br> tag instead of <p>
		//			//change the key pressed to null
		//			evt.keyCode = 0;
		//			
		//			//insert <br> tag
		//			currentRTE = rte;
		//			insertHTML('<br>');
		//			break;
		//	};
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function raiseButton(e) {
	try {
		var el = window.event.srcElement;
		
		className = el.className;
		if (className == 'rteImage' || className == 'rteImageLowered') {
			el.className = 'rteImageRaised';
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function normalButton(e) {
	try {
		var el = window.event.srcElement;
		
		className = el.className;
		if (className == 'rteImageRaised' || className == 'rteImageLowered') {
			el.className = 'rteImage';
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}

function lowerButton(e) {
	try {
		var el = window.event.srcElement;
		
		className = el.className;
		if (className == 'rteImage' || className == 'rteImageRaised') {
			el.className = 'rteImageLowered';
		}
	} catch (e) {
		if (debugMode) alert(e);
	}
}
