// Cross-Browser Rich Text Editor
// http://www.kevinroth.com/rte/demo.htm
// Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM)

//init variables
var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;
var g_contentPath;
var g_anchors_outside_content_cell;

var imagesPath;
var includesPath;
var cssFile;
var parentCommand;

// ifdef VISTA
var hiddenBorderStyleTag = '<style id="vistaTempBorder">td { border: 1px dashed #999999; border-spacing: 1px; } table { border: 2px solid #CCCCCC; }</style>';
var editContentTag = '<script id="vistaFlag" language="JavaScript">document.EditContent = 1</script>';
var heightDifference;
var currentSelection;
var imageHost;
var showPromo;
var promoWin;
var pUp;
var found_anchor = false;
// endif

function initRTE(imgPath, incPath, css, userImageHost, promo, body) {
	//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);

	//check to see if designMode mode is available
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}

	if (!isIE) document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT | Event.MOUSEDOWN | Event.MOUSEUP);
	document.onmouseover = raiseButton;
	document.onmouseout  = normalButton;
	document.onmousedown = lowerButton;
	document.onmouseup   = raiseButton;

	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
	imageHost = userImageHost;
	showPromo = promo;

	if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');

	//for testing standard textarea, uncomment the following line
	//isRichText = false;

}

// ifdef VISTA

function resizeRTE(rte) {
	var height;
	var oRTE;

	if (isIE) {
		height = document.body.offsetHeight - heightDifference;
	} else {
		height = window.innerHeight - heightDifference;
	}
	if (height < (heightDifference / 2)) {
		height = (heightDifference / 2);
	}

	if (oRTE = document.getElementById(rte)) {
		oRTE.style.height = height;
	}
}
// endif

function writeRichText(rte, html, width, height, buttons, readOnly, contentPath) {

	g_contentPath = contentPath;
// ifdef VISTA
	if (height < 0) {
		heightDifference = -1 * height;

		if (isIE) {
			height = document.body.offsetHeight - heightDifference;
		} else {
			height = window.innerHeight - heightDifference;
		}
		if (height < (heightDifference / 2)) {
			height = (heightDifference / 2);
		}
	}
// endif

	if (isRichText) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;
		writeRTE(rte, html, width, height, buttons, readOnly);
	} else {
		writeDefault(rte, html, width, height, buttons, readOnly);
	}

	if (document.all) {
		oRTE = frames[rte].document;

		var selection = oRTE.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;

		var selection = document.getElementById(rte).contentWindow.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	currentSelection = rng;
	
	if (oRTE.focus)
		oRTE.focus();

	if (rng.select)
		rng.select();

}

function writeDefault(rte, html, width, height, buttons, readOnly) {
	if (!readOnly) {
		document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
	} else {
		document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>');
	}
}

function raiseButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}
}

function normalButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}

	className = el.className;
	state = el.state;
	if (className == 'rteImageRaised' || className == 'rteImageLowered') {
		if (state == 'active')
			el.className = 'rteImageLowered';
		else
			el.className = 'rteImage';
	}
}

function lowerButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}

	className = el.className;
	if ((className == 'rteImage' || className == 'rteImageRaised') && el.state != 'disabled') {
		el.className = 'rteImageLowered';
	}
}

