var isRichText = false;
var rng;
var currentEDT;
var allEDTs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;
var html2xhtml;

var lang = "en";
var encoding = "iso-8859-1";


function initEDT(imgPath, incPath, css, convXHTML) {
	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);
	
	html2xhtml = convXHTML;
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}
	
	if (isIE) {
		document.onmouseover = raiseButton;
		document.onmouseout  = normalButton;
		document.onmousedown = lowerButton;
		document.onmouseup   = raiseButton;
	}
	
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
	
	if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'edit.css";</style>');
	
}

function typeEditedText(edt, html, width, height, buttons, readOnly) {
	if (isRichText) {
		if (allEDTs.length > 0) allEDTs += ";";
		allEDTs += edt;
		
		if (readOnly) buttons = false;
		
		if (isIE) {
			if (buttons && (width < 600)) width = 600;
			var tablewidth = width;
		} else {
			if (buttons && (width < 600)) width = 600;
			var tablewidth = width + 4;
		}
		
		document.writeln('<div class="edtDiv">');
		document.writeln('	<table border="0" cellspacing="0" width="75%">');
		document.writeln('		<tr><td align="left" valign="top">');
		if (buttons == true) {
			document.writeln('<table class="edtHeader" cellpadding="2" cellspacing="0" id="Buttons1_' + edt + '" >');
			document.writeln('	<tr>');
			document.writeln('		<td align="center" valign="bottom" style="height: 22px; width: 18%">');
			document.writeln('			<select id="formatblock_' + edt + '" onchange="chooseFont(\'' + edt + '\', this.id);">');
			document.writeln('				<option value="">[Style]</option>');
			document.writeln('				<option value="<p>">Paragraph &lt;p&gt;</option>');
			document.writeln('				<option value="<h1>">Heading 1 &lt;h1&gt;</option>');
			document.writeln('				<option value="<h2>">Heading 2 &lt;h2&gt;</option>');
			document.writeln('				<option value="<h3>">Heading 3 &lt;h3&gt;</option>');
			document.writeln('				<option value="<h4>">Heading 4 &lt;h4&gt;</option>');
			document.writeln('				<option value="<h5>">Heading 5 &lt;h5&gt;</option>');
			document.writeln('				<option value="<h6>">Heading 6 &lt;h6&gt;</option>');
			document.writeln('				<option value="<address>">Address &lt;ADDR&gt;</option>');
			document.writeln('				<option value="<pre>">Formatted &lt;pre&gt;</option>');
			document.writeln('			</select>');
			document.writeln('		</td>');
			document.writeln('		<td align="left" valign="bottom" style="height: 22px; width: 18%">');
			document.writeln('			<select id="fontname_' + edt + '" onchange="chooseFont(\'' + edt + '\', this.id)">');
			document.writeln('				<option value="Font" selected>[Font]</option>');
			document.writeln('				<option value="Arial, Helvetica, sans-serif">Arial</option>');
			document.writeln('				<option value="Courier New, Courier, mono">Courier New</option>');
			document.writeln('				<option value="Times New Roman, Times, serif">Times New Roman</option>');
			document.writeln('				<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>');
			document.writeln('			</select>');
			document.writeln('		</td>');
			document.writeln('		<td align="left" valign="bottom">');
			document.writeln('			<select unselectable="on" id="fontsize_' + edt + '" onchange="chooseFont(\'' + edt + '\', 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></tr>');
			document.writeln('		<tr><td width="75%" align="left" colspan="3">');
			document.writeln('		<table cellpadding="0" cellspacing="0" id="Buttons2_' + edt + '" width="75%">');
			document.writeln('	<tr>');
			document.writeln('		<td align="left" align="top"><img id="bold" class="edtImage" src="' + imagesPath + 'bold.gif" width="20" height="20" alt="Bold" title="Bold" onClick="edtCommand(\'' + edt + '\', \'bold\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'italic.gif" width="20" height="20" alt="Italic" title="Italic" onClick="edtCommand(\'' + edt + '\', \'italic\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'underline.gif" width="20" height="20" alt="Underline" title="Underline" onClick="edtCommand(\'' + edt + '\', \'underline\', \'\')"></td>');
			document.writeln('		<td><img class="edtImage" src="' + imagesPath + 'undo.gif" width="20" height="20" alt="Undo" title="Undo" onClick="edtCommand(\'' + edt + '\', \'undo\')"></td>');
			document.writeln('		<td><img class="edtImage" src="' + imagesPath + 'redo.gif" width="20" height="20" alt="Redo" title="Redo" onClick="edtCommand(\'' + edt + '\', \'redo\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'left.gif" width="20" height="20" alt="Align Left" title="Align Left" onClick="edtCommand(\'' + edt + '\', \'justifyleft\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'centre.gif" width="20" height="20" alt="Center" title="Center" onClick="edtCommand(\'' + edt + '\', \'justifycenter\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'right.gif" width="20" height="20" alt="Align Right" title="Align Right" onClick="edtCommand(\'' + edt + '\', \'justifyright\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'justify.gif" width="20" height="20" alt="Justify Full" title="Justify Full" onclick="edtCommand(\'' + edt + '\', \'justifyfull\', \'\')"></td>');
			//document.writeln('		<td align="left" align="top"><img class="edtVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		</td></tr>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'nlist.gif" width="20" height="20" alt="Ordered List" title="Ordered List" onClick="edtCommand(\'' + edt + '\', \'insertorderedlist\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'list.gif" width="20" height="20" alt="Unordered List" title="Unordered List" onClick="edtCommand(\'' + edt + '\', \'insertunorderedlist\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'outdent.gif" width="20" height="20" alt="Outdent" title="Outdent" onClick="edtCommand(\'' + edt + '\', \'outdent\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'indent.gif" width="20" height="20" alt="Indent" title="Indent" onClick="edtCommand(\'' + edt + '\', \'indent\', \'\')"></td>');
			document.writeln('		<td align="left" align="top"><div id="forecolor_' + edt + '"><img class="edtImage" src="' + imagesPath + 'textcolor.gif" width="20" height="20" alt="Text Color" title="Text Color" onClick="paletteBox(\'' + edt + '\', \'forecolor\', \'\')"></div></td>');
			document.writeln('		<td align="left" align="top"><div id="hilitecolor_' + edt + '"><img class="edtImage" src="' + imagesPath + 'bgcolor.gif" width="20" height="20" alt="Background Color" title="Background Color" onClick="paletteBox(\'' + edt + '\', \'hilitecolor\', \'\')"></div></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'hyperlink.gif" width="20" height="20" alt="Insert Link" title="Insert Link" onClick="attachLink(\'' + edt + '\', \'link\')"></td>');
			document.writeln('		<td align="left" align="top"><img class="edtImage" src="' + imagesPath + 'image.gif" width="20" height="20" alt="Add Image" title="Add Image" onClick="insertImage(\'' + edt + '\')"></td>');
			document.writeln('		<td align="left" align="top"><div id="table_' + edt + '"><img class="edtImage" src="' + imagesPath + 'table.gif" width="20" height="20" alt="Insert Table" title="Insert Table" onClick="designAtable(\'' + edt + '\', \'table\', \'\')"></div></td>');
			document.writeln('	</tr></table>');
			document.writeln('	</td></tr>');
			document.writeln('</table>');
		}
		document.writeln('	</td></tr>');
		document.writeln('	<tr><td align="left" valign="top">');
		document.writeln(' <table  class="edtBack" cellspacing="0"><td align="left" valign="top">');
		document.writeln('<iframe frameborder="0" id="' + edt + '" name="' + edt + '" width="' + width + 'px" height="' + height + 'px" src="' + includesPath + 'blank.htm"></iframe>');
		document.writeln('</td></tr></table>');
		document.writeln('</td></tr></table>');
		if (!readOnly) document.writeln('<br /><input type="checkbox" id="chkSrc' + edt + '" onclick="htmlCode(\'' + edt + '\',' + buttons + ');" />&nbsp;<label for="chkSrc' + edt + '">View Source</label>');
		document.writeln('<iframe class="brdr" frameborder="0" width="154" height="104" id="cp' + edt + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; position: absolute;"></iframe>');
		document.writeln('<input type="hidden" id="hdn' + edt + '" name="' + edt + '" value="">');
		document.writeln('</div>');
		
		document.getElementById('hdn' + edt).value = html;
		designEnable(edt, html, readOnly);
	} else {
		if (!readOnly) {
			document.writeln('<textarea name="' + edt + '" id="' + edt + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
		} else {
			document.writeln('<textarea name="' + edt + '" id="' + edt + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>');
		}
	}
}

function designEnable(edt, html, readOnly) {
	var frameHtml = "<html id=\"" + edt + "\">\n";
	frameHtml += "<head>\n";
	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: 0px;\n";
		frameHtml += "	padding: 0px;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
	}
	frameHtml += "</head>\n";
	frameHtml += "<body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";
	
	if (document.all) {
		var oEDT = frames[edt].document;
		oEDT.open();
		oEDT.write(frameHtml);
		oEDT.close();
		if (!readOnly) {
			oEDT.designMode = "On";
			frames[edt].document.attachEvent("onkeypress", function evt_ie_keypress(event) {ieKeyPress(event, edt);});
		}
	} else {
		try {
			if (!readOnly) document.getElementById(edt).contentDocument.designMode = "on";
			try {
				var oEDT = document.getElementById(edt).contentWindow.document;
				oEDT.open();
				oEDT.write(frameHtml);
				oEDT.close();
				if (isGecko && !readOnly) {
					oEDT.addEventListener("keypress", geckoKeyPress, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			if (isGecko) {
				setTimeout("designEnable('" + edt + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
}

function updateEDT(edt) {
	if (!isRichText) return;
	
	var readOnly = false;
	if (document.all) {
		if (frames[edt].document.designMode != "On") readOnly = true;
	} else {
		if (document.getElementById(edt).contentDocument.designMode != "on") readOnly = true;
	}
	
	if (isRichText && !readOnly) {
		if (document.getElementById("chkSrc" + edt).checked) document.getElementById("chkSrc" + edt).click();
		fixHideval(edt);
	}
}

function fixHideval(edt) {
	var oHdnField = document.getElementById('hdn' + edt);
	
	if (oHdnField.value == null) oHdnField.value = "";
	if (document.all) {
		if (html2xhtml) {
			oHdnField.value = receive_xhtml(frames[edt].document.body, lang, encoding);
		} else {
			oHdnField.value = frames[edt].document.body.innerHTML;
		}
	} else {
		if (html2xhtml) {
			oHdnField.value = receive_xhtml(document.getElementById(edt).contentWindow.document.body, lang, encoding);
		} else {
			oHdnField.value = document.getElementById(edt).contentWindow.document.body.innerHTML;
		}
	}
	
	if (stripHTML(oHdnField.value.replace("&nbsp;", " ")) == "" &&
		oHdnField.value.toLowerCase().search("<hr") == -1 &&
		oHdnField.value.toLowerCase().search("<img") == -1) oHdnField.value = "";
}

function updateEDTs() {
	var vEDTs = allEDTs.split(";");
	for (var i = 0; i < vEDTs.length; i++) {
		updateEDT(vEDTs[i]);
	}
}

function edtCommand(edt, command, option) {
	var oEDT;
	if (document.all) {
		oEDT = frames[edt];
	} else {
		oEDT = document.getElementById(edt).contentWindow;
	}
	
	try {
		oEDT.focus();
	  	oEDT.document.execCommand(command, false, option);
		oEDT.focus();
	} catch (e) {
//		alert(e);
//		setTimeout("edtCommand('" + edt + "', '" + command + "', '" + option + "');", 10);
	}
}

function htmlCode(edt, buttons) {
	var oHdnField = document.getElementById('hdn' + edt);
	
	if (document.getElementById("chkSrc" + edt).checked) {
		if (buttons) {
			showHideElement("Buttons1_" + edt, "hide");
			showHideElement("Buttons2_" + edt, "hide");
		}
		fixHideval(edt);
		if (document.all) {
			frames[edt].document.body.innerText = oHdnField.value;
		} else {
			var oEDT = document.getElementById(edt).contentWindow.document;
			var htmlSrc = oEDT.createTextNode(oHdnField.value);
			oEDT.body.innerHTML = "";
			oEDT.body.appendChild(htmlSrc);
		}
	} else {
		if (buttons) {
			showHideElement("Buttons1_" + edt, "show");
			showHideElement("Buttons2_" + edt, "show");
		}
		if (document.all) {
			var output = escape(frames[edt].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[edt].document.body.innerHTML = unescape(output);
		} else {
			var oEDT = document.getElementById(edt).contentWindow.document;
			var htmlSrc = oEDT.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oEDT.body);
			oEDT.body.innerHTML = htmlSrc.toString();
		}
	}
}

function paletteBox(edt, command) {
	setRange(edt);
	
	var oDialog = document.getElementById('cp' + edt);
	var buttonElement = document.getElementById(command + '_' + edt);
	var iLeftPos = toTheLeft(buttonElement);
	var iTopPos = toTop(buttonElement) + (buttonElement.offsetHeight + 4);
	oDialog.style.left = (iLeftPos) + "px";
	oDialog.style.top = (iTopPos) + "px";
	
	if ((command == parent.command) && (edt == currentEDT)) {
		if (oDialog.style.visibility == "hidden") {
			showHideElement(oDialog, 'show');
		} else {
			showHideElement(oDialog, 'hide');
		}
	} else {
		var vEDTs = allEDTs.split(";");
		for (var i = 0; i < vEDTs.length; i++) {
			showHideElement('cp' + vEDTs[i], 'hide');
		}
		showHideElement(oDialog, 'show');
	}
	
	parent.command = command;
	currentEDT = edt;
}



function designAtable(edt, command) {
	parent.command = command;
	currentEDT = edt;
	InsertTable = popUpWin(includesPath + 'table.htm', 'InsertTable', 360, 180, '');
}

function attachLink(edt, command) {
	parent.command = command;
	currentEDT = edt;
	InsertLink = popUpWin(includesPath + 'link.htm', 'InsertLink', 360, 180, '');
	
	setRange(edt);
	var linkText = '';
	if (isIE) {
		linkText = stripHTML(rng.htmlText);
	} else {
		linkText = stripHTML(rng.toString());
	}
	fixAnchorTxt(linkText);
}

function fixAnchorTxt(linkText) {
	try {
		window.InsertLink.document.linkForm.linkText.value = linkText;
	} catch (e) {
		setTimeout("fixAnchorTxt('" + linkText + "');", 10);
	}
}

function popUpWin (url, win, width, height, options) {
	var leftPos = (screen.availWidth - width) / 2;
	var topPos = (screen.availHeight - height) / 2;
	options += 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;
	return window.open(url, win, options);
}

function setColor(color) {
	var edt = currentEDT;
	var parentCommand = parent.command;
	
	if (document.all) {
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		rng.select();
	}
	
	edtCommand(edt, parentCommand, color);
	showHideElement('cp' + edt, "hide");
}

function insertImage(edt) {
	imagePath = prompt('Enter Image URL:', 'http://');
	if ((imagePath != null) && (imagePath != "")) {
		edtCommand(edt, 'InsertImage', imagePath);
	}
}
function toTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2; 
	
	while(parents_up > 0) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetTop;
}

function toTheLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2;
	
	while(parents_up > 0) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetLeft;
}

function chooseFont(edt, selectname) {
	var idx = document.getElementById(selectname).selectedIndex;
	if (idx != 0) {
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + edt, '');
		edtCommand(edt, cmd, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function insertHTML(html) {
	var edt = currentEDT;
	
	var oEDT;
	if (document.all) {
		oEDT = frames[edt];
	} else {
		oEDT = document.getElementById(edt).contentWindow;
	}
	
	oEDT.focus();
	if (document.all) {
		var oRng = oEDT.document.selection.createRange();
		oRng.pasteHTML(html);
		oRng.collapse(false);
		oRng.select();
	} else {
		oEDT.document.execCommand('insertHTML', false, html);
	}
}

function showHideElement(element, showHide) {
	if (document.getElementById(element)) {
		element = document.getElementById(element);
	}
	
	if (showHide == "show") {
		element.style.visibility = "visible";
	} else if (showHide == "hide") {
		element.style.visibility = "hidden";
	}
}

function setRange(edt) {
	var oEDT;
	if (document.all) {
		oEDT = frames[edt];
		var selection = oEDT.document.selection; 
		if (selection != null) rng = selection.createRange();
	} else {
		oEDT = document.getElementById(edt).contentWindow;
		var selection = oEDT.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	return rng;
}

function stripHTML(oldString) {
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");
	
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");
	
	newString = trim(newString);
	
	return newString;
}

function trim(inputString) {
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
	
   while (ch == " ") { 
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length - 1, retValue.length);
	
   while (ch == " ") { 
      retValue = retValue.substring(0, retValue.length - 1);
      ch = retValue.substring(retValue.length - 1, retValue.length);
   }
	
   while (retValue.indexOf("  ") != -1) {
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
   }
   return retValue;
}
function geckoKeyPress(evt) {
	var edt = 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) {
			edtCommand(edt, cmd, null);
			
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

function ieKeyPress(evt, edt) {
	var key = (evt.which || evt.charCode || evt.keyCode);
	var stringKey = String.fromCharCode(key).toLowerCase();
}

function raiseButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'edtImage' || className == 'edtImageLowered') {
		el.className = 'edtImageRaised';
	}
}

function normalButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'edtImageRaised' || className == 'edtImageLowered') {
		el.className = 'edtImage';
	}
}

function lowerButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'edtImage' || className == 'edtImageRaised') {
		el.className = 'edtImageLowered';
	}
}
