_editor_url = "editor/";
_image_dir = "/usr/"
_image_filter = ".gif,.jpg"

/* 
	Create a regurlar expression consisting of the protocol and domain.  It will be used to strip out 
	domain references in the generated content.
*/
var sDomain = document.URL.substring(0, document.URL.indexOf(document.domain) + document.domain.length);
var domainPattern = new RegExp(sDomain, "gi");

/* ---------------------------------------------------------------------- *\
  Function    : editor_generate
  Description : replace textarea with wysiwyg editor
  Usage       : editor_generate("textarea_id",[height],[width]);
  Arguments   : objname  - ID of textarea to replace
                w        - width of wysiwyg editor
                h        - height of wysiwyg editor
                features - editor features to display. The following is a 
                   list of available features.  
                     font 
                     fontStyles
                     fontExtStyles
                     textAlignment
                     color
                     bullets
                     indent
                     rule
                     link
                     image
                     doclink
                     table
                     wordCleanup
                     viewHTML
\* ---------------------------------------------------------------------- */
function editor_generate(objname, w, h, features) {
   // Default Settings
   var imgURL = _editor_url + 'images/';       // images url
   
   // list of features.
   var edFeatures = {'font':1,'fontStyles':1,'fontExtStyles':1,'textAlignment':1,'color':1,'bullets':1,'indent':1,'rule':1,'link':0,'image':0,'doclink':0,'table':0,'wordCleanup':0,'viewHTML':1 };
      
   // set size to specified size or size of original object
   var obj = document.all[objname];
   if (!w) {
      if (obj.style.width) { width = obj.style.width; }    // use css style
      else if (obj.cols) { width = (obj.cols * 8) + 22; }  // col width + toolbar
      else { width = '100%'; }                             // default
   } else {
      width = w; 
   }
   if (!h) {
      if (obj.style.height) { height = obj.style.height; } // use css style
      else if (obj.rows) { height = obj.rows * 17 }        // row height
      else { height = '200'; }                             // default
   } else {
      height = h; 
   } 
	  
   // Check for IE 5.5+ on Windows
   var Agent, VInfo, MSIE, Ver, Win32, Opera;
   Agent = navigator.userAgent;
   VInfo = Array();                              // version info
   VInfo = Agent.split(";")
   MSIE  = Agent.indexOf('MSIE') > 0;
   Ver   = VInfo[1].substr(6,3);
   Win32 = Agent.indexOf('Windows') > 0 && Agent.indexOf('Mac') < 0 && Agent.indexOf('Windows CE') < 0;
   Opera = Agent.indexOf('Opera') > -1;
   if (!MSIE || Opera || Ver < 5.5 || !Win32) { return; }
   
   if (features){   
      if (features != ""){
         // Determine the features to be exposed
         var aryFeatures = Array();
         aryFeatures = features.split(",");
         
			// turn off all features
         for (n in edFeatures){
            edFeatures[n] = 0;
         }
			
			// turn on selected features
         for (var n = 0; n < aryFeatures.length; n++){
            edFeatures[aryFeatures[n]] = 1;
         }   
      }
   }
  
   var editor = ''
      + '<div id="_' + objname + '_editorDiv" style="border:2px solid ActiveBorder;padding: 3px 5px 3px 5px; background-color: ButtonFace;width:' + width + ';">\n'
		+ '<table id="_' + objname + '_editorTable" border=0 cellspacing=0 cellpadding=0 bgcolor="buttonface" style="padding: 1 0 0 0" width=' + width + ' unselectable="on"><tr><td>\n';
      
		// fullscreen button
      editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:right;"  unselectable="on"><tr><td>\n'
      +    '<button title="Full Screen" id="_' + objname + '_FullScreen" class="btn" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' + imgURL + 'ed_fullscreen.gif" unselectable="on"></button>\n'
      + '</td></tr></table>\n'; 
		
      // font dropdown list
      if (Boolean(edFeatures['font'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;"  unselectable="on">\n'
         + ' <tr>\n'
         + '  <td style="border-width: 0; padding: 2 0 0 3;">\n'
         + '   <select id="_' +objname+ '_FontName" onChange="javascript:editor_action(this.id)" unselectable="on">\n'
         + '   <option value="arial, helvetica, sans-serif">Arial</option>\n'
         + '   <option value="courier new, courier, mono">Courier New</option>\n'
         + '   <option value="Georgia, Times New Roman, Times, Serif">Georgia</option>\n'
         + '   <option value="Tahoma, Arial, Helvetica, sans-serif">Tahoma</option>\n'
         + '   <option value="times new roman, times, serif">Times New Roman</option>\n'
         + '   <option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>\n'
         + '   <option value="wingdings">WingDings</option>\n'
         + '   </select>'
         + '  </td>\n'
         + ' </tr>\n'
         + '</table>\n';
      
         // font sizes
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;"  unselectable="on">\n'
         + ' <tr>\n'
         + '  <td style="border-width: 0; padding: 2 1 0 0;">\n'
         +    '<select id="_' +objname+ '_FontSize" onChange="javascript:editor_action(this.id)" style="width:38px"  unselectable="on">\n'
         + '   <option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option>\n'
         + '   </select>\n\n'
         + '  </td>\n'
         + ' </tr>\n'
         + '</table>\n';
      }
      
      // font styles      
      if (Boolean(edFeatures['fontStyles'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;" unselectable="on"><tr><td>\n'
         +    '<button title="Bold (Ctrl + B)" id="_' +objname+ '_Bold" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_format_bold.gif" unselectable="on"></button>'
         +    '<button title="Italic (Ctrl + I)" id="_' +objname+ '_Italic" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_format_italic.gif" unselectable="on"></button>'
         +    '<button title="Underline (Ctrl + U)" id="_' +objname+ '_Underline" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_format_underline.gif" unselectable="on">\n'
         + '</td></tr></table>\n';
      }
      
      if (Boolean(edFeatures['fontExtStyles'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;" unselectable="on"><tr><td>\n'
         +    '<button title="Strikethrough" id="_' +objname+ '_StrikeThrough" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_format_strike.gif" unselectable="on"></button>'
         +    '<button title="Subscript" id="_' +objname+ '_SubScript" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_format_sub.gif" unselectable="on"></button>'
         +    '<button title="Superscript" id="_' +objname+ '_SuperScript" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_format_sup.gif" unselectable="on">\n'
         + '</td></tr></table>\n'
      }
      
      // text alignment
      if (Boolean(edFeatures['textAlignment'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;" unselectable="on"><tr><td>\n'
         +    '<button title="Justify Left" id="_' +objname+ '_JustifyLeft" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_align_left.gif" unselectable="on"></button>'
         +    '<button title="Justify Center" id="_' +objname+ '_JustifyCenter" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_align_center.gif" unselectable="on"></button>'
         +    '<button title="Justify Right" id="_' +objname+ '_JustifyRight" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_align_right.gif" unselectable="on">\n'
         + '</td></tr></table>\n'; 
      }
         
      // Background and foreground colors
      if (Boolean(edFeatures['color'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;"  unselectable="on" unselectable="on"><tr><td>\n'
         +    '<button title="Font Color" id="_' +objname+ '_ForeColor" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_color_fg.gif" unselectable="on"></button>'
         +    '<button title="Background Color" id="_' +objname+ '_BackColor" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_color_bg.gif" unselectable="on">\n'
         + '</td></tr></table>\n'
       }
           
      // bulleting
      if (Boolean(edFeatures['bullets']) || Boolean(edFeatures['indent'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;"  unselectable="on" unselectable="on"><tr><td>\n';
         if (Boolean(edFeatures['bullets'])){
            editor += '<button title="Ordered List" id="_' +objname+ '_InsertOrderedList" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_list_num.gif" unselectable="on"></button>'
            + '<button title="Bulleted List" id="_' +objname+ '_InsertUnorderedList" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_list_bullet.gif" unselectable="on">\n';
         }
         if (Boolean(edFeatures['indent'])){
            editor += '<button title="Decrease Indent" id="_' +objname+ '_Outdent" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_indent_less.gif" unselectable="on"></button>'
            + '<button title="Increase Indent" id="_' +objname+ '_Indent" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_indent_more.gif" unselectable="on">\n';
         }
         editor += '</td></tr></table>\n';
      }
      
      // Miscellaneous HTML features
      if (Boolean(edFeatures['rule']) || Boolean(edFeatures['link']) || Boolean(edFeatures['image']) || Boolean(edFeatures['doclink'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;" unselectable="on"><tr><td>\n';
                                                                                                   
         if (Boolean(edFeatures['rule'])) {
            editor += '<button title="Horizontal Rule" id="_' +objname+ '_InsertHorizontalRule" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_hr.gif" unselectable="on"></button>';
         }
                                                                                 
         if (Boolean(edFeatures['link'])) {
            editor += '<button title="Insert Web Link (Ctrl + K)" id="_' +objname+ '_CreateLink" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_link.gif" unselectable="on"></button>';
         }
                                                        
         if (Boolean(edFeatures['image'])) {
            editor += '<button title="Insert Image" id="_' +objname+ '_InsertImage" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_image.gif" unselectable="on">\n';
         } 
                                                        
         if (Boolean(edFeatures['doclink'])) {
            editor += '<button title="Insert Resource Link" id="_' +objname+ '_InsertResource" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_doclink.gif" unselectable="on">\n';
         }
         
         editor += '</td></tr></table>\n';
      }
      
      // Table support           
      if (Boolean(edFeatures['table'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;" unselectable="on"><tr><td>\n'
         +    '<button title="Build Table" id="_' +objname+ '_BuildTable" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_table.gif" unselectable="on"></button>'
         + '</td></tr></table>\n';   
      }
      
      
      // Word-generated HTML cleanup
      if (Boolean(edFeatures['wordCleanup'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;" unselectable="on"><tr><td unselectable="on">\n'
         +    '<button title="Cleanup Word HTML" id="_' +objname+ '_cleanhtml" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_cleanup.gif" unselectable="on"></button>'
         + '</td></tr></table>\n';
      }
      
      // View HTML source
      if (Boolean(edFeatures['viewHTML'])) {
         editor += '<table border=0 cellspacing=2 cellpadding=0 bgcolor="buttonface" style="float:left;" unselectable="on"><tr><td>\n'
         +    '<button title="View HTML Source" id="_' +objname+ '_HtmlMode" class="btn" onMouseOver="javascript:highlightButton(this);" onMouseMove="javascript:highlightButton(this);" onMouseOut="javascript:unhighlightButton(this);" onClick="javascript:editor_setmode(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_html.gif" unselectable="on"></button>'
         + '</td></tr></table>\n';
      }

      editor += '</td></tr></table>\n'

      + '<textarea ID="_' +objname + '_editor" style="width:' +width+ '; height:' +height+ '; margin-top: -1px; margin-bottom: -1px;"></textarea>'

      + '<input type="hidden" name="' +objname+ '" value="">';

   // create editor
   var contents = document.all[objname].value;             // get original contents
   document.all[objname].outerHTML = editor;               // create editor frame
   document.all['_'+objname+'_editor'].value = contents;   // set contents

   editor_setmode('_' +objname+ '_HtmlMode', 'init');      // switch to wysiwyg mode
}

/* ---------------------------------------------------------------------- *\
  Function    : editor_action
  Description : perform an editor command on selected editor content
  Usage       :
  Arguments   : button_id - button id string with editor and action name
\* ---------------------------------------------------------------------- */

function editor_action(button_id) {
 
	var BtnParts = Array();
	BtnParts = button_id.split("_");
	var objname    = BtnParts[1];
	var cmdID      = BtnParts[2];
	var button_obj = document.all[button_id];
	var editor_obj = document.all["_" +objname + "_editor"];
	
	// check editor mode (don't perform actions in textedit mode other than toggling to full screen)
	if (editor_obj.tagName.toLowerCase() == 'textarea') {
		if (cmdID.toLowerCase() == 'fullscreen')
			toggleFullscreen(objname);
  	 	
		return; 
	}

  var editdoc = editor_obj.contentWindow.document;
  _editor_focus(editor_obj);

  // execute command for font pulldowns
  var idx = button_obj.selectedIndex;
  if (idx != null) {
    var val = button_obj[ idx ].value;
    editdoc.execCommand(cmdID,0,val);
  }

  // execute command for fgcolor & bgcolor buttons
  else if (cmdID == 'ForeColor' || cmdID == 'BackColor') {
    // figure our optimal window placement for popup dialog
    var posX    = event.screenX;
    var posY    = event.screenY + 20;
    var screenW = screen.width;                                 // screen size
    var screenH = screen.height - 20;                           // take taskbar into account
    if (posX + 232 > screenW) { posX = posX - 232 - 40; }       // if mouse too far right
    if (posY + 164 > screenH) { posY = posY - 164 - 80; }       // if mouse too far down
    var wPosition   = "dialogLeft:" +posX+ "; dialogTop:" +posY;

    var oldcolor = _dec_to_rgb(editdoc.queryCommandValue(cmdID));
    var newcolor = showModalDialog(_editor_url + "select_color.html", oldcolor,
                                   "dialogWidth:238px; dialogHeight: 187px; "
                                   + "resizable: no; help: no; status: no; scroll: no; "
                                   + wPosition);
    if (newcolor != null) { editdoc.execCommand(cmdID, false, "#"+newcolor); }
  }

  // execute command for buttons
  else {
    // subscript & superscript, disable one before enabling the other
    if (cmdID.toLowerCase() == 'subscript' && editdoc.queryCommandState('superscript')) { editdoc.execCommand('superscript'); }
    if (cmdID.toLowerCase() == 'superscript' && editdoc.queryCommandState('subscript')) { editdoc.execCommand('subscript'); }

    // insert link
    if (cmdID.toLowerCase() == 'createlink'){
      editdoc.execCommand(cmdID,1);
    }

    // insert image
    else if (cmdID.toLowerCase() == 'insertimage'){
      var sParam = "root:" + _image_dir + ";filter:" + _image_filter;
      editdoc.body.setAttribute("_imageLibraryParams", sParam)
      window.showModalDialog("imageLibrary.asp", editdoc, "resizable:no; help:no; status:no; scroll:no; font-size:14px; dialogWidth:700px; dialogHeight:520px;")
    }
    // insert image
    else if (cmdID.toLowerCase() == 'insertresource'){
      var sParam = "format:HTML";
      editdoc.body.setAttribute("_resourceLibraryParams", sParam)
      window.showModalDialog("resourceLibrary.asp", editdoc, "resizable:no; help:no; status:no; scroll:no; font-size:14px; dialogWidth:700px; dialogHeight:520px;")
    }
    // insert table
    else if (cmdID.toLowerCase() == 'buildtable'){
      TablePopup(objname);
      // showModalDialog(_editor_url + "insert_table.html", editdoc, "resizable: no; help: no; status: no; scroll: no; ");
    }
    // insert table
    else if (cmdID.toLowerCase() == 'cleanhtml'){
      cleanHTML(objname);
    }
    // full screen
    else if (cmdID.toLowerCase() == 'fullscreen'){
      toggleFullscreen(objname);
    }
    // all other commands
    else {
      editdoc.execCommand(cmdID);
    }
  }

  editor_updateUI(objname);
}

var fullscreenMode = false;
function toggleFullscreen(objname) {
	var editorDiv = document.all["_" + objname + "_editorDiv"];
	var toolbar = document.all["_" + objname + "_editorTable"];
   var editor = document.all["_" + objname + "_editor"];					
	var button_obj = document.all["_" +objname+ "_FullScreen"];    // get button object
 	
	if (!fullscreenMode)
	{										
		button_obj.className = "btnDN"; 
							  
		var coll = document.all.tags("select");
		if (coll != null)
		{				
			for (var i=0; i<coll.length; i++)
			{
				if (coll[i].id.indexOf("_" + objname) != 0)
			   	coll[i].runtimeStyle.display = "none";
			}
		}
																			 
		
		var el = editorDiv.parentElement.offsetParent;
		var leftPos	= 0;
		var topPos = 0;						 
		
		editorDiv.parentElement.runtimeStyle.position = "absolute";
		editorDiv.parentElement.runtimeStyle.margin = 0;
		editorDiv.parentElement.runtimeStyle.padding = 5;
		editorDiv.parentElement.runtimeStyle.posTop = topPos;				
		editorDiv.parentElement.runtimeStyle.posLeft = leftPos;	
		editorDiv.parentElement.runtimeStyle.zIndex = 999;	
		editorDiv.parentElement.runtimeStyle.backgroundColor = "#f9f9f9";	
		
		editorDiv.parentElement.runtimeStyle.width = parent.document.body.clientWidth;
		editorDiv.parentElement.runtimeStyle.height = parent.document.body.offsetHeight - editorDiv.offsetTop - 20;
				
		editorDiv.runtimeStyle.position = "absolute";
		editorDiv.runtimeStyle.zIndex = 999;
		editorDiv.runtimeStyle.width = parent.document.body.clientWidth - 10;
		editorDiv.runtimeStyle.height = parent.document.body.offsetHeight - editorDiv.offsetTop - 20;
		
		toolbar.runtimeStyle.width = "100%";
			
		editor.runtimeStyle.width = "100%";
		editor.runtimeStyle.height = parent.document.body.offsetHeight - editorDiv.offsetTop - editor.offsetTop - 20;
		editor.runtimeStyle.zIndex = 999;
		window.document.body.scrollTop = 0;
		editor.focus();	
		 
		//  Disable the ability to switch between WYSIWYG and HTML modes when the editor is maximized.  This is a hack
		//  to overcome a sizing problem which can be reproduced by:
		// 		1.) maximizing the editor; 
		//			2.) switching to one mode and then back to the original mode; and 
		//  		3.) minimizing the editor again.
      var button_obj = document.all["_" +objname+ "_HtmlMode"];   
      if (button_obj) {                      
      	button_obj.className = 'btnNA';
      	button_obj.disabled = true;
		}
		
		fullscreenMode = true;
	} 
	else 
	{		  
		button_obj.className = "btn";
			  
		var coll = document.all.tags("select");
		if (coll != null)
		{
			for (i=0; i<coll.length; i++) 
		      coll[i].runtimeStyle.display = "block";
		}
		
		editorDiv.parentElement.runtimeStyle.cssText = "";	 
		editorDiv.runtimeStyle.cssText = "";
		toolbar.runtimeStyle.cssText = "";
		editor.runtimeStyle.cssText = "";
		editor.focus();
		
		// Reenable the WYSIWYG/HTML mode button						                          
      var button_obj = document.all["_" +objname+ "_HtmlMode"]; 
      if (button_obj) {
      	button_obj.className = 'btn';
      	button_obj.disabled = false;
		}
		
		fullscreenMode = false;
	}
}

/********************************************************************/
/*						Table Creation Stuff								
/********************************************************************/
var oSel_Table //selection state
var sType_Table
var editor_obj

function GetElement(oElement,sMatchTag){
	while (oElement!=null && oElement.tagName!=sMatchTag){
		if(oElement.id==editor_obj.id) return null;
		oElement = oElement.parentElement;
   }
	return oElement;
}

function TablePopup(objname) {
   editor_obj = document.all["_" +objname + "_editor"];
	editor_obj.focus();
   
	var oSel	= editor_obj.document.selection.createRange();
	var sType = editor_obj.document.selection.type;
		
	oSel_Table = oSel;
	sType_Table = sType;

	var oBlock = (oSel.parentElement != null ? GetElement(oSel.parentElement(),"TABLE") : GetElement(oSel.item(0),"TABLE"));
	if (oBlock!=null){
  		var args = new Array();
  		var arr = null;
  		args["EditTable"] = true;
  		args["cellPadding"] = oBlock.cellPadding;
  		args["cellSpacing"] = oBlock.cellSpacing;
  		args["border"] = oBlock.border;
  		args["borderColor"] = oBlock.borderColor;
  		args["background"] = oBlock.background;
  		args["bgColor"] = oBlock.bgColor;
  		arr = null;
  		arr = showModalDialog(_editor_url + "insert_table.html",args,"dialogWidth:23em;dialogHeight:22em;");			
	} else {
  		var args = new Array();
  		var arr = null;	
  		args["EditTable"] = false;
  		arr = null;
  		arr = showModalDialog(_editor_url + "insert_table.html",args,"dialogWidth:23em; dialogHeight:22em; ");			
   }
	if(arr==null)return;
	if(arr["action"]=="insert")TableInsert(objname, arr);
	if(arr["action"]=="update")TableUpdate(objname,arr);
	if(arr["action"]=="insrow")TableInsertRow();
	if(arr["action"]=="inscol")TableInsertCol();
}

function TableInsert(objname, arr){
   editor_obj = document.all["_" +objname + "_editor"];
	var sHTML = ""
		+ "<TABLE width='40%' "
		+ (((arr["border"]=="") || (arr["border"]=="0")) ? "class=\"NOBORDER\"" : "")
		+	(arr["cellPadding"] != "" ? "cellPadding=\"" + arr["cellPadding"] + "\" " : "")
		+	(arr["cellSpacing"] != "" ? "cellSpacing=\"" + arr["cellSpacing"] + "\" " : "")
		+	(arr["border"] != "" ? "border=\"" + arr["border"] + "\" " : "")
		+	(arr["borderColor"] != "" ? "bordercolor=\"" + arr["borderColor"] + "\" " : "")
		+	(arr["background"] != "" ? "background=\"" + arr["background"] + "\" " : "")
		+	(arr["bgColor"] != "" ? "bgColor=\"" + arr["bgColor"] + "\" " : "")
		+ ">"
	for (var i=0; i < arr["rows"]; i++){
		sHTML += "<TR>";
		for (var j=0; j < arr["cols"]; j++)
		   sHTML += "<TD>&nbsp;</TD>";
		sHTML += "</TR>";
	}
	sHTML += "</TABLE>";
		
	editor_obj.focus();
	if (sType_Table=="Control")
      oSel_Table.item(0).outerHTML = sHTML;
	else 
      oSel_Table.pasteHTML(sHTML);
}

function TableUpdate(objname, arr){
   editor_obj = document.all["_" +objname + "_editor"];
	editor_obj.focus();
   
	var oBlock = (oSel_Table.parentElement != null ? GetElement(oSel_Table.parentElement(),"TABLE") : GetElement(oSel_Table.item(0),"TABLE"))
	if (oBlock!=null){
		oBlock.cellPadding = arr["cellPadding"]
		oBlock.cellSpacing = arr["cellSpacing"]
		oBlock.border = arr["border"]
		oBlock.borderColor = arr["borderColor"]
		oBlock.background = arr["background"]
		oBlock.bgColor = arr["bgColor"]
   }
}

function TableInsertRow(){
	var oSel = oSel_Table;
	var oBlock = (oSel.parentElement != null ? GetElement(oSel.parentElement(),"TABLE") : GetElement(oSel.item(0),"TABLE"));
	var elRow = oBlock.insertRow();
	for (var i=0;i<oBlock.rows[0].cells.length;i++){ //num of cols
		var elCell = elRow.insertCell();
		elCell.innerHTML = "&nbsp;";
   }	
}

function TableInsertCol(){
	var oSel = oSel_Table;
	var oBlock = (oSel.parentElement != null ? GetElement(oSel.parentElement(),"TABLE") : GetElement(oSel.item(0),"TABLE"));
	for (var i=0;i<oBlock.rows.length;i++){ //num of rows
		var elCell = oBlock.rows[i].insertCell();
		elCell.innerHTML = "&nbsp;";
   }	
}

/* ---------------------------------------------------------------------- *\
  Function    : editor_updateUI
  Description : update button status, selected fonts, and hidden output field.
  Usage       :
  Arguments   : objname - ID of textarea to replace
                runDelay: -1 = run now, no matter what
                          0  = run now, if allowed
                        1000 = run in 1 sec, if allowed at that point
\* ---------------------------------------------------------------------- */

function editor_updateUI(objname,runDelay) {	 
	var editor_obj  = document.all["_" +objname+  "_editor"];       // html editor object
	if (runDelay == null) 
	{ 
		runDelay = 0; 
	}
	
	var editdoc, editEvent;
  
	// setup timer for delayed updates (some events take time to complete)
	if (runDelay > 0) 
	{ 
		return setTimeout( function(){ editor_updateUI(objname); }, runDelay ); 
	}

	// don't execute more than 3 times a second (eg: too soon after last execution)
	if (this.tooSoon == 1 && runDelay >= 0) 
	{ 	
		// queue all but urgent events
		this.queue = 1; 
		return; 
	} 

	this.tooSoon = 1;
	setTimeout(
		function(){
    		this.tooSoon = 0;
    		if (this.queue) 
			{ 
				editor_updateUI(objname,-1); 
			};
    		this.queue = 0;
    	}, 333);  // 1/3 second

	// check editor mode and update hidden output field
  	if (editor_obj.tagName.toLowerCase() == 'textarea') 
	{  // textedit mode
		
		var sHTML = editor_obj.value.replace(domainPattern, "");
		document.all[objname].value = sHTML;          // update hidden output field
		return;
	} 
	else 
	{                                                                 // WYSIWYG mode
		editdoc = editor_obj.contentWindow.document;                          // get iframe editor document object
		editEvent = editor_obj.contentWindow.event;
		_fix_placeholder_urls(editdoc);
		
//		var sDomain = document.URL.substring(0, document.URL.indexOf(document.domain) + document.domain.length);
//		var domainPattern = new RegExp(sDomain, "gi");
		var sHTML = editdoc.body.innerHTML.replace(domainPattern, "");
		document.all[objname].value = sHTML;                   // update hidden output field
	}

  // update button states
  var IDList = Array('Bold','Italic','Underline','JustifyLeft','JustifyCenter','JustifyRight','InsertOrderedList','InsertUnorderedList');
  for (i=0; i<IDList.length; i++) {                                 // for each button
    var button_obj = document.all["_" +objname+ "_" +IDList[i]];    // get button object
    if (button_obj == null) { continue; }                           // if no btn obj???
    var cmdActive = editdoc.queryCommandState( IDList[i] );
	
	 if (!cmdActive)  {                                  // option is OK
      if (button_obj.className != 'btn') { button_obj.className = 'btn'; }
      if (button_obj.disabled  != false) { button_obj.disabled = false; }
    } else if (cmdActive)  {                            // option already applied or mixed content
      if (button_obj.className != 'btnDN') { button_obj.className = 'btnDN'; }
      if (button_obj.disabled  != false)   { button_obj.disabled = false; }
    }

  }

  // Loop over font pulldowns
  var IDList = Array('FontName','FontSize');
  for (i=0; i<IDList.length; i++) {
    var cmdActive = editdoc.queryCommandState( IDList[i] );
    var button_obj = document.all["_" +objname+ "_" +IDList[i]];   // button object
    button_obj.disabled = false;
  }

  // Get Font Name and Size
  var fontname = editdoc.queryCommandValue('FontName');
  var fontsize = editdoc.queryCommandValue('FontSize');
  if (fontname != null) { fontname = fontname.toLowerCase(); }

  // Set Font face pulldown
  var fontname_obj = document.all["_" +objname+ "_FontName"];
  if (fontname == null) { fontname_obj.value = fontname; }
  else {
    var foundfont;
    var fonts = fontname_obj.length;
    for (i=0; i<fonts; i++) {
      var thisfont = fontname_obj[i].text.toLowerCase();
      if (thisfont == fontname) {
        fontname_obj.selectedIndex = i;
        foundfont = 1;
      }
    }
    if (foundfont != 1) { fontname_obj.value = fontname; }     // for fonts not in list
  }

  // Set Font size pulldown
  var fontsize_obj = document.all["_" +objname+ "_FontSize"];
  if (fontsize == null) { fontsize_obj.value = fontsize;}
  else {
    for (i=0; i<7; i++) {
      var thissize = fontsize_obj[i].text;
      if (thissize == fontsize) { fontsize_obj.selectedIndex = i; }
    }
  }
}
  
function highlightButton(btn){	
	if (btn.className != "btnDN")
		btn.className = "btnHighlight";
}
function unhighlightButton(btn){	
	if (btn.className == "btnHighlight")
		btn.className = "btn";
}


/* ---------------------------------------------------------------------- *\
  Function    : editor_setmode
  Description : change mode between WYSIWYG and HTML editor
  Usage       : editor_setmode(object_id, mode);
  Arguments   : button_id - button id string with editor and action name
                mode      - init, textedit, or wysiwyg
\* ---------------------------------------------------------------------- */

function editor_setmode(button_id, mode) {

	var BtnParts = Array();
	BtnParts = button_id.split("_");
	var objname    = BtnParts[1];
	var cmdID      = BtnParts[2];
	var editor_obj = document.all["_" +objname + "_editor"];
	var editdoc;    // set below
	
	// define different editors
	var width = editor_obj.runtimeStyle.width;
	if (width == "")
		width = editor_obj.style.width;
			
	var height = editor_obj.runtimeStyle.posHeight;
	if (height == "")
		height = editor_obj.style.posHeight;
	
//	var TextEdit   = '<textarea ID="_' +objname + '_editor" style="width:' +editor_obj.style.width+ '; height:' +editor_obj.style.height+ '; margin-top: -1px; margin-bottom: -1px;"></textarea>';
//	var RichEdit   = '<iframe ID="_' +objname+ '_editor" style="width:' +editor_obj.style.width+ '; height:' +editor_obj.style.height+ ';"></iframe>';

	var TextEdit   = '<textarea ID="_' +objname + '_editor" style="width:' + width + '; height:' + height + '; margin-top: -1px; margin-bottom: -1px;"></textarea>';
	var RichEdit   = '<iframe ID="_' +objname+ '_editor" style="width:' + width + '; height:' + height + ';"></iframe>';
	
  //
  // Switch to TEXTEDIT mode
  //

  if (mode == "textedit" || editor_obj.tagName.toLowerCase() == 'iframe') {
    editdoc = editor_obj.contentWindow.document;
    var contents = editdoc.body.createTextRange().htmlText;
    editor_obj.outerHTML = TextEdit;
    editor_obj = document.all["_" +objname + "_editor"];
    editor_obj.value = contents;
    editor_updateUI(objname);

    // disable buttons
    var IDList = Array('Bold','Italic','Underline','StrikeThrough','SubScript','SuperScript','JustifyLeft','JustifyCenter','JustifyRight','InsertOrderedList','InsertUnorderedList','Outdent','Indent','ForeColor','BackColor','InsertHorizontalRule','CreateLink','InsertImage', 'InsertResource', 'cleanhtml', 'BuildTable');
    for (i=0; i<IDList.length; i++) {                                // for each button
      var button_obj = document.all["_" +objname+ "_" +IDList[i]];   // get button object
      if (button_obj == null) { continue; }                          // if no btn obj???
      button_obj.className = 'btnNA';
      button_obj.disabled = true;
    }

    // disable font pulldowns
    var IDList = Array('FontName','FontSize');
    for (i=0; i<IDList.length; i++) {
      var button_obj = document.all["_" +objname+ "_" +IDList[i]];   // button object
      if (button_obj == null) { continue; }                          // if no btn obj???
      button_obj.disabled = true;
    }

    // set event handlers
    editor_obj.onkeypress  = function() { editor_updateUI(objname); }
    editor_obj.onkeyup     = function() { editor_updateUI(objname); }
    editor_obj.onmouseup   = function() { editor_updateUI(objname); }
    editor_obj.ondrop      = function() { editor_updateUI(objname, 100); }     // these events fire before they occur
    editor_obj.oncut       = function() { editor_updateUI(objname, 100); }
    editor_obj.onpaste     = function() { editor_updateUI(objname, 100); }
    editor_obj.onblur      = function() { editor_updateUI(objname, -1); }

    // update hidden output field
    document.all[objname].value = editor_obj.value;

    _editor_focus(editor_obj);
  }

  //
  // Switch to WYSIWYG mode
  //

  else {
    var contents = editor_obj.value;

    // create editor
    editor_obj.outerHTML = RichEdit;
    editor_obj = document.all["_" +objname + "_editor"];

    // get iframe document object
    editdoc    = editor_obj.contentWindow.document; 

    // set editor contents (and default styles for editor)
    editdoc.open();
    editdoc.write(''
      + '<html><head>\n'
		+ '<link rel="STYLESHEET" type="text/css" href="/css/default.css">\n'
      + '<style>\n'
      + 'body { background-color: #FFFFFF; } \n'
      + '</style>\n'
      + '</head>\n'
      + '<body contenteditable="true" topmargin=1 leftmargin=1>'
      + contents
      + '</body>\n'
      + '</html>\n'
      );
    editdoc.close();

    // enable buttons
    var IDList = Array('Bold','Italic','Underline','StrikeThrough','SubScript','SuperScript','JustifyLeft','JustifyCenter','JustifyRight','InsertOrderedList','InsertUnorderedList','Outdent','Indent','ForeColor','BackColor','InsertHorizontalRule','CreateLink','InsertImage', 'InsertResource', 'cleanhtml','BuildTable');
    for (i=0; i<IDList.length; i++) {
      var button_obj = document.all["_" +objname+ "_" +IDList[i]];
      if (button_obj == null) { continue; }
      button_obj.className = 'btn';
      button_obj.disabled = false;
    }

    // set event handlers
    editdoc.onkeypress     = function() { editor_updateUI(objname); }
    editdoc.onkeyup        = function() { editor_updateUI(objname); }
    editdoc.onmouseup      = function() { editor_updateUI(objname); }
    editdoc.body.ondrop    = function() { editor_updateUI(objname, 100); }     // these events fire before they occur
    editdoc.body.oncut     = function() { editor_updateUI(objname, 100); }
    editdoc.body.onpaste   = function() { editor_updateUI(objname, 100); }
    editdoc.body.onblur    = function() { editor_updateUI(objname, -1); }

    // set initial value
    editor_obj.onload      = function() { 
       try {
          load();
       } catch (e){}
      
       editdoc.body.innerHTML = document.all[objname].value;
        
       try { 
         init();
       } catch (e){}
    }

    // update hidden output field
    _fix_placeholder_urls(editdoc);
	var sHTML = editdoc.body.innerHTML.replace(domainPattern, "");
    document.all[objname].value = sHTML;                     // update hidden output field

    // bring focus to editor
    if (mode != 'init') {             // don't focus on page load, only on mode switch
      _editor_focus(editor_obj);
    }

  }

  // Call update UI
  if (mode != 'init') {             // don't update UI on page load, only on mode switch
    editor_updateUI(objname);
  }

}

/* ---------------------------------------------------------------------- *\
  Function    : _editor_focus
  Description : bring focus to the editor
  Usage       : editor_focus(editor_obj);
  Arguments   : editor_obj - editor object
\* ---------------------------------------------------------------------- */

function _editor_focus(editor_obj) {

  // check editor mode
  if (editor_obj.tagName.toLowerCase() == 'textarea') {         // textarea
    var myfunc = function() { editor_obj.focus(); };
    setTimeout(myfunc,100);                                     // doesn't work all the time without delay
  }

  else {                                                        // wysiwyg
    var editdoc = editor_obj.contentWindow.document;            // get iframe editor document object
    var editorRange = editdoc.body.createTextRange();           // editor range
    var curRange    = editdoc.selection.createRange();          // selection range

    if (curRange.length == null &&                              // make sure it's not a controlRange
        !editorRange.inRange(curRange)) {                       // is selection in editor range
      editorRange.collapse();                                   // move to start of range
      editorRange.select();                                     // select
      curRange = editorRange;
    }
  }

}

/* ---------------------------------------------------------------------- *\
  Function    : _dec_to_rgb
  Description : convert dec color value to rgb hex
  Usage       : var hex = _dec_to_rgb('65535');   // returns FFFF00
  Arguments   : value   - dec value
\* ---------------------------------------------------------------------- */

function _dec_to_rgb(value) {
  var hex_string = "";
  for (var hexpair = 0; hexpair < 3; hexpair++) {
    var byte = value & 0xFF;            // get low byte
    value >>= 8;                        // drop low byte
    var nybble2 = byte & 0x0F;          // get low nybble (4 bits)
    var nybble1 = (byte >> 4) & 0x0F;   // get high nybble
    hex_string += nybble1.toString(16); // convert nybble to hex
    hex_string += nybble2.toString(16); // convert nybble to hex
  }
  return hex_string.toUpperCase();
}

/* ---------------------------------------------------------------------- *\
  Function    : _fix_placeholder_urls
  Description : editor make relative urls absolute, this change them back
                if the url contains a placeholder ("***")
  Usage       : _fix_placeholder_urls(editdoc)
  Arguments   : editdoc - reference to editor document
\* ---------------------------------------------------------------------- */

function _fix_placeholder_urls(editdoc) {
  var i;

  // for links
  for (i=0; i < editdoc.links.length; i++) {
    editdoc.links[i].href = editdoc.links[i].href.replace(/^[^*]*(\*\*\*)/, "$1");
  }

  // for images
  for (i=0; i < editdoc.images.length; i++) {
    editdoc.images[i].src = editdoc.images[i].src.replace(/^[^*]*(\*\*\*)/, "$1");
  }

}

/* ---------------------------------------------------------------------- *\
  Function    : editor_insertHTML
  Description : insert string at current cursor position in editor.  If
                two strings are specifed, surround selected text with them.
  Usage       : editor_insertHTML(objname, str1, [str2], reqSelection)
  Arguments   : objname - ID of textarea
                str1 - HTML or text to insert
                str2 - HTML or text to insert (optional argument)
                reqSelection - (1 or 0) give error if no text selected
\* ---------------------------------------------------------------------- */

function editor_insertHTML(objname, str1,str2, reqSel) {
  var editor_obj = document.all["_" +objname + "_editor"];    // editor object
  if (str1 == null) { str1 = ''; }
  if (str2 == null) { str2 = ''; }

  // for non-wysiwyg capable browsers just add to end of textbox
  if (document.all[objname] && editor_obj == null) {
    document.all[objname].focus();
    document.all[objname].value = document.all[objname].value + str1 + str2;
    return;
  }

  // error checking  
  if (editor_obj == null) { return alert("Unable to insert HTML.  Invalid object name '" +objname+ "'."); }

  _editor_focus(editor_obj);

  var tagname = editor_obj.tagName.toLowerCase();
  var sRange;

 // insertHTML for wysiwyg iframe
  if (tagname == 'iframe') {
    var editdoc = editor_obj.contentWindow.document;
    sRange  = editdoc.selection.createRange();
    var sHtml   = sRange.htmlText;

    // check for control ranges
    if (sRange.length) { return alert("Unable to insert HTML.  Try highlighting content instead of selecting it."); }

    // insert HTML
    var oldHandler = window.onerror;
    window.onerror = function() { alert("Unable to insert HTML for current selection."); return true; } // partial table selections cause errors
    if (sHtml.length) {                                 // if content selected
      if (str2) { sRange.pasteHTML(str1 +sHtml+ str2) } // surround
      else      { sRange.pasteHTML(str1); }             // overwrite
    } else {                                            // if insertion point only
      if (reqSel) { return alert("Unable to insert HTML.  You must select something first."); }
      sRange.pasteHTML(str1 + str2);                    // insert strings
    }
    window.onerror = oldHandler;
  }

  // insertHTML for plaintext textarea
  else if (tagname == 'textarea') {
    editor_obj.focus();
    sRange  = document.selection.createRange();
    var sText   = sRange.text;

    // insert HTML
    if (sText.length) {                                 // if content selected
      if (str2) { sRange.text = str1 +sText+ str2; }  // surround
      else      { sRange.text = str1; }               // overwrite
    } else {                                            // if insertion point only
      if (reqSel) { return alert("Unable to insert HTML.  You must select something first."); }
      sRange.text = str1 + str2;                        // insert strings
    }
  }
  else { alert("Unable to insert HTML.  Unknown object tag type '" +tagname+ "'."); }

  // move to end of new content
  sRange.collapse(false); // move to end of range
  sRange.select();        // re-select

}  

   function cleanHTML(objname) {  
      var editor_obj = document.all["_" +objname + "_editor"]; 
      editor_obj.focus();
      
      var oSel = editor_obj.document.selection.createRange();
   	oSel.expand("textedit")
      
      if (confirm('This action will clean the HTML code pasted from MS Word\nWould you like to proceed?')){
   		var temp = oSel.text;
   		temp = temp.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi,"");  
   		temp = temp.replace(/<span([^>])*>(&nbsp;)*\s*<\/span>/gi,""); 
   		temp = temp.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, "<$1$3");
   		temp = temp.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, "<$1$3");
   		temp = temp.replace(/<\\?\??xml[^>]>/gi, "");
   		temp = temp.replace(/<\/?\w+:[^>]*>/gi, "");
     		oSel.pasteHTML(temp);  
   	   editor_obj.focus()
   	}

   }

/* ---------------------------------------------------------------------- */