function writeRTE(rte, html, width, height, buttons, readOnly) {
	if (readOnly) buttons = false;
	
	//adjust minimum table widths
	if (isIE) {
		if (buttons && (width < 600)) width = 600;
		var tablewidth = width;
	} else {
		if (buttons && (width < 500)) width = 500;
		var tablewidth = width + 4;
	}
	
	if (buttons == true) {
		document.writeln('<div id=\"anchorPosition\" style=\"position:relative; visibility:hidden;\"></div>');
		document.writeln('<div id=\"anchorPositionIE\" style=\"position:absolute; visibility:hidden;\"></div><div id="anchorPopup" style="position: absolute; z-index: 30; visibility: hidden;">');
		document.writeln('<table border="1" style="border: 1px solid black;" cellspacing="0" cellpadding="0" class="alertpopup"><tr><td bgcolor="#FFFFFF">&nbsp;<a id=anchorDisplayName></a>&nbsp;</td></tr></table></div>');
		document.writeln('<table class="rteBack" cellpadding=0 cellspacing=0 id="Buttons1_' + rte + '" width="' + tablewidth + '">');
		document.writeln('	<tr>');
		if (!isGecko) { // XPConnect exception if we try to cut, copy or paste
			document.writeln('		<td><img class="rteImage" id="cut" src="' + imagesPath + 'cut.gif" width="23" height="22" alt="Cut" title="Cut" onClick="FormatText(\'' + rte + '\', \'cut\')"></td>');
			document.writeln('		<td><img class="rteImage" id="copy" src="' + imagesPath + 'copy.gif" width="23" height="22" alt="Copy" title="Copy" onClick="FormatText(\'' + rte + '\', \'copy\')"></td>');
			document.writeln('		<td><img class="rteImage" id="paste" src="' + imagesPath + 'paste.gif" width="23" height="22" alt="Paste" title="Paste" onClick="FormatText(\'' + rte + '\', \'paste\')"></td>');
			document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
		}
		document.writeln('		<td><img class="rteImage" id="undo" src="' + imagesPath + 'undo.gif" width="23" height="22" alt="Undo" title="Undo" onClick="FormatText(\'' + rte + '\', \'undo\')"></td>');
		document.writeln('		<td><img class="rteImage" id="redo" src="' + imagesPath + 'redo.gif" width="23" height="22" alt="Redo" title="Redo" onClick="FormatText(\'' + rte + '\', \'redo\')"></td>');
//		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
//		document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'find.gif" width="23" height="22" alt="Find" title="Find" onClick="locate(\'' + rte + '\')"></td>');
		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
		document.writeln('		<td><img class="rteImage" id="justifyleft" src="' + imagesPath + 'justifyleft.gif" width="23" height="22" alt="Align Left" title="Align Left" onClick="FormatText(\'' + rte + '\', \'justifyleft\', \'\')"></td>');
		document.writeln('		<td><img class="rteImage" id="justifycenter" src="' + imagesPath + 'justifycenter.gif" width="23" height="22" alt="Center" title="Center" onClick="FormatText(\'' + rte + '\', \'justifycenter\', \'\')"></td>');
		document.writeln('		<td><img class="rteImage" id="justifyright" src="' + imagesPath + 'justifyright.gif" width="23" height="22" alt="Align Right" title="Align Right" onClick="FormatText(\'' + rte + '\', \'justifyright\', \'\')"></td>');
		document.writeln('		<td><img class="rteImage" id="justifyfull" src="' + imagesPath + 'justifyfull.gif" width="23" height="22" alt="Justify Full" title="Justify Full" onclick="FormatText(\'' + rte + '\', \'justifyfull\', \'\')"></td>');
		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
		document.writeln('		<td><img class="rteImage" id="inserthorizontalrule" src="' + imagesPath + 'inserthorizontalrule.gif" width="23" height="22" alt="Horizontal Rule" title="Horizontal Rule" onClick="FormatText(\'' + rte + '\', \'inserthorizontalrule\', \'\')"></td>');
		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
		document.writeln('		<td><img id="insertorderedlist" class="rteImage" src="' + imagesPath + 'insertorderedlist.gif" width="23" height="22" alt="Ordered List" title="Ordered List" onClick="FormatText(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>');
		document.writeln('		<td><img id="insertunorderedlist" class="rteImage" src="' + imagesPath + 'insertunorderedlist.gif" width="23" height="22" alt="Unordered List" title="Unordered List" onClick="FormatText(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>');
		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
		document.writeln('		<td><img id = "outdent" class="rteImage" src="' + imagesPath + 'outdent.gif" width="23" height="22" alt="Outdent" title="Outdent" onClick="FormatText(\'' + rte + '\', \'outdent\', \'\')"></td>');
		document.writeln('		<td><img id="indent" class="rteImage" src="' + imagesPath + 'indent.gif" width="23" height="22" alt="Indent" title="Indent" onClick="FormatText(\'' + rte + '\', \'indent\', \'\')"></td>');
		if (spellInstalled()) {
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="23" height="22" alt="Spell Check" title="Spell Check" onClick="checkspell()"></td>');
		}
		if (showPromo) {
		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td nowrap><a href="#" onClick="FormatText(\'' + rte + '\', \'insertpromo\', \'\')" style="text-decoration:none">Insert Promo Code&hellip;</a></td>');
		}
		document.writeln('		<td width="100%">');
		document.writeln('		</td>');
		document.writeln('	</tr>');
		document.writeln('</table>');
		document.writeln('<table class="rteBack" cellpadding="0" cellspacing="0" id="Buttons2_' + rte + '" width="' + tablewidth + '">');
		document.writeln('	<tr>');
		document.writeln('		<td>');
		document.writeln('			<select unselectable="on" id="formatblock_' + rte + '" onclick="focusRTE(\'' + rte + '\')" onchange="Select(\'' + rte + '\', this.id);">');	
		document.writeln('				<option value="">Style</option>');
		document.writeln('				<option value="<p>">Paragraph</option>');
		document.writeln('				<option value="<h1>">Heading 1 <h1></option>');
		document.writeln('				<option value="<h2>">Heading 2 <h2></option>');
		document.writeln('				<option value="<h3>">Heading 3 <h3></option>');
		document.writeln('				<option value="<h4>">Heading 4 <h4></option>');
		document.writeln('				<option value="<pre>">Formatted <pre></option>');
		document.writeln('			</select>');
		document.writeln('		</td>');
		document.writeln('		<td>');
		document.writeln('			<select unselectable="on" id="fontname_' + rte + '" onclick="focusRTE(\'' + rte + '\')" onchange="Select(\'' + rte + '\', this.id)">');
		document.writeln('				<option value="">Font</option>');
		document.writeln('				<option value="arial">Arial</option>');
		document.writeln('				<option value="courier">Courier New</option>');
		document.writeln('				<option value="times new roman">Times New Roman</option>');
		document.writeln('				<option value="verdana">Verdana</option>');
		document.writeln('			</select>');
		document.writeln('		</td>');
		document.writeln('		<td>');
		document.writeln('			<select unselectable="on" id="fontsize_' + rte + '" onclick="focusRTE(\'' + rte + '\')" onchange="Select(\'' + rte + '\', this.id);">');
		document.writeln('				<option value="">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><img class="rteImage" id="bold" src="' + imagesPath + 'bold.gif" width="23" height="22" alt="Bold" title="Bold" onClick="FormatText(\'' + rte + '\', \'bold\', \'\')"></td>');
		document.writeln('		<td><img class="rteImage" id="italic" src="' + imagesPath + 'italic.gif" width="23" height="22" alt="Italic" title="Italic" onClick="FormatText(\'' + rte + '\', \'italic\', \'\')"></td>');
		document.writeln('		<td><img class="rteImage" id="underline" src="' + imagesPath + 'underline.gif" width="23" height="22" alt="Underline" title="Underline" onClick="FormatText(\'' + rte + '\', \'underline\', \'\')"></td>');
		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
		document.writeln('		<td><div id="forecolor_' + rte + '"><img id="forecolor" class="rteImage" src="' + imagesPath + 'forecolor.gif" width="23" height="22" alt="Text Color" title="Text Color" onClick="FormatText(\'' + rte + '\', \'forecolor\', \'\')"></div></td>');
		document.writeln('		<td><div id="backcolor_' + rte + '"><img id="backcolor" class="rteImage" src="' + imagesPath + 'backcolor.gif" width="23" height="22" alt="Background Color" title="Text Hilite Color" onClick="FormatText(\'' + rte + '\', \'backcolor\', \'\')"></div></td>');
		document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
		document.writeln('		<td><img id="createlink" class="rteImage" src="' + imagesPath + 'createlink.gif" width="23" height="22" alt="Insert Link" title="Insert Link" onClick="FormatText(\'' + rte + '\', \'createlink\')"></td>');
		document.writeln('		<td><img id="unlink" class="rteImage" src="' + imagesPath + 'unlink.gif" width="23" height="22" alt="Remove Link" title="Remove Link" onClick="FormatText(\'' + rte + '\', \'unlink\')"></td>');
		document.writeln('		<td><div id="addanchor_' + rte + '"><img id="addanchor" class="rteImage" src="/rte/images/anchor_editor.gif" width="16" height="17" alt="Add New Anchor" title="Add New Anchor" onClick="FormatText(\'' + rte + '\', \'addanchor\', \'\')"></div></td>');
		document.writeln('		<td><img id="attachfile" class="rteImage" src="' + imagesPath + 'attachfile.gif" width="23" height="22" alt="Attach File" title="Attach File" onClick="FormatText(\'' + rte + '\', \'attachfile\')"></td>');
		document.writeln('		<td><img id="insertimage" class="rteImage" src="' + imagesPath + 'insertimage.gif" width="23" height="22" alt="Add Image" title="Add Image" onClick="FormatText(\'' + rte + '\', \'insertimage\')"></td>');
		document.writeln('		<td><div id="inserttable_' + rte +'"><img id="inserttable" class="rteImage" src="' + imagesPath + 'inserttable.gif" width="23" height="22" alt="Add Table" title="Add Table" onClick="FormatText(\'' + rte + '\', \'inserttable\')"></div></td>');
		if (!showPromo) {
			document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td nowrap><a href="javascript:FormatText(\'' + rte + '\', \'insertfield\')" style="text-decoration:none">Insert Field&hellip;</a></td>');
		}
		document.writeln('		<td width="100%"></td>');
		document.writeln('	</tr>');
		document.writeln('</table>');
	}
	document.writeln('<iframe id="' + rte + '" name="' + rte + '" width="' + width + 'px" height="' + height + 'px"></iframe>');
	document.writeln('<div id="contextMenu' + rte + '" src="/rte/menu.html" marginwidth="0" marginheight="0" style="border: 1px solid black; visibility: hidden; display: none;"></div>');
	if (!readOnly) document.writeln('<br /><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" />&nbsp;View Source');
	if (!readOnly) document.writeln('<input type="checkbox" id="chkTDB' + rte + '" onclick="toggleTDBorders(\'' + rte + '\');" checked />&nbsp;Show Hidden Elements');
	document.writeln('<iframe width="154" height="160" id="cp' + rte + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>');
// ifdef VISTA
	document.writeln('<iframe width="430" height="235" id="link' + rte + '" src="' + includesPath + 'links.php" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>');
	document.writeln('<iframe width="300" height="100" id="addanchor' + rte + '" src="' + includesPath + 'addanchor.php" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>');
	document.writeln('<iframe width="400" height="350" id="picker' + rte + '" src="/upload/picker.php" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>');
	document.writeln('<iframe width="300" height="80" id="fields' + rte + '" src="/rte/fields.php" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>');
	document.writeln('<iframe width="180" height="100" id="table' + rte + '" src="/rte/table.html" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>');
// endif
	document.writeln('<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="">');
	document.getElementById('hdn' + rte).value = html;

	enableDesignMode(rte, html, readOnly);

}

function enableDesignMode(rte, html, readOnly) {
	var frameHtml;
	var pattern = /<body/i;

	if (pattern.test(html)) {
		frameHtml = editContentTag;
		frameHtml += html + hiddenBorderStyleTag;
	} else {
		frameHtml = "<html id=\"" + rte + "\">\n";
		frameHtml += "<head>\n";
		//to reference your stylesheet, set href property below to your stylesheet path and uncomment
		frameHtml += "</head>\n";
		frameHtml += editContentTag;
		frameHtml += "<body id=\"vistaDummyBody\">\n";
		frameHtml += html + "\n";
		frameHtml += hiddenBorderStyleTag;
		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";
	} 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", kb_handler, true);
					oRTE.addEventListener("click", callUpdateToolbars, true);
					oRTE.addEventListener("contextmenu", showContextMenu, true);
					oRTE.addEventListener("mouseover", callOnMouseOver, true);
					oRTE.addEventListener("dblclick", callOnDoubleClick, 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;
			}
		}
	}
		  	
	if (document.all) {
		oRTE = frames[rte].document;
		oRTE.onselectionchange = callUpdateToolbars;
		oRTE.oncontextmenu = showContextMenu;
		oRTE.onmouseover = callOnMouseOver;
		oRTE.ondblclick = callOnDoubleClick;
	}
}

