// Script by: Chris Williams
//  - Pure Form Solutions -
// www.PureFormSolutions.com

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

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

initRTE();

function initRTE() {
	//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;
	}
}

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

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

function writeRTE(rte,html,width,height,readOnly) {
	if (isIE != true) {
		width += 2;
	}

	document.writeln('<iframe id="' + rte + '" name="' + rte + '" width="' + width + '" height="' + height + '" style=\"border: 1px solid #000000; float: left;\"></iframe>');
	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 = "<html id=\"" + rte + "\">\n";
	frameHtml += "<head>\n";
	frameHtml += "<style>\n";

	frameHtml += "body {\n";
	frameHtml += "	font-size: 11px;\n";
	frameHtml += "	color: #000000;\n";
	frameHtml += "	font-family: arial, sans-serif;\n";
	frameHtml += "	border: 0px solid #ffffff;\n";
	frameHtml += "	background: #ffffff;\n";
	frameHtml += "	margin: 0px;\n";
	frameHtml += "	padding: 0px;\n";
	frameHtml += "}\n";

	frameHtml += "p {\n";
	frameHtml += "	margin-top: 0px;\n";
	frameHtml += "	margin-bottom: 0px;\n";
	frameHtml += "}\n";

	frameHtml += "a {\n";
	frameHtml += "	color: #051e7a;\n";
	frameHtml += "	text-decoration: none;\n";
	frameHtml += "}\n";

	frameHtml += "a:hover {\n";
	frameHtml += "	color: #051e7a;\n";
	frameHtml += "}\n";

	frameHtml += "</style>\n";
	frameHtml += "</head>\n";
	frameHtml += "<body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";

	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) {
			oRTE.designMode = "On";
		}
	} 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);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");",10);
			} else {
				return false;
			}
		}
	}
}

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

	try {
		if (isRichText) {
			if (oHdnMessage.value == null) {
				oHdnMessage.value = "";
			}
			if (document.all) {
				oHdnMessage.value = frames[rte].document.body.innerHTML;
			} else {
				oHdnMessage.value = oRTE.contentWindow.document.body.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 = "";
			}
		}
	} catch (_e) {
		// fuck it //
	}
}

//Function to format text in the text box
function formatText(rte,command,option) {
	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();
	}

	try {
		if (command == "createlink") {
			alert("For a link to another website or webpage type the prefix \"http://\" BEFORE the url [i.e. http://www.google.com].\n\nIf you are linking to an Email address, type the prefix \"mailto:\" [i.e. mailto:you@mail.com]");
			var szURL = prompt("Please enter an Email address or URL:","");
			try {
				// ignore error for blank urls
				oRTE.document.execCommand("Unlink",false,null);
				oRTE.document.execCommand("CreateLink",false,szURL);
			} catch (e) {
				// do nothing
			}
		} else {
			oRTE.focus();
		  	oRTE.document.execCommand(command,false,option);
			oRTE.focus();
		}
	} catch (e) {
		alert(e);
	}
}

// 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();
		document.getElementById(selectname).selectedIndex = 0;
	}
}

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

	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = "";
		switch (key) {
			case "b": cmd = "bold"; break;
			case "i": cmd = "italic"; break;
			case "u": cmd = "underline"; break;
		};

		if (cmd) {
			formatText(rte,cmd,true);

			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

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