// Cross-Browser Rich Text Editor  v2.0
// http://www.kevinroth.com/rte/demo.htm
// Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM)
// Edited by Robert Fuess to be configurable and to process images differently
//
//  allow undo feature

//init variables
var isRichText = false;
var rng;
var currentRTE;

//added init variables
var EnableViewHTML = true;
var EnableViewLink = true;
var EnableUndo = true;
var EnableInsertImage = false;

var ImageFolder = "RichTextArea/images";
var EnableViewImage = false;
var indentEnabled = false;
var fontEnabled = false;
var headEnabled = false;
var tableColumns = 13;
var sizeDownOneRow = false;
var showSize = true;
var styleSheet = '';
var showWarning = false;

function SetShowWarning(showIt) {
  showWarning = showIt;
}



//=====================================
//added to enable/disable for features
//=====================================
function SetEnableInsertImage (canInsertImage) {
  EnableInsertImage = canInsertImage;
}

/*
  SetStyleSheet('<LINK href="style/MAIN.CSS" type="text/css" rel="stylesheet">');
*/
function SetStyleSheet (newStyleSheet) {  
  if (newStyleSheet != "") {
      styleSheet = '<LINK href="' + newStyleSheet + '" type="text/css" rel="stylesheet">';
  }
}

function GetEnableInsertImage () {
  return EnableInsertImage;
}

function SetEnableViewHTML (canView) {
  EnableViewHTML = canView;
}
function GetEnableViewHTML () {
  return EnableViewHTML;
}

function SetEnableUndo (canUndo) {
  EnableUndo = canUndo;
}
function GetEnableUndo () {
  return EnableUndo;
}

function SetEnableLink (canView) {
  EnableViewLink = canView;
}
function GetEnableLink () {
  return EnableViewLink;
}

function SetEnableImage (canView) {
  EnableViewImage = canView;
}
function GetEnableImage () {
  return EnableViewImage;
}

function SetImageFolder (folder) {
  ImageFolder = folder;
}
function GetImageFolder () {
  return ImageFolder;
}

function EnableHead () {
  headEnabled = true;
}

function EnableIndent () {
  indentEnabled = true;
}

function EnableFont () {
  fontEnabled = true;
}

function PutSizeDownOneRow () {
  sizeDownOneRow = true;
}


function HideSize() {
   showSize=false; //default is false
}

function initRTE() {
       
	//check to see if designMode mode is available
	if (document.getElementById) {
		if (document.all) {
			//check for internet explorer 5.5+
			if (document.URLUnencoded) isRichText = true;
			//window.history.forward(); //try to avoid error with going back
		} else {
			//check for browsers that support designmode
			if (!document.layers) {
			  if (document.designMode) {
			      isRichText = true;
			   }
			}
		}
	}
}

function writeRichText(rte, html, width, height, buttons) {
	if (isRichText) {
		writeRTE(rte,styleSheet+ html, width, height, buttons);
	} else {
		writeDefault(rte, html, width, height, buttons);
	}
}

function writeDefault(rte, html, width, height, buttons) {
	document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' 
	                + html
	                + '</textarea>');
}