function showContextMenu(e) {
	var rte = 'userHTML';
	var oRTE =  document.getElementById(rte);;
	var menuDiv = document.getElementById('contextMenu' + rte);

	var pElement;
	var isTD = false;
	var menuHTML = '';
	if (isIE) {
		if (pUp == null)
			pUp = window.createPopup();

		pElement = pUp.document.body;
		pUp.document.createStyleSheet('/rte/rte.css');
	} else {
		if (pUp == null) {
			pUp = document.createElement('DIV');
			document.body.appendChild(pUp);
			pUp.style.position = 'absolute';
			pUp.style.visibility = 'hidden';
			pUp.style.display = 'none';
			pUp.id = 'contextMenu' + rte;
		}
		pElement = pUp;
	}
	
	if (isIE) {
		e = oRTE.contentWindow.event;
		var xPos = e.x + getOffsetLeft(oRTE);
		var yPos = e.y + getOffsetTop(oRTE);
	} else {
		var xPos = e.clientX + getOffsetLeft(oRTE);
		var yPos = e.clientY + getOffsetTop(oRTE);
	}

	if (document.all) {
		var myRTE = frames(rte);
		var selection = myRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
		var isAnchor = false;

		if (selection.type != 'Control') {
			// Walk up the DOM tree to try and find a TD. Then stop.
			for (var el = rng.parentElement(); el != null && el.tagName != 'TD' && el.parentNode; el = el.parentNode);
			isTD = (el.tagName == 'TD');
		}
		else {
			var parent = rng.item(0).parentElement;
			if (parent.tagName == 'A') {
				if (parent.className == 'vistaanchor') {
					isAnchor = true;
				}
			}

		}

		if (isTD) {
			var table = el.parentNode.parentNode.parentNode;
			var tableBorder = table.border;
			var tableWidth = table.width;
		}
	} else {
		myRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = myRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
		// Walk up the DOM tree to try and find a TD. Then stop.
		for (var el = rng.commonAncestorContainer; el && el.tagName != 'TD' && el.parentNode; el = el.parentNode);
		isTD = el.tagName == 'TD';

		for (var el = rng.commonAncestorContainer; el && el.tagName != 'TD' && el.parentNode; el = el.parentNode)
		{
			if (el.className == 'vistaanchor')
				isAnchor = true;
		}

		if (isTD) {
			var table = rng.commonAncestorContainer.parentNode.parentNode.parentNode.parentNode;
			var tableBorder = table.border;
			var tableWidth = table.width;
		}
	}

	var menuTable = document.createElement('TABLE');
	menuTable.cellspacing = 0;
	menuTable.cellpadding = 1;
	menuTable.style.border = '1px solid black';
	menuTable.id = 'menu';
	var menuTBody = document.createElement('TBODY');
	menuTable.appendChild(menuTBody);

	if (isGecko) { // XPConnect exception when we try to cut, copy or paste
		var commands = ['Undo', 'Redo', '', 'insertimage'];
	} else {
		var commands = ['Cut', 'Copy', 'Paste', '', 'Undo', 'Redo', '', 'insertimage'];
	}

	if (isTD) {
		commands = commands.concat(['', 'toggleborder', 'togglewidth', '', 'addcell', 'delcell', '', 'addrow', 'delrow', '', 'addcol', 'delcol']);
	}

	if (isAnchor) {
		commands = ['Cut', 'Copy', 'Paste', '', 'Undo', 'Redo', '', 'modifyanchor'];
	}

	for (var i = 0; i < commands.length; i ++) {
		var commandLabel, enabled = true;
		switch (commands[i]) {
			case 'insertimage':
				commandLabel = 'Insert Image&hellip;';
				enabled = oRTE.contentWindow.document.queryCommandEnabled('insertimage');
				break;
			case 'toggleborder':
				if (tableBorder == 1)
					commandLabel = 'Turn off Border';
				else
					commandLabel = 'Turn on Border';
				break;
			case 'togglewidth':
				if (tableWidth == '100%')
					commandLabel = 'Auto Width';
				else
					commandLabel = 'Full Width';
				break;
			case 'addcell':
				commandLabel = 'Insert Cell';
				enabled = isTD;
				break;
			case 'delcell':
				commandLabel = 'Delete Cell';
				enabled = isTD;
				break;
			case 'addrow':
				commandLabel = 'Insert Row';
				enabled = isTD;
				break;
			case 'delrow':
				commandLabel = 'Delete Row';
				enabled = isTD;
				break;
			case 'addcol':
				commandLabel = 'Insert Column';
				enabled = isTD;
				break;
			case 'delcol':
				commandLabel = 'Delete Column';
				enabled = isTD;
				break;
			case '':			case '':
				commandLabel = '<hr noshade=1 style="margin: 2px;" color="gray">';
				enabled = false;
				break;
			case 'modifyanchor':
				commandLabel = 'Properties';
				enabled = isAnchor;
				break;
			default:
				commandLabel = commands[i];
				enabled = oRTE.contentWindow.document.queryCommandEnabled(commands[i]);
				break;
		}
		var menuCell = document.createElement('TD');

		if (enabled) {
			menuCell.innerHTML = commandLabel;
			menuCell.id = commands[i];
			menuCell.className = 'menuItem';
			menuCell.unselectable = 'on';
			menuCell.nowrap = 1;
			if (isIE) {
				menuCell.onmouseover = "this.className = 'menuOver';";
				menuCell.onmouseout = "this.className = 'menuItem';";
				menuCell.onclick = "parent.clickMenu(this.id);";
			} else {
				menuCell.onmouseover = menuOver;
				menuCell.onmouseout = menuOut;
				menuCell.onclick = menuClick;
			}
		} else {
			menuCell.innerHTML = commandLabel;
			menuCell.className = 'menuDisabled';
			menuCell.unselectable = 'on';
			menuCell.nowrap = 1;
		}

		var menuRow = document.createElement('TR');
		menuRow.appendChild(menuCell);
		menuTBody.appendChild(menuRow);
	}

	if (isIE) {
		pElement.innerHTML = menuTable.outerHTML;
	} else {
		pElement.innerHTML = '';
		pElement.appendChild(menuTable);
	}

	pElement.oncontextmenu = function() { return false; };

	if (isIE) {
		var menuElement = pUp.document.getElementById('menu');
		pUp.show(xPos, yPos, 0, 0, document.body);
		pUp.show(xPos, yPos, menuElement.offsetWidth, menuElement.offsetHeight, document.body);
	} else {
		pElement.style.left = xPos;
		pElement.style.top = yPos;
		pElement.style.visibility = 'visible';
		pElement.style.display = 'inline';
	}

	if (isIE)
		return false;
	else
		e.stopPropagation();
}

function menuOver(e) {
	e.target.className = 'menuOver';
}

function menuOut(e) {
	e.target.className = 'menuItem';
}

function menuClick(e) {
	clickMenu(e.target.id);
}

function clickMenu(command) {
	var rte = 'userHTML';
	var oRTE =  document.getElementById(rte);

	if (!document.all) {
		var selection = oRTE.contentWindow.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	try {
		switch (command) {
			case 'insertimage':
				FormatText(rte, 'insertimage', '', false);
				break;
			case 'addcell':
			case 'delcell':
			case 'addrow':
			case 'delrow':
			case 'addcol':
			case 'delcol':
			case 'toggleborder':
			case 'togglewidth':
				FormatTable(rte, command);
				break;
			case 'modifyanchor':
				FormatText(rte, 'addanchor', '', false);
				break;
			default:
				oRTE.contentWindow.document.execCommand(command, '', false);
				break;
		}
	} catch (e) {
		alert(e);
	}

	if (isIE) {
		pUp.hide();
	} else {
		var menuDiv = pUp; //document.getElementById('contextMenu' + rte);
		
		menuDiv.style.visibility = 'hidden';
		menuDiv.style.display = 'none';
	}
}

function updateRTEs() {
	var vRTEs = allRTEs.split(";");
	for (var i = 0; i < vRTEs.length; i++) {
		updateRTE(vRTEs[i]);
	}
}

function updateRTE(rte) {
	if (!isRichText) return;

	//set message value
	var oHdnMessage = document.getElementById('hdn' + rte);
	var oRTE = document.getElementById(rte);
	var readOnly = false;

	//check for readOnly mode
	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).checked) {
			document.getElementById("chkSrc" + rte).checked = false;
			toggleHTMLSrc(rte);
		}

		if (document.getElementById("chkTDB" + rte).checked) {
			toggleAnchors(rte, false);
		}

		if (oHdnMessage.value == null) oHdnMessage.value = "";

		if (document.all) {
			var style = frames[rte].document.getElementById('vistaTempBorder');
			if (style && style.tagName == 'STYLE') {
				style.parentNode.removeChild(style);
			}
			var script = frames[rte].document.getElementById('vistaFlag');
			if (script && script.tagName == 'SCRIPT') {
 				script.parentNode.removeChild(script);
			}

			if (frames[rte].document.body.id == 'vistaDummyBody') {
				oHdnMessage.value = escape(frames[rte].document.body.innerHTML);
			} else {
				oHdnMessage.value = escape(frames[rte].document.documentElement.outerHTML);
			}
		} else {
			var style = oRTE.contentDocument.getElementById('vistaTempBorder');
			if (style && style.tagName == 'STYLE') {
				style.parentNode.removeChild(style);
			}

			var script = oRTE.contentDocument.getElementById('vistaFlag');
			if (script && script.tagName == 'SCRIPT') {
 				script.parentNode.removeChild(script);
			}

			if (oRTE.contentDocument.body.id == 'vistaDummyBody') {
				oHdnMessage.value = escape(oRTE.contentDocument.body.innerHTML);
			} else {			
				// Hack to simulate outerHTML
				var foo = oRTE.contentDocument.createElement('foo');
				foo.appendChild(oRTE.contentDocument.documentElement.cloneNode(true));
				oHdnMessage.value = escape(foo.innerHTML);
			}
		}

		//if there is no content (other than formatting) set value to nothing
		if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == ""
			&& oHdnMessage.value.toLowerCase().search("<hr") == -1
			&& oHdnMessage.value.toLowerCase().search("<img") == -1) oHdnMessage.value = "";
		//fix for gecko
		if (escape(oHdnMessage.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A") oHdnMessage.value = "";
	}
}

