﻿
//init variables
var isRichText = false;
var rng;
var currentRTE;
var vcurrentRTE;
var allRTEs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;
var bbEnable;
//var SiteAddress="http://localhost/Kanoon/";
var SiteAddress="http://www.araksampadia.com/";

function initRTE(imgPath, incPath, css) {
	//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 && !isKonqueror) {
		isRichText = true;
	}

	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;

	if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');
	
	//for testing standard textarea, uncomment the following line
	//isRichText = false;
}

function writeRichText(rte, html, width, height, buttons, readOnly, bb) {
	if (isRichText) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;
		bbEnable=bb;
		if (readOnly) buttons = false;
		
		//adjust minimum table widths
		if (isIE) {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width;
		} else {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width + 4;
		}
		
        document.writeln('<table height="'+height+'" width="'+width+'">');
		if (buttons == true) {
		    document.writeln('<tr class="rteBack" style="height: auto;"><td>');
			document.writeln('<select id="fontname_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id)" style="float: left; font-family: Tahoma">');
			document.writeln('<option value="Font" selected>[فونت]</option>');
			document.writeln('<option value="Tahoma, Helvetica, sans-serif">Tahoma</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('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
			document.writeln('<select unselectable="on" id="fontsize_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);" style="float: left; font-family: Tahoma">');
			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('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
			document.writeln('<div class="rteDivBack">');
			document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="Bold_'+rte+'" class="rteImage" src="' + imagesPath + 'bold.gif" alt="Bold" title="ضخیم" onClick="rteCommand(\'' + rte + '\', \'bold\', \'\')" unselectable="on" style="width:22px ;height: 22px; float: left" onmouseout="editor_updateToolbar(\''+rte+'\');" /></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="Italic_'+rte+'" class="rteImage" src="' + imagesPath + 'italic.gif" style="width:22px ;height: 22px" alt="Italic" title="ایتالیک" onClick="rteCommand(\'' + rte + '\', \'italic\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');" /></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="Underline_'+rte+'" class="rteImage" src="' + imagesPath + 'underline.gif" alt="Underline" title="زیر خط" onClick="rteCommand(\'' + rte + '\', \'underline\', \'\')" unselectable="on" style="width:22px ;height: 22px" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="Strikethrough_'+rte+'" class="rteImage" src="' + imagesPath + 'strike.gif" style="width:22px ;height: 22px" alt="Strike" title="خط خورده" onClick="rteCommand(\'' + rte + '\', \'strikethrough\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');" /></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
			document.writeln('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
			document.writeln('<div class="rteDivBack">');
			document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="JustifyLeft_'+rte+'" class="rteImage" src="' + imagesPath + 'left_just.gif" style="width:22px ;height: 22px" alt="Align Left" title="تراز سمت چپ" onClick="rteCommand(\'' + rte + '\', \'justifyleft\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="JustifyCenter_'+rte+'" class="rteImage" src="' + imagesPath + 'centre.gif" style="width:22px ;height: 22px" alt="Center" title="تراز مرکز" onClick="rteCommand(\'' + rte + '\', \'justifycenter\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="JustifyRight_'+rte+'" class="rteImage" src="' + imagesPath + 'right_just.gif" style="width:22px ;height: 22px" alt="Align Right" title="تراز سمت راست" onClick="rteCommand(\'' + rte + '\', \'justifyright\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="JustifyFull_'+rte+'" class="rteImage" src="' + imagesPath + 'justifyfull.gif" style="width:22px ;height: 22px" alt="Justify Full" title="تراز کامل" onclick="rteCommand(\'' + rte + '\', \'justifyfull\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
			document.writeln('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
			document.writeln('<div class="rteDivBack">');
			document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="Superscript_'+rte+'" class="rteImage" src="' + imagesPath + 'sup.gif" style="width:22px ;height: 22px" alt="Superscript" title="توان" onClick="rteCommand(\'' + rte + '\', \'superscript\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="Subscript_'+rte+'" class="rteImage" src="' + imagesPath + 'sub.gif" style="width:22px ;height: 22px" alt="Subscript" title="اندیس" onClick="rteCommand(\'' + rte + '\', \'subscript\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
            document.writeln('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
            document.writeln('<div class="rteDivBack">');
			document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="InsertOrderedList_'+rte+'" class="rteImage" src="' + imagesPath + 'numbered_list.gif" style="width:22px ;height: 22px" alt="Ordered List" title="لیست مرتب" onClick="rteCommand(\'' + rte + '\', \'insertorderedlist\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img id="InsertUnorderedList_'+rte+'" class="rteImage" src="' + imagesPath + 'list.gif" style="width:22px ;height: 22px" alt="Unordered List" title="لیست نامرتب" onClick="rteCommand(\'' + rte + '\', \'insertunorderedlist\', \'\')" unselectable="on" onmouseout="editor_updateToolbar(\''+rte+'\');"></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
			document.writeln('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
			document.writeln('<div class="rteDivBack">');
            document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'outdent.gif" style="width:22px ;height: 22px" alt="Outdent" title="کم کردن حاشیه" onClick="rteCommand(\'' + rte + '\', \'outdent\', \'\')" unselectable="on"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'indent.gif" style="width:22px ;height: 22px" alt="Indent" title="افزایش حاشیه" onClick="rteCommand(\'' + rte + '\', \'indent\', \'\')" unselectable="on"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'textcolor.gif" style="width:22px ;height: 22px" alt="Text Color" title="رنگ متن" onClick="dlgColorPalette(\'' + rte + '\', \'forecolor\', \'\')" unselectable="on"></div></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" style="width:22px ;height: 22px" alt="Background Color" title="رنگ زمینه" onClick="dlgColorPalette(\'' + rte + '\', \'hilitecolor\', \'\')" unselectable="on"></div></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
			document.writeln('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
			document.writeln('<div class="rteDivBack">');
			document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'hr.gif" style="width:22px ;height: 22px" alt="Horizontal Rule" title="خط افقی" onClick="rteCommand(\'' + rte + '\', \'inserthorizontalrule\', \'\')" unselectable="on"></div>');
            document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'hyperlink.gif" style="width:22px ;height: 22px" alt="Insert Link" title="قرار دادن لینک" onClick="insertLink(\'' + rte + '\')" unselectable="on"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'image.gif" style="width:22px ;height: 22px" alt="Add Image" title="قرار دادن تصویر" onClick="addImage(\'' + rte + '\')" unselectable="on"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			if(bbEnable){
			    document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'quote.gif" style="width:22px ;height: 22px" alt="Quote" title="نقل قول" onClick="insertHTML(\''+rte+'\',\'[quote][/quote]\')" unselectable="on"></div>');
			    document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
            }
			document.writeln('<div class="rteButtonMid"><div id="table_' + rte + '"><img class="rteImage" src="' + imagesPath + 'insert_table.gif" style="width:22px ;height: 22px" alt="Insert Table" title="قرار دادن جدول" onClick="dlgInsertTable(\'' + rte + '\', \'table\', \'\')" unselectable="on"></div></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
			document.writeln('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
            document.writeln('<div class="rteDivBack">');
            document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'cut.gif" style="width:22px ;height: 22px" alt="Cut" title="برش" onClick="rteCommand(\'' + rte + '\', \'cut\')"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'copy.gif" style="width:22px ;height: 22px" alt="Copy" title="کپی" onClick="rteCommand(\'' + rte + '\', \'copy\')"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'paste.gif" style="width:22px ;height: 22px" alt="Paste" title="چسباندن" onClick="rteCommand(\'' + rte + '\', \'paste\')"></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
			document.writeln('<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" border="0" alt="" unselectable="on" style="float: left">');
			document.writeln('<div class="rteDivBack">');
			document.writeln('<div class="rteButtonLeft"><img src="' + imagesPath + 'ButtonLeft.gif" unselectable="on" style="float: left" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'undo.gif" style="width:22px ;height: 22px" alt="Undo" title="برگشت" onClick="rteCommand(\'' + rte + '\', \'undo\')"></div>');
			document.writeln('<div class="rteSplitter"><img src="' + imagesPath + 'Splitter.gif" unselectable="on" /></div>');
			document.writeln('<div class="rteButtonMid"><img class="rteImage" src="' + imagesPath + 'redo.gif" style="width:22px ;height: 22px" alt="Redo" title="انجام مجدد" onClick="rteCommand(\'' + rte + '\', \'redo\')"></div>');
			document.writeln('<div class="rteButtonRight"><img src="' + imagesPath + 'ButtonRight.gif" unselectable="on" /></div>');
			document.writeln('</div>');
			document.writeln('</td></tr>');
		}
		document.writeln('<tr style="height: 100%"><td>');
		document.writeln('<iframe id="' + rte + '" name="' + rte + '" width=100%; height="' + height + '" src="' + includesPath + 'blank.htm" dir="rtl" class="IFrameClass"></iframe>');
		//if (!readOnly) document.writeln('<br /><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" />&nbsp;View Source');
		document.writeln('<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + '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.writeln('</td</tr>');
		document.writeln('</table>');
		document.getElementById('hdn' + rte).value = html;
		enableDesignMode(rte, html, readOnly);
	} else {
		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 enableDesignMode(rte, html, readOnly) {
	var frameHtml = "<html id=\"" + rte + "\">\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 += "	font-family: Tahoma;\n";
		frameHtml += "	font-size: 2;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
	}
	frameHtml += "</head>\n";
	frameHtml += "<body dir='rtl' style='font-family: Tahoma;'>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";
	
	if (document.all) {
		var oRTE = frames[rte].document;
		var editor_obj = document.getElementById(rte).contentWindow.document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) oRTE.designMode = "On";
		//Handlers for toolbar update
        editor_obj.onkeydown   = function() { editor_updateToolbar(rte); }
        editor_obj.onkeypress  = function() { editor_updateToolbar(rte); }
        editor_obj.onkeyup     = function() { editor_updateToolbar(rte); }
        editor_obj.onmouseup   = function() { editor_updateToolbar(rte); }
        editor_obj.ondrop      = function() { editor_updateToolbar(rte); }
        editor_obj.oncut       = function() { editor_updateToolbar(rte); }
        editor_obj.onpaste     = function() { editor_updateToolbar(rte); }
        editor_obj.onblur      = function() { editor_updateToolbar(rte); }
	} 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();
				//Handlers for toolbar update
				oRTE.addEventListener("keydown", function() { editor_updateToolbar(rte); }, true);
                oRTE.addEventListener("keypress", function() { editor_updateToolbar(rte); }, true);
                oRTE.addEventListener("keyup", function() { editor_updateToolbar(rte); }, true);
                oRTE.addEventListener("mouseup", function() { editor_updateToolbar(rte); }, true);
                oRTE.addEventListener("drop", function() { editor_updateToolbar(rte); }, true);
                oRTE.addEventListener("cut", function() { editor_updateToolbar(rte); }, true);
                oRTE.addEventListener("paste", function() { editor_updateToolbar(rte); }, true);
                oRTE.addEventListener("blur", function() { editor_updateToolbar(rte); }, true);
				if (isGecko && !readOnly) {
					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 editor_updateToolbar(objname) {
  var editor_obj  = document.getElementById(objname);
  // update toolbar state


  var editdoc = editor_obj.contentWindow.document;

  // Set FontName pulldown
  var fontname_obj = document.getElementById("fontname_" +objname);
  if (fontname_obj) {
    var fontname = editdoc.queryCommandValue('FontName');
    if (fontname == null) { fontname_obj.value = null; }
    else {
      var found = 0;
      for (i=0; i<fontname_obj.length; i++) {
        if (fontname.toLowerCase() == fontname_obj[i].text.toLowerCase()) {
          fontname_obj.selectedIndex = i;
          found = 1;
        }
      }
      if (found != 1) { fontname_obj.value = null; }     // for fonts not in list
    }
  }

  // Set FontSize pulldown
  var fontsize_obj = document.getElementById("fontsize_" + objname);
  if (fontsize_obj) {
    var fontsize = editdoc.queryCommandValue('FontSize');
    if (fontsize == null) { fontsize_obj.value = null; }
    else {
      var found = 0;
      for (i=0; i<fontsize_obj.length; i++) {
        if (fontsize == fontsize_obj[i].value) { fontsize_obj.selectedIndex = i; found=1; }
      }
      if (found != 1) { fontsize_obj.value = null; }     // for sizes not in list
    }
  }

  // update button states
  var IDList = Array('Bold','Italic','Underline','Strikethrough','JustifyLeft','JustifyCenter','JustifyRight','JustifyFull','InsertOrderedList','InsertUnorderedList','Superscript','Subscript');
  for (i=0; i<IDList.length; i++) {
    var btnObj = document.getElementById(IDList[i] + "_" + objname);
    if (btnObj == null) { continue; }
    var cmdActive = editdoc.queryCommandState( IDList[i] );

    if (!cmdActive)  {                                  // option is OK
      if (btnObj.className != 'rteImage') { btnObj.className = 'rteImage'; }
      if (btnObj.disabled  != false) { btnObj.disabled = false; }
    } else if (cmdActive)  {                            // option already applied or mixed content
      if (btnObj.className != 'rteImageLowered') { btnObj.className = 'rteImageLowered'; }
      if (btnObj.disabled  != false)   { btnObj.disabled = false; }
    }
  }
}

function UpdateButtonState(objname,action){
    var editor_obj  = document.getElementById(objname);
    var editdoc = editor_obj.contentWindow.document;
    var btnObj = document.getElementById(action + "_" + objname);
    var cmdActive = editdoc.queryCommandState( action );

    if (!cmdActive)  {                                  // option is OK
      if (btnObj.className != 'rteImage') { btnObj.className = 'rteImage'; }
      if (btnObj.disabled  != false) { btnObj.disabled = false; }
    } else if (cmdActive)  {                            // option already applied or mixed content
      if (btnObj.className != 'rteImageLowered') { btnObj.className = 'rteImageLowered'; }
      if (btnObj.disabled  != false)   { btnObj.disabled = 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);
	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 (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 = "";
	}
}

function rteCommand(rte, command, option) {
	//function to perform command
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	try {
		oRTE.focus();
	  	oRTE.document.execCommand(command, false, option);
		oRTE.focus();
	} catch (e) {
	}
	editor_updateToolbar(rte);
}

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) {
		showHideElement("Buttons1_" + rte, "hide");
		showHideElement("Buttons2_" + rte, "hide");
		if (document.all) {
			oRTE.body.innerText = oRTE.body.innerHTML;
		} else {
			var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		showHideElement("Buttons1_" + rte, "show");
		showHideElement("Buttons2_" + rte, "show");
		if (document.all) {
			//fix for IE
			var output = escape(oRTE.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");
			
			oRTE.body.innerHTML = unescape(output);
		} else {
			var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
	}
}

function dlgColorPalette(rte, command) {
	//function to display or hide color palettes
	setRange(rte);
	
	//get dialog position
	var oDialog = document.getElementById('cp' + rte);
	var buttonElement = document.getElementById(command + '_' + rte);
	var iLeftPos = getOffsetLeft(buttonElement);
	var iTopPos = getOffsetTop(buttonElement) + (buttonElement.offsetHeight + 4);
	oDialog.style.left = (iLeftPos) + "px";
	oDialog.style.top = (iTopPos) + "px";
	
	if ((command == parent.command) && (rte == currentRTE)) {
		//if current command dialog is currently open, close it
		if (oDialog.style.visibility == "hidden") {
			showHideElement(oDialog, 'show');
		} else {
			showHideElement(oDialog, 'hide');
		}
	} else {
		//if opening a new dialog, close all others
		var vRTEs = allRTEs.split(";");
		for (var i = 0; i < vRTEs.length; i++) {
			showHideElement('cp' + vRTEs[i], 'hide');
		}
		showHideElement(oDialog, 'show');
	}
	
	//save current values
	parent.command = command;
	currentRTE = rte;
}

function dlgInsertTable(rte, command) {
    vcurrentRTE=rte;
	//function to open/close insert table dialog
	//save current values
	setRange(rte);
	parent.command = command;
	currentRTE = rte;
	var windowOptions = 'history=no,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=no,width=360,height=200';
	window.open(includesPath + 'insert_table.htm', 'InsertTable', windowOptions);
}

function Smile(command) {
    insertHTML(vcurrentRTE,"<img src='"+SiteAddress+"Smiles/New/"+command+".gif' />");
}

function SmileT(rte, command) {
    insertHTML(rte,"<img src='"+SiteAddress+"Smiles/New/"+command+".gif' />");
}

function SmileW(rte) {
    vcurrentRTE=rte;
	setRange(rte);
	currentRTE = rte;
	var windowOptions = 'history=no,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=285';
	window.open(includesPath + 'Smileys.aspx', 'Smiles', windowOptions);
}

function insertLink(rte) {
	//function to insert link
	var szURL = prompt("Enter a URL:", "");
	try {
		//ignore error for blank urls
		rteCommand(rte, "Unlink", null);
		rteCommand(rte, "CreateLink", szURL);
	} catch (e) {
		//do nothing
	}
}

function setColor(color) {
	//function to set color
	var rte = currentRTE;
	var parentCommand = parent.command;
	
	if (document.all) {
		//retrieve selected range
		var sel = frames[rte].document.selection; 
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		if (sel != null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}
	
	rteCommand(rte, parentCommand, color);
	showHideElement('cp' + rte, "hide");
}

function addImage(rte) {
	//function to add image
	imagePath = prompt('Enter Image URL:', 'http://');				
	if ((imagePath != null) && (imagePath != "")) {
		rteCommand(rte, 'InsertImage', imagePath);
	}
}

function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 1;
	
	while(parents_up > 0) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetTop;
}

function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 1;
	
	while(parents_up > 0) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetLeft;
}

function selectFont(rte, selectname) {
	//function to handle font changes
	var idx = document.getElementById(selectname).selectedIndex;
	// First one is always a label
	if (idx != 0) {
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + rte, '');
		rteCommand(rte, cmd, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function 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) {
			rteCommand(rte, cmd, null);
			
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

function insertHTML(rte,html) {
	var oRTE;
	
	if (rte==null)
	    rte=vcurrentRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	oRTE.focus();
	if (document.all) {
		oRTE.document.selection.createRange().pasteHTML(html);
	} else {
		oRTE.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(rte) {
	//function to store range of current selection
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		var selection = oRTE.document.selection; 
		if (selection != null) rng = selection.createRange();
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
}

function stripHTML(oldString) {
	//function to strip all html
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");
	
	//replace carriage returns and line feeds
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");
	
	//trim string
	newString = trim(newString);
	
	return newString;
}

function trim(inputString) {
   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);
   }
	
   while (retValue.indexOf("  ") != -1) {
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
   }
   return retValue; // Return the trimmed string back to the user
}