function writeRTE(rte, html, width, height, buttons) {
	if (buttons == true) {
		document.writeln('<style type="text/css">');
		document.writeln('.btnImage {cursor: pointer; cursor: hand;}');
		document.writeln('</style>');

		document.writeln('<table class="RTEBehindButtons" id="Buttons2_' + rte + '" cellpadding="1" cellspacing="0">');
		document.writeln('	<tr>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_bold.gif" width="25" height="24" alt="Bold" title="Bold" onClick="FormatText(\'' + rte + '\', \'bold\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_italic.gif" width="25" height="24" alt="Italic" title="Italic" onClick="FormatText(\'' + rte + '\', \'italic\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_underline.gif" width="25" height="24" alt="Underline" title="Underline" onClick="FormatText(\'' + rte + '\', \'underline\', \'\')"></td>');
		document.writeln('		<td>&nbsp;</td>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_left_just.gif" width="25" height="24" alt="Align Left" title="Align Left" onClick="FormatText(\'' + rte + '\', \'justifyleft\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_centre.gif" width="25" height="24" alt="Center" title="Center" onClick="FormatText(\'' + rte + '\', \'justifycenter\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_right_just.gif" width="25" height="24" alt="Align Right" title="Align Right" onClick="FormatText(\'' + rte + '\', \'justifyright\', \'\')"></td>');
		document.writeln('		<td>&nbsp;</td>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_numbered_list.gif" width="25" height="24" alt="Ordered List" title="Ordered List" onClick="FormatText(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_list.gif" width="25" height="24" alt="Unordered List" title="Unordered List" onClick="FormatText(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>');
		document.writeln('		<td>&nbsp;</td>');
		
		if (EnableViewLink) {
		   document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_hyperlink.gif" width="25" height="24" alt="Insert Link" title="Insert Link" onClick="FormatText(\'' + rte + '\', \'createlink\')"></td>');
		   tableColumns = tableColumns + 1;
		}
		if (indentEnabled) {
				//assert: should show indent tags
				document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_outdent.gif" width="25" height="24" alt="Outdent" title="Outdent" onClick="FormatText(\'' + rte + '\', \'outdent\', \'\')"></td>');
				document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_indent.gif" width="25" height="24" alt="Indent" title="Indent" onClick="FormatText(\'' + rte + '\', \'indent\', \'\')"></td>');
		        document.writeln('		<td>&nbsp;</td>');
		        tableColumns = tableColumns + 3;
		}
		if (EnableInsertImage) {
		   document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_image.gif" width="25" height="24" alt="Add Image" title="Add Image" onClick="AddImage(\'' + rte + '\')"></td>');
		}
		document.writeln('		<td><div id="forecolor"><img class="btnImage" src="' +  GetImageFolder() + '/post_button_textcolor.gif" width="25" height="24" alt="Text Color" title="Text Color" onClick="FormatText(\'' + rte + '\', \'forecolor\', \'\')"></div></td>');
		document.writeln('		<td><div id="hilitecolor"><img class="btnImage" src="' +  GetImageFolder() + '/post_button_bgcolor.gif" width="25" height="24" alt="Background Color" title="Background Color" onClick="FormatText(\'' + rte + '\', \'hilitecolor\', \'\')"></div></td>');
		
		
		if (!sizeDownOneRow && showSize) {
		  document.writeln('		<td>');
          document.writeln('			<select unselectable="on" id="fontsize" onchange="Select(\'' + rte + '\', this.id);">');
		  document.writeln('				<option value="Size">Size</option>');
		  document.writeln('				<option value="1">1</option>');
		  document.writeln('				<option value="2">2</option>');
		  document.writeln('				<option value="3">3</option>');
		  document.writeln('				<option value="4">4</option>');
		  document.writeln('				<option value="5">5</option>');
		  document.writeln('				<option value="6">6</option>');
		  document.writeln('				<option value="7">7</option>');
		  document.writeln('			</select>');
		  document.writeln('		</td>');
		  tableColumns = tableColumns + 1;
		}
		
		
		if (EnableUndo && !sizeDownOneRow) {
		  document.writeln('		<td>&nbsp;</td>');
		  document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_undo.gif" width="25" height="24" alt="Undo" title="Undo" onClick="FormatText(\'' + rte + '\', \'undo\')"></td>');
		  document.writeln('		<td><img class="btnImage" src="' +  GetImageFolder() + '/post_button_redo.gif" width="25" height="24" alt="Redo" title="Redo" onClick="FormatText(\'' + rte + '\', \'redo\')"></td>');
		  tableColumns = tableColumns + 3;
		}	
		document.writeln('	</tr>');
		
		//these things go in the next row
		if (fontEnabled || headEnabled || sizeDownOneRow) {
		  document.writeln('	<tr>');
		  document.writeln('		<td colspan="' + tableColumns + '">');		   
		  if (fontEnabled) {
		    document.writeln('			<select id="fontname" name="selectFont" onchange="Select(\'' + rte + '\', 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>');
		  }		  
		  if (headEnabled) {		
		    document.writeln('			<select id="formatblock" onchange="Select(\'' + rte + '\', this.id);">');
		    document.writeln('				<option value="<p>">Normal</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="<h5>">Heading 5 <h5></option>');
		    document.writeln('				<option value="<h6>">Heading 6 <h6></option>');
		    document.writeln('				<option value="<address>">Address <ADDR></option>');
		    document.writeln('				<option value="<pre>">Formatted <pre></option>');
		    document.writeln('			</select>');
		  }		   
		  if (sizeDownOneRow && showSize) {
		    document.writeln('			<select unselectable="on" id="fontsize" onchange="Select(\'' + rte + '\', this.id);">');
		    document.writeln('				<option value="Size">Size</option>');
		    document.writeln('				<option value="1">1</option>');
		    document.writeln('				<option value="2">2</option>');
		    document.writeln('				<option value="3">3</option>');
		    document.writeln('				<option value="4">4</option>');
		    document.writeln('				<option value="5">5</option>');
		    document.writeln('				<option value="6">6</option>');
		    document.writeln('				<option value="7">7</option>');
		    document.writeln('			</select>');
		    if (EnableUndo) {
		       document.writeln('		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
		       document.writeln('		<img class="btnImage" src="' +  GetImageFolder() + '/post_button_undo.gif" width="25" height="24" alt="Undo" title="Undo" onClick="FormatText(\'' + rte + '\', \'undo\')">');
		       document.writeln('		<img class="btnImage" src="' +  GetImageFolder() + '/post_button_redo.gif" width="25" height="24" alt="Redo" title="Redo" onClick="FormatText(\'' + rte + '\', \'redo\')">');
		    }
		    if (showWarning) {
		       document.writeln('<small><span style="color:red; font-weight:bold">DO NOT use <i>Back</i> Button</span></small>');
		    }
		  }
		  
		  document.writeln('		</td>');		
		  document.writeln('	</tr>');
		}
		
		document.writeln('</table>');
	}
	document.writeln('<iframe id="' + rte + '" width="' + width + 'px" height="' + height + 'px" src="blank.htm"><\/iframe>');
    if (GetEnableViewHTML()) {
	      document.writeln('<br><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" \/>&nbsp;View HTML');
    }
    /* height="174" -> height="190" */
	document.writeln('<iframe width="254" height="190" id="cp' + rte + '" src="palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; position: absolute;"><\/iframe>');
	document.writeln('<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="">');
	document.getElementById('hdn' + rte).value = html;
	setTimeout('enableDesignMode(\'' + rte + '\', \'' + html + '\')', 250);
}

function toggleHideExtraButtons() {
  if (!document.layers) {
    if (document.getElementById("ExtraButtons")) {
      if (document.getElementById("ExtraButtons").style.visibility == "hidden") {
         document.getElementById("ExtraButtons").style.visibility = "visible";
      } else {
         document.getElementById("ExtraButtons").style.visibility = "hidden";
      }
    }
  }
}
function enableDesignMode(rte, html) {
	if (document.all) {
		frames[rte].document.open();
		frames[rte].document.write(html);
		frames[rte].document.close();
		frames[rte].document.designMode = "On";
	}
	else {
		var updateHTML = "document.getElementById('" + rte + "').contentWindow.document.body.innerHTML = '" + html + "';";
		setTimeout(updateHTML + "document.getElementById('" + rte + "').contentDocument.designMode = 'On';", 500);
		//attach a keyboard handler for Mozilla to make keyboard shortcuts for formatting text work
		document.getElementById(rte).contentWindow.document.addEventListener("keypress", kb_handler, true);
	}
}

function updateRTE(rte) {
	//set message value
	var oHdnMessage = document.getElementById('hdn' + rte);
	var oMessageFrame = document.getElementById(rte);
	
	if (isRichText) {
		if (oHdnMessage.value == null) oHdnMessage.value = "";
		oHdnMessage.value = oMessageFrame.contentWindow.document.body.innerHTML;
		//exception for Mozilla
		if (oHdnMessage.value.indexOf('<br>') > -1 && oHdnMessage.value.length == 8) oHdnMessage.value = "";
	}
}

function toggleHTMLSrc(rte) {
    toggleHideExtraButtons();  //added to hide extra buttons

	//contributed by Bob Hutzel (thanks Bob!)
	var doc = document.getElementById(rte).contentWindow.document;
	
	if (document.getElementById("chkSrc" + rte).checked) {
	
		document.getElementById("Buttons2_" + rte).style.visibility = "hidden";
				
		if (document.all) {
			doc.body.innerText = doc.body.innerHTML;
		} else {
			var htmlSrc = doc.createTextNode(doc.body.innerHTML);
			doc.body.innerHTML = "";
			doc.body.appendChild(htmlSrc);
		}

	} else {
		//document.getElementById("Buttons1_" + rte).style.visibility = "visible";
		document.getElementById("Buttons2_" + rte).style.visibility = "visible";
		if (document.all) {
			doc.body.innerHTML = doc.body.innerText;
		} else {
			var htmlSrc = doc.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(doc.body);
			doc.body.innerHTML = htmlSrc.toString();
		}
	}
}



//Function to format text in the text box
function FormatText(rte, command, option) {
	if ((command == "forecolor") || (command == "hilitecolor")) {
		parent.command = command;
		buttonElement = document.getElementById(command);
		document.getElementById('cp' + rte).style.left = getOffsetLeft(buttonElement) + "px";
		document.getElementById('cp' + rte).style.top = (getOffsetTop(buttonElement) + buttonElement.offsetHeight) + "px";
		
		if (document.getElementById('cp' + rte).style.visibility == "hidden")
			document.getElementById('cp' + rte).style.visibility="visible";
		else {
			document.getElementById('cp' + rte).style.visibility="hidden";
		}
		
		//get current selected rte
		currentRTE = rte;
		
		//get current selected range
		var sel = document.getElementById(rte).contentWindow.document.selection; 
		if (sel!=null) {
			rng = sel.createRange();
		}
	}
	else if (command == "createlink") { // && browser.isIE55up == false
		var szURL = prompt("Enter a URL:", "");
		//szURL += prompt("Enter a description for this URL:", ""); 
		document.getElementById(rte).contentWindow.document.execCommand("Unlink",false,null)
		document.getElementById(rte).contentWindow.document.execCommand("CreateLink",false,szURL)
	}
	else {
		document.getElementById(rte).contentWindow.focus();
	  	document.getElementById(rte).contentWindow.document.execCommand(command, false, option);
		document.getElementById(rte).contentWindow.focus();
	}
}

//Function to set color
function setColor(color) {
	var parentCommand = parent.command;
	var rte = currentRTE;
	
	if (document.all) {
		//retrieve selected range
		var sel = document.getElementById(rte).contentWindow.document.selection; 
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		if (sel!=null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}
	else {
		document.getElementById(rte).contentWindow.focus();
	}
	document.getElementById(rte).contentWindow.document.execCommand(parentCommand, false, color);
	document.getElementById(rte).contentWindow.focus();
	document.getElementById('cp' + rte).style.visibility="hidden";
}

//Function to add image
function AddImage(rte) {
    var imageName = "";
    imageName = prompt('Enter Image Name:', '');
    var imagePath = "";
    var ampersand = "&amp;";
    
    if (!document.all) {
      ampersand = "&";
    }
    
    if ((imageName != null) && (imageName != "")) {
    
        
        imagePath = 'Picture.aspx?img=' + imageName
	         + ampersand + 'width=';
	     
		imageWidth =  prompt('Enter Image Width:', '100');
		if (imageWidth < 5) {
		   imageWidth=5
		}
		if (imageWidth > 500) {
		   imageWidth=500;
		}
		imagePath += imageWidth;
	    imageAlt = prompt('Enter Image Description:', '');	
	    var s = String(imageAlt);
	    imagePath += ampersand + "alt=" + s.replace(' ','+');
	}
				
	if ((imagePath != null) && (imagePath != "")) {
		document.getElementById(rte).contentWindow.focus()
		document.getElementById(rte).contentWindow.document.execCommand('InsertImage', false, imagePath);
	}
	
	document.getElementById(rte).contentWindow.focus()
}

//function to perform spell check
function checkspell() {
    /*
    //
    // "try" has JavaScript problems in Netscape browsers (4.6)
    //
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		}
		else
			alert("Error Loading ieSpell: Exception " + exception.number);
	}
	*/
}

function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent){
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	//adjusted offset - 200 for HiddenPinesHOA.com (
	return mOffsetTop - 175;
}

function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	//adjusted offset - 200 for HiddenPinesHOA.com
	return mOffsetLeft - 200;
}

function Select(rte, selectname)
{
	var cursel = document.getElementById(selectname).selectedIndex;
	// First one is always a label
	if (cursel != 0) {
		var selected = document.getElementById(selectname).options[cursel].value;
		document.getElementById(rte).contentWindow.document.execCommand(selectname, false, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
	document.getElementById(rte).contentWindow.focus();
}

function kb_handler(evt, rte) {
	//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) {
			evt.target.ownerDocument.execCommand(cmd,false,true);
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

if (!document.layers) {   
  initRTE();
}