function toggleHTMLSrc(rte) {
	//contributed by Bob Hutzel (thanks Bob!)
	var oRTE;
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}

	if (document.getElementById("chkSrc" + rte).checked) {
		if (document.getElementById("chkTDB" + rte).checked) {
			toggleAnchors(rte, false);
		}
		document.getElementById("Buttons1_" + rte).style.visibility = "hidden";
		document.getElementById("Buttons2_" + rte).style.visibility = "hidden";
		document.getElementById("chkTDB" + rte).disabled = true;

		var style = oRTE.getElementById('vistaTempBorder');
		if (style && style.tagName == 'STYLE') {
			style.parentNode.removeChild(style);
		}

		var script = oRTE.getElementById('vistaFlag');
		if (script && script.tagName == 'SCRIPT') {
 			script.parentNode.removeChild(script);
		}

		if (document.all) {
			if (oRTE.body.id == 'vistaDummyBody') {
				var HTML = oRTE.body.innerHTML;
			} else {
				var HTML = oRTE.documentElement.outerHTML;
				oRTE.open();
				oRTE.write('<html><body></body></html>');
				oRTE.close();
			}
			oRTE.body.innerText = HTML;
		} else {
			if (oRTE.body.id == 'vistaDummyBody') {
				var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
			} else {
				// Hack to simulate outerHTML
				var foo = oRTE.createElement('foo');
				foo.appendChild(oRTE.documentElement.cloneNode(true));
			
				var htmlSrc = oRTE.createTextNode(foo.innerHTML);
			}

			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		document.getElementById("Buttons1_" + rte).style.visibility = "visible";
		document.getElementById("Buttons2_" + rte).style.visibility = "visible";
		document.getElementById("chkTDB" + rte).disabled = false;
		var addBorders = document.getElementById("chkTDB" + rte).checked;

		if (document.all) {
			var output = escape(oRTE.body.innerText);
		} else {
			var output = escape(oRTE.body.textContent);
		}

		if (addBorders)
			output = output + hiddenBorderStyleTag;

		output = output + editContentTag;

		var pattern = /<body/i;
	
		output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
		output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
		if (pattern.test(unescape(output))) {
			oRTE.open();
			oRTE.write(unescape(output));
		} else {
			oRTE.open();
			oRTE.write('<html><body id="vistaDummyBody">' + unescape(output) + '</body></html>');
		}
		oRTE.close();

		if (document.all) {
			oRTE.onselectionchange = callUpdateToolbars;
			oRTE.oncontextmenu = showContextMenu;
			oRTE.onclick = callUpdateToolbars;
			oRTE.onmouseover = callOnMouseOver;
			oRTE.ondblclick = callOnDoubleClick;
		} else {
			oRTE.addEventListener("keypress", kb_handler, true);
			oRTE.addEventListener("click", callUpdateToolbars, true);
			oRTE.addEventListener("contextmenu", showContextMenu, true);
			oRTE.addEventListener("mouseover", callOnMouseOver, true);
			oRTE.addEventListener("dblclick", callOnDoubleClick, true);
		}

		if (document.getElementById("chkTDB" + rte).checked) {
			toggleAnchors(rte, true);
		}
	}
}

function toggleAnchors(rte, on) {

	var oRTE_t;
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}

	var a_tags = oRTE.body.getElementsByTagName('A');
	var len = a_tags.length;
	if (on){
		for (i=0; i<len; i++) {
			if ((a_tags.item(i).innerHTML == "") && (a_tags.item(i).className == 'vistaanchor')) {
				oRTE.body.getElementsByTagName('A').item(i).innerHTML = '<img src="/rte/images/anchor_editor.gif" class="vistaanchor" border=0 style="vertical-align: bottom" align=center>';
			}
		}
	} else {
		for (i=0; i<len; i++) {
			if ((a_tags.item(i).className == 'vistaanchor')
			   && (a_tags.item(i).innerHTML != "")) {
				a_tags.item(i).innerHTML = '';
			}
			else if ((a_tags.item(i).className == 'vistaanchor')
			   && (a_tags.item(i).innerHTML == "")) {
				var del_child = a_tags.item(i);
				del_child.parentNode.removeChild(del_child);
				i--;
				len--;
			}
		}
	}

	//Delete stray anchor images
	var img_tags = oRTE.body.getElementsByTagName('IMG');
	len = img_tags.length;
	for (i=0; i<len; i++) {
		if (img_tags.item(i).className == 'vistaanchor') {
			var parent = img_tags.item(i).parentNode;
			if (parent.className != 'vistaanchor') {
				var del_child = img_tags.item(i);
				del_child.parentNode.removeChild(del_child);
				i--;
				len--;
			}
		}
	}
}

function getPageAnchorsOutsideCell(remove_anchors) {
	var all_anchors = getAnchorsList(g_contentPath, false);

	var all_anchors_array = all_anchors.split("\t");
	var remove_anchors_array = remove_anchors.split("\t");

	var page_anchors_outside_cell = new Array();
	var k=0;
	for (var i=0; i<all_anchors_array.length; i++) {
		var found = false;
		for (var j=0; ((j<remove_anchors_array.length) && (found != true)); j++) {
			if (all_anchors_array[i] == remove_anchors_array[j])
				found = true;
		}
		if (!found) 
			//page_anchors_outside_cell = page_anchors_outside_cell + '\t' + all_anchors_array[i];
			page_anchors_outside_cell[k++] = all_anchors_array[i]
	}
	return page_anchors_outside_cell;
}

function getCurrentCellAnchors() {
	var rte = 'userHTML';
	var result_str = '';
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}
	var a_tags = oRTE.body.getElementsByTagName('A');
	var len = a_tags.length;

	for (var i=0; i<len; i++) {
		if ((a_tags.item(i).className == 'vistaanchor')
			   && (a_tags.item(i).innerHTML == "")) {
				var del_child = a_tags.item(i);
				del_child.parentNode.removeChild(del_child);
				i--;
				len--;
		}
	}

	for (var i=0; i<len; i++) {
		if (a_tags.item(i).className == 'vistaanchor') {
			if (result_str != '')
				result_str = result_str + "\t" + a_tags.item(i).name;
			else
				result_str = a_tags.item(i).name;
		}
	}
	return result_str;
}

function initAnchorsList() {
	g_anchors_outside_content_cell = getPageAnchorsOutsideCell(getCurrentCellAnchors());
}

function toggleTDBorders(rte) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}
	if (document.getElementById("chkTDB" + rte).checked) {
		var html = oRTE.body.innerHTML;
		oRTE.body.innerHTML = html + hiddenBorderStyleTag;

		toggleAnchors(rte, true);
	} else {
		var style = oRTE.getElementById('vistaTempBorder');
		if (style && style.tagName == 'STYLE') {
			style.parentNode.removeChild(style);
		}
		toggleAnchors(rte, false);		
	}
}

