//init variables
var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;
var generateXHTML;

var lang = "en";
var encoding = "iso-8859-1";

var theRTE;

function initRTE(imgPath, incPath, css, genXHTML) {
	//set browser vars
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); 
	isGecko = (ua.indexOf("gecko") != -1);
	isSafari = (ua.indexOf("safari") != -1);
	isKonqueror = (ua.indexOf("konqueror") != -1);
	
	generateXHTML = genXHTML;
	
	//check to see if designMode mode is available
	//Safari/Konqueror think they are designMode capable even though they are not
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}
	
	if (isIE) {
		document.onmouseover = raiseButton;
		document.onmouseout  = normalButton;
		document.onmousedown = lowerButton;
		document.onmouseup   = raiseButton;
	}
	
	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
	
	if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');
	
	//for testing standard textarea, uncomment the following line
	//isRichText = false;
}

function writeRichText(rte, html, PGDText, width, height, buttons, readOnly, frameCharset, eViewSource, quoteOriginalButton) {
	
	theRTE = rte;
	
	if (isRichText) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;
		
		if (readOnly) buttons = false;
		
		//adjust minimum table widths
		if (isIE) {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width;
		} else {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width + 4;
		}

		//document.writeln('<div class="rteDiv2">');
		if (buttons) {
			document.writeln('<table cellpadding=0 cellspacing=0 id="Buttons1_' + rte + '" class="rteBar">');
			document.writeln('	<tr>');
			document.writeln('		<td nowrap>');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'removeformat.gif" width="21" height="20" alt="Remove Text Formatting" title="Remove Text Formatting" onClick="rteCommand(\'' + rte + '\', \'removeformat\', \'\')">');
			document.writeln('		</td>');	
			document.writeln('		<td nowrap>');		
			document.writeln('			<select class="rteSelect" id="fontname_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id)">');
			document.writeln('				<option value="Font" selected>Font Face</option>');
			
			var FontFaceCollection = new Array("Times New Roman","Arial","Verdana","Tahoma","Courier New","Trebuchet MS","Microsoft Sans Serif")
			for (var i = 0; i<FontFaceCollection.length; i++){
				document.writeln('				<option value="' + FontFaceCollection[i] + '">' + FontFaceCollection[i] + '</option>');
			}
			document.writeln('			</select>');
			document.writeln('			<select class="rteSelect" unselectable="on" id="fontsize_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);">');
			document.writeln('				<option value="Size">Size</option>');
			document.writeln('				<option value="1">1</option>');
			document.writeln('				<option value="2">2</option>');
			document.writeln('				<option value="3">3</option>');
			document.writeln('				<option value="4">4</option>');
			document.writeln('				<option value="5">5</option>');
			document.writeln('				<option value="6">6</option>');
			document.writeln('				<option value="7">7</option>');
			document.writeln('			</select>');
			document.writeln('		</td>');	
			document.writeln('		<td nowrap>');			
			document.writeln('		<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt="">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'code.gif" width="21" height="20" alt="Add [code] tag" title="Add [code] tag" onClick="surroundText(\'' + rte + '\',\'[code]\',\'[/code]\')">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'quote.gif" width="21" height="20" alt="Add [quote] tag" title="Add [quote] tag" onClick="surroundHTML(\'' + rte + '\',\'[quote]\',\'[/quote]\')">');
			if (quoteOriginalButton=='true') document.writeln('		<img class="rteImage" src="' + imagesPath + 'quoteOriginal.gif" width="21" height="20" alt="Quote Original" title="Quote Original" onClick="quoteOriginal(\'' + rte + '\')">');
			if (isIE) {
				document.writeln('		<img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="21" height="20" alt="Spell Check" title="Spell Check" onClick="checkspellIE()">');
			//} else {
				//document.writeln('		<img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="21" height="20" alt="Spell Check" title="Spell Check" onClick="checkspellMOZ('+ rte +')">');
			}			
			document.writeln('		</td>');
			//document.writeln('		<td width="100%"></td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
			document.writeln('<table cellpadding=0 cellspacing=0 id="Buttons2_' + rte + '" class="rteBar">');
			document.writeln('	<tr>');
			document.writeln('		<td nowrap colspan="3"><img class="rteImage" src="' + imagesPath + 'bold.gif" width="21" height="20" alt="Bold" title="Bold" onClick="rteCommand(\'' + rte + '\', \'bold\', null)">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'italic.gif" width="21" height="20" alt="Italic" title="Italic" onClick="rteCommand(\'' + rte + '\', \'italic\', \'\')">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'underline.gif" width="21" height="20" alt="Underline" title="Underline" onClick="rteCommand(\'' + rte + '\', \'underline\', \'\')">');
			document.writeln('		<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt="">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'left_just.gif" width="21" height="20" alt="Align Left" title="Align Left" onClick="rteCommand(\'' + rte + '\', \'justifyleft\', \'\')">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'centre.gif" width="21" height="20" alt="Center" title="Center" onClick="rteCommand(\'' + rte + '\', \'justifycenter\', \'\')">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'right_just.gif" width="21" height="20" alt="Align Right" title="Align Right" onClick="rteCommand(\'' + rte + '\', \'justifyright\', \'\')">');
			document.writeln('		<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt="">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'hr.gif" width="21" height="20" alt="Horizontal Rule" title="Horizontal Rule" onClick="rteCommand(\'' + rte + '\', \'inserthorizontalrule\', \'\')">');
			document.writeln('		<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt="">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'numbered_list.gif" width="21" height="20" alt="Ordered List" title="Ordered List" onClick="rteCommand(\'' + rte + '\', \'insertorderedlist\', \'\')">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'list.gif" width="21" height="20" alt="Unordered List" title="Unordered List" onClick="rteCommand(\'' + rte + '\', \'insertunorderedlist\', \'\')">');
			document.writeln('		<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt="">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'outdent.gif" width="21" height="20" alt="Outdent" title="Outdent" onClick="rteCommand(\'' + rte + '\', \'outdent\', \'\')">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'indent.gif" width="21" height="20" alt="Indent" title="Indent" onClick="rteCommand(\'' + rte + '\', \'indent\', \'\')">');
			document.writeln('		<img id="forecolor_' + rte + '" class="rteImage" src="' + imagesPath + 'textcolor.gif" width="21" height="20" alt="Text Color" title="Text Color" onClick="dlgColorPalette(\'' + rte + '\', \'forecolor\', \'\')">');
			document.writeln('		<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt="">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'hyperlink.gif" width="21" height="20" alt="Insert Link" title="Insert Link" onClick="addLinkSimple(\'' + rte + '\')">');
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'unlink.gif" width="21" height="20" alt="Remove Link" title="Remove Link" onClick="rteCommand(\'' + rte + '\', \'unlink\', null)">');			
			document.writeln('		<img class="rteImage" src="' + imagesPath + 'image.gif" width="21" height="20" alt="Add Image" title="Add Image" onClick="addImage(\'' + rte + '\')">');
			//document.writeln('		<td width="100%"></td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
		}

		document.writeln('<iframe id="' + rte + '" name="' + rte + '" style="width:' + width + 'px; height:' + height + 'px;" class="rteFrame" src=""></iframe>');

		if (!readOnly && eViewSource) document.writeln('<br /><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\',' + buttons + ');" />&nbsp;<label for="chkSrc' + rte + '">View Source</label>');
		
		build_palette(rte);
		
		document.getElementById('cp'+rte).onmouseover = function(){MouseOut(this)};
		
  		if (!document.all){
			document.getElementById(rte).contentWindow.document.addEventListener("mousedown", dismisscolorpalette, true);
			document.getElementById(rte).contentWindow.document.addEventListener("keypress", dismisscolorpalette, true);
		}
		
		document.writeln('<input type="hidden" id="hdn' + rte + '" name="wysiwyg_' + rte + '" value="">');
		document.getElementById('hdn' + rte).value = html;
		
		document.writeln('<input type="hidden" id="baseRef_' + rte + '" name="baseRef_' + rte + '" value="">');
		document.getElementById('baseRef_' + rte).value = location.href.substring(0,location.href.lastIndexOf("/")+1);
		//alert (document.getElementById('baseRef_' + rte).value);
		
		enableDesignMode(rte, html, readOnly, frameCharset);
		
	} else {
		if (!readOnly) {
			document.writeln('<textarea name="wysiwyg_' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + PGDText + '</textarea>');
		} else {
			document.writeln('<textarea name="wysiwyg_' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + PGDText + '</textarea>');
		}
	}
}

function dismisscolorpalette(){
	document.getElementById('cp'+this.id).style.visibility = 'hidden';
}

function dlgColorPalette(rte, command) {
	//function to display or hide color palettes
	setRange(rte);
	//get dialog position
	var oDialog = document.getElementById('cp' + rte);
	var buttonElement = document.getElementById(command + '_' + rte);
	var iLeftPos = getOffsetLeft(buttonElement);
	var iTopPos = getOffsetTop(buttonElement) + (buttonElement.offsetHeight);
	oDialog.style.left = (iLeftPos) + "px";
	oDialog.style.top = (iTopPos) + "px";
	
	if ((command == parent.command) && (rte == currentRTE)) {
		//if current command dialog is currently open, close it
		if (oDialog.style.visibility == "hidden") {
			showHideElement(oDialog, 'show');
		} else {
			showHideElement(oDialog, 'hide');
		}
	} else {
		//if opening a new dialog, close all others
		var vRTEs = allRTEs.split(";");
		for (var i = 0; i < vRTEs.length; i++) {
			showHideElement('cp' + vRTEs[i], 'hide');
		}
		showHideElement(oDialog, 'show');
	}
	
	//save current values
	parent.command = command;
	currentRTE = rte;
}

var colorPaletteTimeout ;

function MouseOut(obj){
	obj.onmouseout=function(){ Obj=this; colorPaletteTimeout=setTimeout('Obj.style.visibility=\'hidden\'',250); }
	obj.onmouseover=function(){ clearTimeout(colorPaletteTimeout); }
}

function build_palette(rte){
		document.writeln('<div style="width:200px;height:365px; overflow:auto; margin:1px; padding:1px; border:2px solid #CCCCCC; visibility:hidden; position: absolute; top:0px;left:0px" id="cp' + rte + '">');
		document.writeln('<table width="100%" cellpadding="0" cellspacing="0" align="center">');
		document.writeln('	<tr>');
		document.writeln('		<td>');
		document.writeln('			<table width="100%" cellpadding="0" cellspacing="0" align="center">');
		var colorPalette = new Array("00","33","66","99","CC","FF")
		for (var r_counter=0; r_counter<colorPalette.length; r_counter++){
			document.writeln('	<tr>');
			for (var g_counter=0; g_counter<colorPalette.length; g_counter++){
				for (var b_counter=0; b_counter<colorPalette.length; b_counter++){
					document.writeln('<td id="#' + colorPalette[r_counter] + colorPalette[g_counter] + colorPalette[b_counter] + '" style="border:1px solid #E2E2E2;" bgcolor="#' + colorPalette[r_counter] + colorPalette[g_counter] + colorPalette[b_counter] + '" height="10" onclick="setColor(this.id)" onmouseover="this.style.border = \'1px dotted white\'"  onmouseout="this.style.border = \'1px solid #E2E2E2\'"><img width="1" height="1"></td>')
				}	
				document.writeln('	</tr>');		
			}
		}
		document.writeln('			</table>');
		document.writeln('		</td>');
		document.writeln('	</tr>');
		document.writeln('</table>');
		document.writeln('</div>');
}

function enableDesignMode(rte, html, readOnly, frameCharset) {
	var frameHtml = "<html id=\"" + rte + "\">\n";
	frameHtml += "<head>\n";
	//to reference your stylesheet, set href property below to your stylesheet path and uncomment
	if (cssFile.length > 0) {
		frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
	} else {
		frameHtml += "<style>\n";
		frameHtml += "body {\n";
		frameHtml += "	background: #FFFFFF;\n";
		frameHtml += "	margin: 1px;\n";
		frameHtml += "	padding: 1px;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
	}
	//frameHtml += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + frameCharset + "\">\n";
	
	frameHtml += "<style>p {margin:0px;}</style></head>\n";
	frameHtml += "<body class='msg'>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";
	
	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) {
			oRTE.designMode = "On";
			frames[rte].document.attachEvent("onkeypress", function evt_ie_keypress(event) {ieKeyPress(event,rte);});
			//oRTE.onkeypress = function(){testKeyPress(event) ;}
		}
	} else {
		try {
			if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try {
				var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if (isGecko && !readOnly) {
					//attach a keyboard handler for gecko browsers to make keyboard shortcuts work
					oRTE.addEventListener("keypress", geckoKeyPress, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
}

function updateRTE(rte) {
	if (!isRichText) return;
	
	//check for readOnly mode
	var readOnly = false;
	if (document.all) {
		if (frames[rte].document.designMode != "On") readOnly = true;
	} else {
		if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
	}
	
	if (isRichText && !readOnly) {
		//if viewing source, switch back to design view
		if (document.getElementById("chkSrc" + rte)){
		if (document.getElementById("chkSrc" + rte).checked) document.getElementById("chkSrc" + rte).click();}
		setHiddenVal(rte);
	}
}

function setHiddenVal(rte) {
	//set hidden form field value for current rte
	var oHdnField = document.getElementById('hdn' + rte);
	if (oHdnField.value == null) oHdnField.value = "";
	if (document.all) {
		oHdnField.value = frames[rte].document.body.innerHTML;
	} else {
		oHdnField.value = document.getElementById(rte).contentWindow.document.body.innerHTML;
	}
	
	//if there is no content (other than formatting) set value to nothing
	if (stripHTML(oHdnField.value.replace("&nbsp;", " ")) == "" &&
		oHdnField.value.toLowerCase().search("<hr") == -1 &&
		oHdnField.value.toLowerCase().search("<img") == -1) oHdnField.value = "";
}

function updateRTEs() {
	var vRTEs = allRTEs.split(";");
	for (var i = 0; i < vRTEs.length; i++) {
		updateRTE(vRTEs[i]);
	}
}

function rteCommand(rte, command, option) {
	//function to perform command
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		oRTE.document.execCommand("useCSS", false, true);
	}
	
	try {
		oRTE.focus();
	  	oRTE.document.execCommand(command, false, option);
		oRTE.focus();
	} catch (e) {
//		alert(e);
//		setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 10);
	}
}

function toggleHTMLSrc(rte, buttons) {
	//contributed by Bob Hutzel (thanks Bob!)
	var oHdnField = document.getElementById('hdn' + rte);
	
	if (document.getElementById("chkSrc" + rte).checked) {
		//we are checking the box
		if (buttons) {
			showHideElement("Buttons1_" + rte, "hide");
			showHideElement("Buttons2_" + rte, "hide");
		}
		setHiddenVal(rte);
		if (document.all) {
			frames[rte].document.body.innerText = oHdnField.value;
		} else {
			var oRTE = document.getElementById(rte).contentWindow.document;
			var htmlSrc = oRTE.createTextNode(oHdnField.value);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		//we are unchecking the box
		if (buttons) {
			showHideElement("Buttons1_" + rte, "show");
			showHideElement("Buttons2_" + rte, "show");
		}
		if (document.all) {
			//fix for IE
			var output = escape(frames[rte].document.body.innerText);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
			frames[rte].document.body.innerHTML = unescape(output);
		} else {
			var oRTE = document.getElementById(rte).contentWindow.document;
			var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
	}
}

function setColor(color) {
	//function to set color
	var rte = currentRTE;
	var parentCommand = parent.command;
	
	if (document.all) {
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		
		//retrieve selected range
		rng.select();
	}
	
	rteCommand(rte, parentCommand, color);
	showHideElement('cp' + rte, "hide");
}

function addLinkSimple(rte) {
	//function to add link
	var	linkURL = prompt('Enter URL:', 'http://');
	if ((linkURL != null) && (linkURL != "")) {
		var rng = setRange(rte);
		if (document.all) rng = rng.text;
		currentRTE = rte;
		if (rng == "") {
			rng = linkURL;
			insertHTML('<a href="' + linkURL + '">' + rng + '</a>');
		} else {
			rteCommand(rte, 'CreateLink', linkURL);
		}
	}
}

function addImage(rte) {
	//function to add image
	imagePath = prompt('Enter Image URL:', 'http://');				
	if ((imagePath != null) && (imagePath != "")) {
		rteCommand(rte, 'InsertImage', imagePath);
	}
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;

	while(mOffsetParent != document.body) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent != document.body) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetLeft;
}

function selectFont(rte, selectname) {
	//function to handle font changes
	var idx = document.getElementById(selectname).selectedIndex;
	// First one is always a label
	if (idx != 0) {
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + rte, '');
		rteCommand(rte, cmd, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function addSelectedText(rte,smText){
	currentRTE = rte;
	//alert(smText);
	insertHTML(smText.replace(/\r\n/g,"<br>").replace(/\n/g,"<br>").replace(/\r/g,"<br>"));
}

function quoteOriginal(rte){
	if (document.postform){
		if (document.postform.quote.value!=""){
			addSelectedText(rte,document.postform.quote.value);
			document.postform.quote.value = "";
		}
	}
}

function addSmiley(rte, smSrc){
	if (isIE){
		currentRTE = rte;
		insertHTML('<img src="' + smSrc + '">');
	} else {
		rteCommand(rte, 'InsertImage', smSrc);
	}
}

function surroundHTML(rte,openTag,closeTag){ // wrap opening and ending tag around selection as HTML
	insertHTML(openTag + grabSelection(rte) + closeTag);
}

function surroundText(rte,openTag,closeTag){ // wrap opening and ending tag around selection as TEXT
	var text = grabSelection(rte).replace(/(\r|\n)/gi,"").replace(/<br>/gi,"\r\n").replace(/<[^>]*>/gi,"").replace(/\r\n/gi,"<br>");
	insertHTML(openTag + "<br>" + text + closeTag);
}

function grabSelection(rte){ // return selection HTML as String
	currentRTE = rte;
	var rng;
	if (isIE) {
		var rng = setRange(rte);
		rng = rng.htmlText;
		rng = rng.replace(/<\/p>/gi,"<br>").replace(/<p>/gi,"");
	} else {	
		rng = moz_read_selection_html(rte);
	}
	return rng;
}

function moz_read_selection_html(rte){
	var selection = document.getElementById(rte).contentWindow.getSelection();
	var rngHTML = selection.getRangeAt(0).cloneContents();
	var div = document.createElement('div');
	div.appendChild(rngHTML);
	return div.innerHTML;
}

function insertHTML(html) {
	//function to add HTML -- thanks dannyuk1982
	var rte = currentRTE;
	
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	oRTE.focus();
	if (document.all) {
		var oRng = oRTE.document.selection.createRange();
		oRng.pasteHTML(html);
		oRng.collapse(false);
		oRng.select();
	} else {
		oRTE.document.execCommand('insertHTML', false, html);
	}
}

function setRange(rte) {
	//function to store range of current selection
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		var selection = oRTE.document.selection; 
		if (selection != null) rng = selection.createRange();
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	return rng;
}

function showHideElement(element, showHide) {
	//function to show or hide elements
	//element variable can be string or object
	if (document.getElementById(element)) {
		element = document.getElementById(element);
	}

	if (showHide == "show") {
		element.style.visibility = "visible";
	} else if (showHide == "hide") {
		element.style.visibility = "hidden";
	}

}

function stripHTML(oldString) {
	//function to strip all html
	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;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
	
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length - 1, retValue.length);
	
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length - 1);
      ch = retValue.substring(retValue.length - 1, retValue.length);
   }
	
	// Note that there are two spaces in the string - look for multiple spaces within the string
   while (retValue.indexOf("  ") != -1) {
		// Again, there are two spaces in each of the strings
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
   }
   return retValue; // Return the trimmed string back to the user
}

//********************
//Gecko-Only Functions
//********************
function geckoKeyPress(evt) {
	//function to add bold, italic, and underline shortcut commands to gecko RTEs
	//contributed by Anti Veeranna (thanks Anti!)
	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, null);
			
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

//*****************
//IE-Only Functions
//*****************
function ieKeyPress(evt, rte) {
	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;
	};	
}

function checkspellIE() {
	//function to perform spell check
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		} else {
			alert("Error Loading ieSpell: Exception " + exception.number);
		}
	}
}

function checkspellMOZ(rte){
	SpellBound.checkSpellingAll();//(document.getElementById(rte).contentWindow.document.getElementsByTagName('body')[0]);	
}

function raiseButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageLowered') {
		el.className = 'rteImageRaised';
	}
}

function normalButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImageRaised' || className == 'rteImageLowered') {
		el.className = 'rteImage';
	}
}

function lowerButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageRaised') {
		el.className = 'rteImageLowered';
	}
}