//Function to format text in the text box
function FormatText(rte, command, option) {
	hideDrawers(rte);

	var oRTE;
	if (document.all) {
		oRTE = frames[rte];

		//get current selected range
		currentSelection.select();	
		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	oRTE.focus();

	// See if command is enabled
	var dummyCommand;
	if (command == 'attachfile')
		dummyCommand = 'createlink';
	else if (command == 'insertfield' || command == 'insertpromo' || command == 'inserttable')
		dummyCommand = 'insertimage';
	else if (command == 'addanchor')
		dummyCommand = 'insertimage';
	else
		var dummyCommand = command;

	// if not, exit
	if (isIE && !oRTE.document.queryCommandEnabled(dummyCommand))
		return;

	try {
		if ((command == "forecolor") || (command == "backcolor")) {
			//save current values
			parentCommand = command;
			currentRTE = rte;

			//position and show color palette
			buttonElement = document.getElementById(command + '_' + rte);
			// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
			document.getElementById('cp' + rte).style.left = getOffsetLeft(buttonElement, 4) + "px";
			document.getElementById('cp' + rte).style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight + 4) + "px";
			if (document.getElementById('cp' + rte).style.visibility == "hidden") {
				document.getElementById('cp' + rte).style.visibility = "visible";
				document.getElementById('cp' + rte).style.display = "inline";
			} else {
				document.getElementById('cp' + rte).style.visibility = "hidden";
				document.getElementById('cp' + rte).style.display = "none";
			}
// ifdef VISTA
		} else if (command == "inserttable") {
			//save current values
			parentCommand = command;
			currentRTE = rte;
			currentSelection = rng;

			//position and show color palette
			buttonElement = document.getElementById(command + '_' + rte);
			// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
			document.getElementById('table' + rte).style.left = getOffsetLeft(buttonElement, 4) + "px";
			document.getElementById('table' + rte).style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight + 4) + "px";
			if (document.getElementById('table' + rte).style.visibility == "hidden") {
				document.getElementById('table' + rte).style.visibility = "visible";
				document.getElementById('table' + rte).style.display = "inline";
			} else {
				document.getElementById('table' + rte).style.visibility = "hidden";
				document.getElementById('table' + rte).style.display = "none";
			}
		} else if (command == "createlink") {
			// can't create an empty link
			if (isIE && selection.type == 'None')
				return;

			// pop up dialog with pre-populated link and target
			var href = 'http://';
			var target = 'default';
			var title = '';

			linkDrawer = document.getElementById('link' + rte);
			buttonElement = document.getElementById('Buttons2_' + rte);

			// wait for palette to load before showing
			if (linkDrawer.contentWindow.initLinkDrawer == null)
				return;

			linkDrawer.style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight) + "px";
			linkDrawer.style.left = (150 + getOffsetLeft(buttonElement)) + "px";
			if (linkDrawer.style.visibility == 'hidden') {
				linkDrawer.style.visibility = 'visible';
				linkDrawer.style.display = 'inline';
			} else {
				linkDrawer.style.visibility = 'hidden';
				linkDrawer.style.display = 'none';
			}

			var existing_link = false; // used by IE
			if (isIE) {
				if (selection.type == 'Text') {
					var parent = rng.parentElement();
					if (parent.tagName == 'A') {
						existing_link = true;
						href = parent.href;
						target = parent.target;
						title = parent.title;
					}
					else {
						var inside = rng.htmlText;
						if ((inside.indexOf("<A") > 0) || (inside.indexOf("A>") > 0))
							existing_link = true;
					}
				} else if (selection.type == 'Control') {
					// In this case, we want the surrounding A tag, even if the image is what's selected.
					if (rng.item(0) && rng.item(0).tagName == 'IMG') {
						var parent = rng.item(0).parentElement;
						if (parent.tagName == 'A') {
							existing_link = true;
							href = parent.href;
							target = parent.target;
							title = parent.title;
						}
					}
				}
			} else if (isGecko) {
				var parent = rng.commonAncestorContainer;
				if (parent.tagName == 'A') {
					href = parent.href;
					target = parent.target;
					title = parent.title;
				}
				else 
				{
					var child = rng.cloneContents().firstChild;
					if (child.tagName == 'A') {
						href = child.href;
						target = child.target;
						title = child.title;
					}
				}
			}

			var current_page_anchors = getCurrentCellAnchors();
			linkDrawer.contentWindow.initLinkDrawer(rte, href, target, title, current_page_anchors, g_contentPath, existing_link);
			currentSelection = rng;
// endif
		} else if (command == 'attachfile' || command == 'insertimage') {
			// can't create an empty link
			if (isIE && selection.type == 'None' && command == 'attachfile')
				return;

			// pop up dialog with pre-populated 
			var href = 'http://';
			var target = '_self';
			var align = '';
			var alt = '';

			pickerDrawer = document.getElementById('picker' + rte);
			buttonElement = document.getElementById('Buttons2_' + rte);

			pickerDrawer.style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight) + "px";
			pickerDrawer.style.left = (200 + getOffsetLeft(buttonElement)) + "px";
			if (pickerDrawer.style.visibility == 'hidden') {
				pickerDrawer.style.visibility = 'visible';
				pickerDrawer.style.display = 'inline';
			} else {
				pickerDrawer.style.visibility = 'hidden';
				pickerDrawer.style.display = 'none';
			}

			if (isIE) {
				if (selection.type == 'Text') {
					var parent = rng.parentElement();
					if (parent.tagName == 'A') {
						href = parent.href;
						target = parent.target;
						alt = parent.title;
					}
				} else if (selection.type == 'Control' && command == 'attachfile') {
					// In this case, we want the surrounding A tag, even if the image is what's selected.
					if (rng.item(0) && rng.item(0).tagName == 'IMG') {
						var parent = rng.item(0).parentElement;
						if (parent.tagName == 'A') {
							href = parent.href;
							target = parent.target;
							alt = parent.title;
						}
					}
				} else if (selection.type == 'Control' && command == 'insertimage') {
					if (rng.item(0) && rng.item(0).tagName == 'IMG') {
						align = rng.item(0).align;
						href = rng.item(0).src;
						alt = rng.item(0).alt;
					}
				} // else nothing to pre-pop
			} else if (isGecko) {
				if (command == 'attachfile') {
					var parent = rng.commonAncestorContainer;
					if (parent.tagName == 'A') {
						href = parent.href;
						target = parent.target;
						alt = parent.title;
					} else {
						var child = rng.cloneContents().firstChild;
						if (child && child.nodeType == 1 && child.tagName == 'A') {
							target = child.target;
							href = child.href;
							alt = child.title;
						}
					}
				} else if (command == 'insertimage') {
					var child = rng.cloneContents().firstChild;
					if (child && child.nodeType == 1 && child.tagName == 'IMG') {
						align = child.align;
						href = child.src;
						alt = child.alt;
					}
				}
			}

			setTimeout(function(){ pickerDrawer.contentWindow.initPickerForm(href, target, rte, command, align, alt); }, 150);
			currentSelection = rng;
		} else if (command == 'insertfield') {
			var curPos = currentSelection;
			// Pop up drawer with dropdown for fields
			fieldsDrawer = document.getElementById('fields' + rte);
			buttonElement = document.getElementById('Buttons2_' + rte);

			fieldsDrawer.style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight) + "px";
			fieldsDrawer.style.left = (200 + getOffsetLeft(buttonElement)) + "px";
			if (fieldsDrawer.style.visibility == 'hidden') {
				fieldsDrawer.style.visibility = 'visible';
				fieldsDrawer.style.display = 'inline';
			} else {
				fieldsDrawer.style.visibility = 'hidden';
				fieldsDrawer.style.display = 'none';
			}

			fieldsDrawer.contentWindow.initFieldForm(rte, rng.text);
			currentSelection = rng;
		} else if (command == 'insertpromo') {
			// Pop up drawer with dropdown for fields
			var promoWin = window.open('/store/email_promo.php', 'promo_win', 'width=660,height=412,innerWidth=660,innerHeight=412,menubar=no,status=yes,location=no,personalbar=no,toolbar=no,scrollbars=yes,resizable=yes');

			currentSelection = rng;
		} else if (command == 'addanchor') {
			var curPos = currentSelection;
			// Pop up drawer with dropdown for fields
			anchorDrawer = document.getElementById('addanchor' + rte);
			buttonElement = document.getElementById('Buttons2_' + rte);

			anchorDrawer.style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight) + "px";
			anchorDrawer.style.left = (200 + getOffsetLeft(buttonElement)) + "px";
			if (anchorDrawer.style.visibility == 'hidden') {
				anchorDrawer.style.visibility = 'visible';
				anchorDrawer.style.display = 'inline';
			} else {
				anchorDrawer.style.visibility = 'hidden';
				anchorDrawer.style.display = 'none';
			}

			var anchor_name = '';

			if (isIE) {
				if (selection.type == 'Control') {
					if (rng.item(0) && rng.item(0).tagName == 'IMG') {
						var parent = rng.item(0).parentElement;
						if (parent.tagName == 'A') {
							if (parent.className == 'vistaanchor') {
								anchor_name = parent.name;
							}
						}
					}
				}
				anchorDrawer.contentWindow.initAnchorForm(rte, anchor_name, curPos, selection.type, rng);
			
			}
	 		else {
				var child = rng.commonAncestorContainer;
				var sel_type = 'None';
				if (child && child.tagName == 'A') {
					if (child.className == 'vistaanchor') {
						anchor_name = child.name;
						sel_type = 'Control';
					}
				}
				anchorDrawer.contentWindow.initAnchorForm(rte, anchor_name, curPos, sel_type, rng);
			}

			currentSelection = rng;
// endif		
		} else {
			oRTE.focus();
		  	oRTE.document.execCommand(command, false, option);
			oRTE.focus();
		}
	} catch (e) {
		alert(e);
	}

	updateToolbars(rte);
}


// Adds and deletes cells, rows, and columns
// colspan and rowspan could be handled more intelligently
// TODO: add merge/split cells
function FormatTable(rte, command) {
	var oRTE, myTD;

	if (document.all) {
		oRTE = frames[rte].document;
		for (var el = rng.parentElement(); el && el.tagName != 'TD' && el.parentNode; el = el.parentNode);
		var parent = rng.parentElement();
	} else {
		oRTE = document.getElementById(rte).contentDocument;
		for (var el = rng.commonAncestorContainer; el && el.tagName != 'TD' && el.parentNode; el = el.parentNode);
	}

	if (el && el.tagName == 'TD') {
		var myTD = el;
		var myTR = myTD.parentNode;
		var myTB = myTR.parentNode;
		var myTable = myTB.parentNode;

		switch (command) {
			case 'toggleborder':
				myTable.border = (myTable.border == 1) ? 0 : 1;
				break;
			case 'togglewidth':
				if (myTable.width == '100%') {
					myTable.width = '';
				} else {
					myTable.width = '100%';
					myTable.style.width = '';
				}
				break;			
			case 'addcell':
				var td = oRTE.createElement('TD');

				if (isGecko)
					td.innerHTML = '&nbsp;';

				myTD.parentNode.insertBefore(td, myTD);
				break;
			case 'delcell':
				myTD.parentNode.removeChild(myTD);
				break;
			case 'addrow':
				var myOffset = myTD.offsetTop;
				var rows = myTB.getElementsByTagName('TR');

				var expandMe = Array();
				var b = 0;

				var rowSpanCells = Array();
				var cellOffsets = Array();
				var atMyRow = false;
				for (var i = 0; i < rows.length; i ++) {
					var cells = rows.item(i).getElementsByTagName('TD');

					for (var j = 0; j < cells.length; j ++) {
						var cellOffset = cells.item(j).offsetLeft;

						// for the first row, gather the x positions
						if (i == 0)
							cellOffsets[j] = cellOffset;

						// flag as the most recent cell in this x position
						rowSpanCells[cellOffset] = cells.item(j)

						// see if we've reached the row of the cell that was targeted
						if (cells.item(j) == myTD)
							atMyRow = true;
					}
					
					if (atMyRow) {
						var k = 0;
						var tr = oRTE.createElement('TR');

						for (j = 0; j < cells.length; j ++) {
							var thisCellOffset = cells.item(j).offsetLeft;
							var gridCellOffset = cellOffsets[k];

							while (gridCellOffset < thisCellOffset) {
								expandMe[b ++] = rowSpanCells[gridCellOffset];
								k += rowSpanCells[gridCellOffset].colSpan;
								gridCellOffset = cellOffsets[k];
							}

							if (thisCellOffset == gridCellOffset) {
								var td = oRTE.createElement('TD');
								td.colSpan = cells.item(j).colSpan;
								if (isGecko)
									td.innerHTML = '&nbsp;';
								tr.appendChild(td);
								
							}

							k += cells.item(j).colSpan;
						}

						myTB.insertBefore(tr, myTR);

						for (j = 0; j < expandMe.length; j ++)
							expandMe[j].rowSpan ++;

						break;
					}
				}
				break;
			case 'delrow':
				var myOffset = myTD.offsetTop;
				var rows = myTB.getElementsByTagName('TR');

				var shrinkMe = Array();
				var moveMe = Array();
				var beforeMe = Array();
				var a = 0;
				var b = 0;

				var rowSpanCells = Array();
				var cellOffsets = Array();
				var atMyRow = false;
				for (var i = 0; i < rows.length; i ++) {
					var cells = rows.item(i).getElementsByTagName('TD');

					for (var j = 0; j < cells.length; j ++) {
						var cellOffset = cells.item(j).offsetLeft;

						// for the first row, gather the x positions
						if (i == 0)
							cellOffsets[j] = cellOffset;

						// flag as the most recent cell in this x position
						rowSpanCells[cellOffset] = cells.item(j)

						// see if we've reached the row of the cell that was targeted
						if (cells.item(j) == myTD)
							atMyRow = true;
					}
					
					if (atMyRow) {
						var k = 0;

						for (j = 0; j < cells.length; j ++) {
							var thisCellOffset = cells.item(j).offsetLeft;
							var gridCellOffset = cellOffsets[k];

							while (gridCellOffset < thisCellOffset) {
								shrinkMe[b ++] = rowSpanCells[gridCellOffset];
								k += rowSpanCells[gridCellOffset].colSpan;
								gridCellOffset = cellOffsets[k];
							}

							if (cells.item(j).rowSpan > 1) {
								moveMe[a ++] = cells.item(j);
								shrinkMe[b++] = cells.item(j);
							}

							k += cells.item(j).colSpan;
						}

						var nextTR = myTR.nextSibling;
						if (nextTR) {
							var cells = nextTR.getElementsByTagName('TD');

							k = 0;
							for (j = 0; j < cells.length && k < moveMe.length; j ++) {
								var thisCellOffset = cells.item(j).offsetLeft;
								var myCellOffset = moveMe[k].offsetLeft;

								while (thisCellOffset > myCellOffset) {
									beforeMe[k ++] = cells.item(j);
									if (k >= moveMe.length)
										break;
									myCellOffset = moveMe[k].offsetLeft;
								}
							}

							while (k < moveMe.length) {
								nextTR.appendChild(moveMe[k]);
								moveMe[k] = null;
								k ++;
							}

							for (j = 0; j < moveMe.length; j ++) {
								if (moveMe[j])
									nextTR.insertBefore(moveMe[j], beforeMe[j]);
							}
						}

						myTB.removeChild(myTR);

						for (j = 0; j < shrinkMe.length; j ++)
							shrinkMe[j].rowSpan --;

						break;
					}
				}
				break;
			case 'addcol':
				var myOffset = myTD.offsetLeft;
				var rows = myTB.getElementsByTagName('TR');

				var beforeMe = Array();
				var expandMe = Array();
				var a = 0;
				var b = 0;
				var skipRows = 0;

				for (var i = 0; i < rows.length; i ++) {
					var cells = rows.item(i).getElementsByTagName('TD');

					for (var j = 0; j < cells.length; j ++) {
						var currentOffset = cells.item(j).offsetLeft;

						skipRows = 0;
						if (currentOffset == myOffset) {
							beforeMe[a ++] = cells.item(j);
							skipRows = cells.item(j).rowSpan - 1;
							break;
						} else if (currentOffset > myOffset) {
							expandMe[b ++] = cells.item(j - 1);
							break;
						}
					}
					
					i += skipRows;
				}

				for (i = 0; i < beforeMe.length; i ++) {
					var td = oRTE.createElement('TD');
					if (beforeMe[i].rowSpan > 1)
						td.rowSpan = beforeMe[i].rowSpan;
					if (isGecko)
						td.innerHTML = '&nbsp;';

					beforeMe[i].parentNode.insertBefore(td, beforeMe[i]);
				}

				for (i = 0; i < expandMe.length; i ++) {
					expandMe[i].colSpan ++;
				}
				break;
			case 'delcol':
				var myOffset = myTD.offsetLeft;
				var rows = myTB.getElementsByTagName('TR');

				var deleteMe = Array();
				var shrinkMe = Array();
				var a = 0;
				var b = 0;
				var skipRows = 0;

				for (var i = 0; i < rows.length; i ++) {
					var cells = rows.item(i).getElementsByTagName('TD');

					for (var j = 0; j < cells.length; j ++) {
						var currentOffset = cells.item(j).offsetLeft;

						skipRows = 0;
						if (currentOffset == myOffset) {
							if (cells.item(j).colSpan > 1)
								shrinkMe[b ++] = cells.item(j)
							else
								deleteMe[a ++] = cells.item(j);
							skipRows = cells.item(j).rowSpan - 1;
							break;
						} else if (currentOffset > myOffset) {
							shrinkMe[b ++] = cells.item(j - 1);
							break;
						}
					}
					
					i += skipRows;
				}

				for (i = 0; i < deleteMe.length; i ++) {
					deleteMe[i].parentNode.removeChild(deleteMe[i]);
				}

				for (i = 0; i < shrinkMe.length; i ++) {
					shrinkMe[i].colSpan --;
				}
				break;
		}
	}
}

function hideDrawers(rte) {
	document.getElementById('cp' + rte).style.visibility = "hidden";
	document.getElementById('cp' + rte).style.display = "none";

	document.getElementById('link' + rte).style.visibility = "hidden";
	document.getElementById('link' + rte).style.display = "none";

	document.getElementById('addanchor' + rte).style.visibility = "hidden";
	document.getElementById('addanchor' + rte).style.display = "none";

	document.getElementById('picker' + rte).style.visibility = "hidden";
	document.getElementById('picker' + rte).style.display = "none";

	document.getElementById('fields' + rte).style.visibility = "hidden";
	document.getElementById('fields' + rte).style.display = "none";

	document.getElementById('table' + rte).style.visibility = "hidden";
	document.getElementById('table' + rte).style.display = "none";
}

// ifdef VISTA
function createLink(rte, href, target, title, existing_link) {
	var oRTE;

	if (isIE)
		currentSelection.select();

	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();
	}

	var hostPattern = /^\w{3,5}:\/\//;
	if (imageHost != '' && !hostPattern.test(href)) {
		href = 'http://' + imageHost + href;
	}

	oRTE.focus();
	if (isIE) {

		if (existing_link) {
			oRTE.document.execCommand('CreateLink', false, href);
		} else {				
			if (selection.type == 'Text') {
				var rng1 = rng.duplicate();
				var rng2 = rng.duplicate();
				rng1.collapse();
				rng2.collapse(false);
				rng1.pasteHTML("-");
				rng2.pasteHTML("-");
				rng.execCommand('CreateLink', false, href);
				rng.collapse();
				rng.moveStart('character', -1);
				rng.moveEnd('character', 0);
				rng.pasteHTML("");

				rng2.moveStart('character', -1);
				rng2.moveEnd('character', 0);
				rng2.pasteHTML("");

			} else if (selection.type == 'Control') {
				if (rng.item(0) && rng.item(0).tagName == 'IMG') {
					var myImg = rng.item(0);
					var oldHtml = myImg.outerHTML;
					myImg.outerHTML = '<A href="' + href + '" title="' + title + '" target ="' + target + '">' + oldHtml + '</A>';
				}
			}
		}
	}
	else {
		oRTE.document.execCommand('CreateLink', false, href);
	}
	oRTE.focus();


	// Set target
	if (isIE) {
		if (selection.type == 'Text') {
			var parent = rng.parentElement();
			if (parent.tagName == 'A') {
				parent.target = target;
				parent.title = title;
			}
		} else if (selection.type == 'Control') {
			if (rng.item(0) && rng.item(0).tagName == 'IMG') {
				var parent = rng.item(0).parentElement;
				if (parent.tagName == 'A') {
					parent.target = target;
					parent.title = title;
				}
			}
		}
	} else if (isGecko) {
		var parent = rng.commonAncestorContainer;
		if (parent.tagName == 'A') {
			parent.target = target;
			parent.title = title;			
		} else {
			var rangeContents = currentSelection.extractContents();
			var child;
			if (child = rangeContents.firstChild) {
				if (child.nodeType == 1 && child.tagName == 'A') {
					child.target = target;
					child.title = title;
				}
			}
			rng.insertNode(rangeContents);
		}
	}

	linkDrawer = document.getElementById('link' + rte);
	linkDrawer.style.visibility = 'hidden';
	linkDrawer.style.display = 'none';

	pickerDrawer = document.getElementById('picker' + rte);
	pickerDrawer.style.visibility = 'hidden';
	pickerDrawer.style.display = 'none';
}
//endif

//Function to set color
function setColor(color) {
	var rte = currentRTE;
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}

	document.getElementById('cp' + rte).style.visibility = "hidden";
	document.getElementById('cp' + rte).style.display = "none";

	if (color == '')
		return;

	if (document.all) {
		//retrieve selected range
		var sel = oRTE.document.selection;
		if (sel != null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}
	oRTE.focus();
	oRTE.document.execCommand(parentCommand, false, color);
	oRTE.focus();
}

function insertImage(rte, imagePath, imageAlign, imageAlt, width, height)
{
	var oRTE, selection;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}

	if (isIE) {
		currentSelection.select();
	}

	if ((imageHost != null) && (imageHost != "")) {
		imagePath = 'http://' + imageHost + imagePath;
	}

	if ((imagePath != null) && (imagePath != "")) {
		oRTE.focus();
		oRTE.document.execCommand('InsertImage', false, imagePath);
		oRTE.focus();
	}

	var myImage;
	if (document.all) {
		selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
			myImage = rng.item(0);
		}
	} else {
		selection = oRTE.getSelection();
		var range = selection.getRangeAt(selection.rangeCount - 1);
		range.setStart(range.startContainer, range.startOffset - 1);
		var rangeContents = selection.getRangeAt(selection.rangeCount - 1).extractContents();
		var child;

		if (child = rangeContents.firstChild) {
			if (child.nodeType == 1 && child.tagName == 'IMG') {
				myImage = child;
			}
		}

		range.insertNode(rangeContents);
	}
	
	if (myImage) {
		myImage.border = 0;
		myImage.align = imageAlign;
		myImage.alt = imageAlt;
		if (width && height) {
			myImage.width = width;
			myImage.height = height;
		}
	}	

	document.getElementById('picker' + rte).style.visibility = "hidden";
	document.getElementById('picker' + rte).style.display = "none";
}

function insertAnchorData(rte, safeName, modify, curPos, curSel, curRng) {
	var oRTE;
	var sel;

	var imgContent = '<img class=vistaanchor src="/rte/images/anchor_editor.gif" border=0 align=center style="vertical-align: bottom">';
	if (modify){
		var anchorContent = safeName;
	} else {

		if (document.getElementById("chkTDB" + rte).checked) {
			var anchorContent = '<a name="' + safeName + '" class=vistaanchor>' + imgContent + '</a>';
		}
		else {
			var anchorContent = '<a name="' + safeName + '" class=vistaanchor></a>';
		}
	}

	if (document.all) {
		rng = curPos;
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
		oRTE = document.getElementById(rte).contentWindow;
		sel = selection;
	}

	if (isIE) {
		try {
			if (curSel == 'Control') {
				var parent = curRng.item(0).parentElement;
				if (parent.tagName == 'A') {
					if (parent.className == 'vistaanchor') {
						parent.name = anchorContent;
					}
				}
				else {
					var myImg = curRng.item(0);
					var oldHtml = myImg.outerHTML
					myImg.outerHTML = anchorContent + oldHtml;
				}
			} else {
				var txt = rng.htmlText;
				rng.pasteHTML(anchorContent + txt);
			}
		} catch (e) {}
	} else {
		if (curSel == 'Control') {
			var child = rng.commonAncestorContainer;
			var sel_type = 'None';
			if (child && child.tagName == 'A') {
				if (child.className == 'vistaanchor') {
					child.name = anchorContent;
				}
			}
		}
		else {

			var text = oRTE.document.createElement('A');
			text.innerHTML = imgContent;
			text.name = safeName;
			text.className = 'vistaanchor';
			rng.insertNode(text);
		}
	}
	document.getElementById('fields' + rte).style.visibility = "hidden";
	document.getElementById('fields' + rte).style.display = "none";
}

function insertField(rte, field) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];

		//get current selected range
		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
		oRTE = document.getElementById(rte).contentWindow;
 	}

	if (isIE) {
		try {
			rng.pasteHTML(field);
		} catch (e) {}
	} else {
		var text = oRTE.document.createElement('A');
		text.innerHTML = unescape(field);
		rng.insertNode(text);
	}

	document.getElementById('fields' + rte).style.visibility = "hidden";
	document.getElementById('fields' + rte).style.display = "none";
}

function insertTable(rows, cols, width, border) {
	var rte = currentRTE;
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		oRTE.focus();

		//get current selected range
/*		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		} */ // Buggy due to weirdness with rte losing focus to table drawer

		rng = currentSelection;
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
		oRTE = document.getElementById(rte).contentWindow;
	}

	var table = oRTE.document.createElement('TABLE');
	var tbody = oRTE.document.createElement('TBODY');

	for (var i = 0; i < rows; i ++) {
		var row = oRTE.document.createElement('tr');

		for (var j = 0; j < cols; j++) {
			var cell = oRTE.document.createElement('td');
			row.appendChild(cell);
		}

		tbody.appendChild(row);
	}
	table.appendChild(tbody);

	if (border)
		table.border = 1;
	else {
		table.border = 0;
	}

	if (width != '')
		table.width = '100%';
	else
		table.width = (cols * 20) + 'px';

	if (isIE) {
		rng.pasteHTML(table.outerHTML);
	} else if (isGecko) {
		rng.insertNode(table);
	}

	document.getElementById('table' + rte).style.visibility = "hidden";
	document.getElementById('table' + rte).style.display = "none";
}

//Function to add image
function AddImage(rte) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];

		//get current selected range
		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	imagePath = prompt('Enter Image URL:', 'http://');
	if ((imagePath != null) && (imagePath != "")) {
		oRTE.focus();
		oRTE.document.execCommand('InsertImage', false, imagePath);
		oRTE.focus();
	}
}

//function to perform spell check
function checkspell() {
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		return false;		
	}
}

function spellInstalled() {
	if (!isIE)
		return false;

	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
	}
	catch(exception) {
		return false;		
	}

	return true;
}

function locate(rte) {
	window.find();
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
function getOffsetTop(elm, parents_up) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;

	if(!parents_up) {
		parents_up = 10000; // arbitrary big number
	}
	while(parents_up>0 && mOffsetParent) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}

	return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
function getOffsetLeft(elm, parents_up) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;

	if(!parents_up) {
		parents_up = 10000; // arbitrary big number
	}
	while(parents_up>0 && mOffsetParent) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}

	return mOffsetLeft;
}

function Select(rte, selectname) {
	var oRTE;

	if (document.all) {
		oRTE = frames[rte];

		//get current selected range
		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	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, '');
		oRTE.focus();
		oRTE.document.execCommand(cmd, false, selected);
		oRTE.focus();

		if (isIE && cmd == 'fontsize' && selected == '3')
			rng.pasteHTML('<font size="3">' + rng.htmlText + '</font>');
		document.getElementById(selectname).selectedIndex = 0;
	}

	updateToolbars(rte);
}

function kb_handler(evt) {
	var rte = evt.target.id;

	//contributed by Anti Veeranna (thanks Anti!)
	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) {
			FormatText(rte, cmd, true);
			//evt.target.ownerDocument.execCommand(cmd, false, true);
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}

	updateToolbars(rte);
}

function callUpdateToolbars(e) {
	var rte = 'userHTML';

	updateToolbars(rte);
	if (!isIE && pUp != null) {
		// Hide the popup menu
		pUp.style.visibility = 'hidden';
		pUp.style.display = 'none';
	}
}


function callOnDoubleClick(e) {

	var rte = 'userHTML';
	hideDrawers(rte);
	var oRTE;
	var sel_type;
	var anchor_name;
	if (document.all) {
		oRTE = frames[rte];

		//get current selected range
		currentSelection.select();	
		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
			sel_type = selection.type;
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	if (document.all) {
		var el = frames['userHTML'].document.parentWindow.event.srcElement;
		anchor_name = el.parentElement.name;
	} else {
		var el = e.target;
		sel_type = 'Control';
		anchor_name = e.target.parentNode.name;
	}

	if (el.className == 'vistaanchor') {
		anchorDrawer = document.getElementById('addanchor' + rte);
		buttonElement = document.getElementById('Buttons2_' + rte);

		anchorDrawer.style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight) + "px";
		anchorDrawer.style.left = (200 + getOffsetLeft(buttonElement)) + "px";
		if (anchorDrawer.style.visibility == 'hidden') {
			anchorDrawer.style.visibility = 'visible';
			anchorDrawer.style.display = 'inline';
		} else {
			anchorDrawer.style.visibility = 'hidden';
			anchorDrawer.style.display = 'none';
		}
		var curPos = currentSelection;
		anchorDrawer.contentWindow.initAnchorForm(rte, anchor_name, curPos, sel_type, rng);
	}	
}


function callOnMouseOver(e) {

	var text_label = '';
	var is_anchor = false;

	if (document.all) {
		text_label = frames['userHTML'].document.parentWindow.event.srcElement.parentElement.name;
		if (frames['userHTML'].document.parentWindow.event.srcElement.parentElement.className == 'vistaanchor')
			is_anchor = true;
		var coordX = frames['userHTML'].document.parentWindow.event.clientX;
		var coordY = frames['userHTML'].document.parentWindow.event.clientY;
	} else {
		//var el = e.target; // debug: have NOT tested in FF
		text_label = e.target.parentNode.name;
		if (e.target.parentNode.className == 'vistaanchor')
			is_anchor = true;
		var coordX = e.clientX;
		var coordY = e.clientY;
	}

	if (is_anchor) {
		showAnchorPopup(coordX, coordY, text_label);
		found_anchor = true;
	}
	else {
		hideAnchorPopup();
	}
}

function updateToolbars(rte) {
	if (!rte) rte = 'userHTML';
	var selection;
	if (document.all) {
		oRTE = frames[rte].document;

		selection = oRTE.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;

		selection = document.getElementById(rte).contentWindow.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	// Enable/disable editing commands:
	// cut, copy, paste, undo, redo
	if (isIE) {
		var commands = ['cut', 'copy', 'paste', 'undo', 'redo', 'indent', 'outdent', 'inserthorizontalrule', 'createlink', 'unlink', 'forecolor', 'backcolor'];
	} else {
		var commands = ['undo', 'redo', 'indent', 'outdent', 'inserthorizontalrule', 'createlink', 'unlink', 'forecolor', 'backcolor'];
	}

	for (i = 0; i < commands.length; i ++) {
		var button = document.getElementById(commands[i]);
		var enabled = oRTE.queryCommandEnabled(commands[i]);
		button.src = enabled ? imagesPath + commands[i] + '.gif' : imagesPath + commands[i] + '_off.gif';
		button.state = enabled ? 'enabled' : 'disabled';
	}


	// Show state of formatting buttons:
	var commands = ['bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist']

	for (i = 0; i < commands.length; i ++) {
		var button = document.getElementById(commands[i]);
		var enabled = oRTE.queryCommandEnabled(commands[i]);
		var state = oRTE.queryCommandState(commands[i]);

		if (!enabled) {
			button.state = 'disabled';
			button.src = imagesPath + commands[i] + '_off.gif';
		} else if (state) {
			button.className = 'rteImageLowered';
			button.state = 'active';
			button.src = imagesPath + commands[i] + '.gif';
		} else {
			button.className = 'rteImage';
			button.state = 'normal';
			button.src = imagesPath + commands[i] + '.gif';
		}
	}

	document.getElementById('fontsize_' + rte).value = oRTE.queryCommandValue('fontsize');
	document.getElementById('fontsize_' + rte).disabled = !oRTE.queryCommandEnabled('fontsize');
	document.getElementById('fontname_' + rte).value = String(oRTE.queryCommandValue('fontname')).toLowerCase();
	document.getElementById('fontname_' + rte).disabled = !oRTE.queryCommandEnabled('fontname');

	var format = oRTE.queryCommandValue('formatblock');
	if (isIE) {
		switch (format) {
			case 'Normal':
				format = '';
				break;
			case 'Paragraph':
				format = '<p>';
				break;
			case 'Heading 1':
				format = '<h1>';
				break;
			case 'Heading 2':
				format = '<h2>';
				break;
			case 'Heading 3':
				format = '<h3>';
				break;
			case 'Heading 4':
				format = '<h4>';
				break;
			case 'Formatted':
				format = '<pre>';
				break;
			default:
				format = '<' + format + '>';
		}
	} else {
		format = '<' + format + '>';
	}

	document.getElementById('formatblock_' + rte).value = format;
	document.getElementById('formatblock_' + rte).disabled = !oRTE.queryCommandEnabled('formatblock');
	currentSelection = rng;
}

function stripHTML(oldString) {
	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
}

function focusRTE(rte) {

	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}

	oRTE.focus();
	currentSelection.select();
}

function showAnchorPopup( curX, curY, anchorname )
{
//        if((!popupHelp) && (!visibleHelp))
//        {
                if ( typeof( wait ) == "undefined" )
                {
                        wait = 300;
                }

                popupAnchorPopup   = true;
                visibleAnchorPopup = false;

                if ( document.layers )
                {
                        anchorPopupObject = document.layers['anchorPopup'];
                }
                else if ( document.all )
                {
                        anchorPopupObject = document.all['anchorPopup'];
                }
                else
                {
                        anchorPopupObject = document.getElementById( 'anchorPopup' );
                }

                if ( typeof( offset ) == "undefined" )
                {
                        offset = 245;
                }

                if ( typeof( anchorPopupObject ) != "undefined" )
                {
                        /*if ( wait > 0 )
                        {
                                //setTimeout( "displayAnchorPopup(" + offset + ")", wait );
                        }
                        else*/
                        {
                                displayAnchorPopup( curX, curY, anchorname );
                        }
                }
//	}

//	return;
}


function displayAnchorPopup( curX, curY, anchorname )
{
//        if ( ( visibleAnchorPopup ) || ( !popupAnchor ) )
//                return;
	popupAnchorPopup   = false;
	visibleAnchorPopup = true;
	var msg = unescape(anchorname);

	if ( typeof( curX ) == "undefined" ) {
		curX = 0;
	}
        if ( typeof( curY ) == "undefined" ) {
		curY = 28;
	}
	if (curY < 28) {
		curY = 28;
	}

	if ( document.layers )
	{
		if ( document.layers['anchorPopup'] != null )
		{
			document.layers['anchorPopup'].left = document.layers['anchorPosition'].pageX - offset;
			document.layers['anchorPopup'].top = document.layers['anchorPosition'].pageY;
			document.layers['anchorPopup'].visibility = "show";
		}
	}
	else if ( document.all )
	{
		if ( document.all['anchorPopup'] != null )
		{
			document.all['anchorPopup'].style.left = document.all['anchorPositionIE'].offsetLeft + curX + 2;
			document.all['anchorPopup'].style.top = document.all['anchorPositionIE'].offsetTop + curY + 32;
			document.all['anchorPopup'].style.visibility = "visible";
			document.getElementById('anchorDisplayName').innerHTML = msg;
		}
	}
	else if ( document.getElementById( 'anchorPopup' ) != null )
	{
		var anchorPopupElement = document.getElementById( 'anchorPopup' );

		anchorPopupElement.style.left = document.getElementById( 'anchorPosition' ).offsetLeft + curX + 2;
		anchorPopupElement.style.top  = document.getElementById( 'anchorPosition' ).offsetTop + curY + 32;
		document.getElementById('anchorDisplayName').innerHTML = msg;
		anchorPopupElement.style.visibility = "visible";
	}
}

function hideAnchorPopup ()
{
	if ( document.layers )
	{
		if ( document.layers['anchorPopup'] != null )
		{
			document.layers['anchorPopup'].visibility = "show";
		}
	}
	else if ( document.all )
	{
		if ( document.all['anchorPopup'] != null )
		{
			if (document.all['anchorPopup'].style.visibility == 'visible' && found_anchor) {
				setTimeout('document.all["anchorPopup"].style.visibility = "hidden"', 500);
				setTimeout('found_anchor = false', 2000);
			}
		}
	}
	else if ( document.getElementById( 'anchorPopup' ) != null )
	{
		var anchorPopupElement = document.getElementById( 'anchorPopup' );
		anchorPopupElement.style.visibility = "hidden";
        }
	
}

