//
// wysiwyg for Ripe Web Manager
//



/* ---------------------------------------------------------------------- *\
  Global Variables: Set global variables such as images directory, 
	                  WYSIWYG Height, Width, and CSS Directory.
\* ---------------------------------------------------------------------- */
	

// Images Directory
imagesDir = PATH_LIBS+"wysiwyg/icons/";


// CSS Directory
cssDir = PATH_LIBS+"wysiwyg/styles/";

// Popups Directory
popupsDir = PATH_LIBS+"wysiwyg/popups/";


// WYSIWYG Width and Height
wysiwygWidth = "100%";
wysiwygHeight = 400;


// Include wordclean js file
document.write('<script language="JavaScript" type="text/javascript" src="'+PATH_LIBS+'wysiwyg/wordclean.js"></script>\n');


// Include Style Sheet
document.write('<link rel="stylesheet" type="text/css" href="' +cssDir+ 'styles.css">\n');

var formatOverride = true;

/* ---------------------------------------------------------------------- *\
  Toolbar Settings: Set the features and buttons available in the WYSIWYG
	                  Toolbar.
\* ---------------------------------------------------------------------- */

// List of available style types
  var Styles2 = new Array();
  Styles2[0] = "Normal";
  Styles2[1] = "Heading 1";
  Styles2[2] = "Heading 2";
  Styles2[3] = "Heading 3";
	Styles2[4] = "Heading 4";
	Styles2[5] = "Heading 5";
	
// List of available style block codes
  var Styles1 = new Array();
  Styles1[0] = "<p>";
  Styles1[1] = "<h1>";
  Styles1[2] = "<h2>";
  Styles1[3] = "<h3>";
	Styles1[4] = "<h4>";
	Styles1[5] = "<h5>";


// List of available font types
  var Fonts = new Array();
  Fonts[0] = "Arial";
  Fonts[1] = "Sans Serif";
  Fonts[2] = "Tahoma";
	Fonts[3] = "Verdana";
	Fonts[4] = "Courier New";
	Fonts[5] = "Georgia";
	Fonts[6] = "Times New Roman";
	Fonts[7] = "Impact";
  Fonts[8] = "Comic Sans MS";


// List of available font sizes
var FontSizes = new Array();
  FontSizes[0]  = "1";
  FontSizes[1]  = "2";
  FontSizes[2]  = "3";
	FontSizes[3]  = "4";
	FontSizes[4]  = "5";
	FontSizes[5]  = "6";
	FontSizes[6]  = "7";

// Order of available commands in toolbar one
  var buttonNameSL = new Array();
    buttonNameSL[0]  = "bold";
    buttonNameSL[1]  = "italic";
    buttonNameSL[2]  = "underline";
    buttonNameSL[3]  = "seperator";
    buttonNameSL[4]  = "insertimage";
  	buttonNameSL[5]  = "createlink";
    
  var buttonName = new Array();
    buttonName[0]  = "seperator";
    buttonName[1]  = "bold";
    buttonName[2]  = "italic";
    buttonName[3]  = "underline";
  	buttonName[4]  = "strikethrough";
    buttonName[5]  = "seperator";
  	buttonName[6]  = "subscript";
  	buttonName[7]  = "superscript";
  	buttonName[8]  = "seperator";
  	buttonName[9]  = "justifyleft";
  	buttonName[10]  = "justifycenter";
  	buttonName[11] = "justifyright";
  	buttonName[12] = "seperator";
  	buttonName[13] = "unorderedlist";
  	buttonName[14] = "orderedlist";
  	buttonName[15] = "outdent";
  	buttonName[16] = "indent";

// Order of available commands in toolbar two
// If editor var has been set to light then show light toolbar
  var buttonName2L = new Array();
    buttonName2L[0]  = "undo";
  	buttonName2L[1]  = "redo";
    buttonName2L[2]  = "seperator";
    buttonName2L[3]  = "forecolor";
  	buttonName2L[4]  = "backcolor";
  	buttonName2L[5]  = "seperator";
  	buttonName2L[6]  = "cut";
  	buttonName2L[7]  = "copy";
  	buttonName2L[8]  = "paste";
  	buttonName2L[9]  = "seperator";
  	buttonName2L[10]  = "inserttable";
    buttonName2L[11]  = "insertimage";
  	buttonName2L[12]  = "createlink";
    
  var buttonName2 = new Array();
    buttonName2[0]  = "undo";
  	buttonName2[1]  = "redo";
    buttonName2[2]  = "seperator";
    buttonName2[3]  = "forecolor";
  	buttonName2[4]  = "backcolor";
  	buttonName2[5]  = "seperator";
  	buttonName2[6]  = "cut";
  	buttonName2[7]  = "copy";
  	buttonName2[8]  = "paste";
  	buttonName2[9]  = "seperator";
  	//buttonName2[10]  = "columns";
  	buttonName2[10]  = "inserttable";
    buttonName2[11]  = "insertimage";
  	buttonName2[12]  = "createlink";
    buttonName2[13]  = "insertform";
    buttonName2[14]  = "components";
  	buttonName2[15]  = "seperator";
  	buttonName2[16]  = "cleanwordpaste";
    buttonName2[17]  = "seperator";
  	buttonName2[18]  = "goAdvanced";

	
// Order of available commands in toolbar three
var buttonName3 = new Array();
	buttonName3[0]  = "viewSource";
	
// List of available actions and their respective ID and images
var ToolbarList = {
//Name              buttonID                 buttonTitle           buttonImage                            buttonImageRollover                       a href
  "bold":           ['Bold',                 'Bold',               imagesDir + 'bold.gif',               imagesDir + 'bold_on.gif',                  ""],
  "italic":         ['Italic',               'Italic',             imagesDir + 'italics.gif',            imagesDir + 'italics_on.gif',               ""],
  "underline":      ['Underline',            'Underline',          imagesDir + 'underline.gif',          imagesDir + 'underline_on.gif',               ""],
	"strikethrough":  ['Strikethrough',        'Strikethrough',      imagesDir + 'strikethrough.gif',      imagesDir + 'strikethrough_on.gif',               ""],
	"seperator":      ['',                     '',                   imagesDir + 'seperator.gif',          imagesDir + 'seperator.gif',               ""],
	"subscript":      ['Subscript',            'Subscript',          imagesDir + 'subscript.gif',          imagesDir + 'subscript_on.gif',                   ""],
	"superscript":    ['Superscript',          'Superscript',        imagesDir + 'superscript.gif',        imagesDir + 'superscript_on.gif',                 ""],
	"justifyleft":    ['Justifyleft',          'Justify Left',        imagesDir + 'justify_left.gif',       imagesDir + 'justify_left_on.gif',               ""],
	"justifycenter":  ['Justifycenter',        'Justify Center',      imagesDir + 'justify_center.gif',     imagesDir + 'justify_center_on.gif',             ""],
	"justifyright":   ['Justifyright',         'Justify Right',       imagesDir + 'justify_right.gif',      imagesDir + 'justify_right_on.gif',              ""],
	"unorderedlist":  ['InsertUnorderedList',  'Insert Unordered List',imagesDir + 'list_unordered.gif',     imagesDir + 'list_unordered_on.gif',            ""],
	"orderedlist":    ['InsertOrderedList',    'Insert Ordered List',  imagesDir + 'list_ordered.gif',       imagesDir + 'list_ordered_on.gif',              ""],
	"outdent":        ['Outdent',              'Outdent',            imagesDir + 'indent_left.gif',        imagesDir + 'indent_left_on.gif',                 ""],
	"indent":         ['Indent',               'Indent',             imagesDir + 'indent_right.gif',       imagesDir + 'indent_right_on.gif',                ""],
	"cut":            ['Cut',                  'Cut',                imagesDir + 'cut.gif',                imagesDir + 'cut_on.gif',                         ""],
	"copy":           ['Copy',                 'Copy',               imagesDir + 'copy.gif',               imagesDir + 'copy_on.gif',                        ""],
  "paste":          ['Paste',                'Paste',              imagesDir + 'paste.gif',              imagesDir + 'paste_on.gif',                       ""],
	"forecolor":      ['ForeColor',            'ForeColor',          imagesDir + 'forecolor.gif',          imagesDir + 'forecolor_on.gif',                   ""],
	"backcolor":      ['BackColor',            'BackColor',          imagesDir + 'backcolor.gif',          imagesDir + 'backcolor_on.gif',                   ""],
	"undo":           ['Undo',                 'Undo',               imagesDir + 'undo.gif',               imagesDir + 'undo_on.gif',                        ""],
	"redo":           ['Redo',                 'Redo',               imagesDir + 'redo.gif',               imagesDir + 'redo_on.gif',                        ""],
	"columns":        ['columns',              'Column Templates',    imagesDir + 'insert_table.gif',       imagesDir + 'insert_table_on.gif',               'href="'+popupsDir+'columns.php?wysiwyg=area1&host_level='+ level+'&r_acc='+ r_acc+'&keepThis=true&TB_iframe=true&height=400&width=400" class="thickbox" title="Column templates"'],
	"inserttable":    ['InsertTable',          'Insert Table',        imagesDir + 'insert_table.gif',       imagesDir + 'insert_table_on.gif',               'href="'+popupsDir+'create_table.php?wysiwyg=area1&host_level='+ level+'&r_acc='+ r_acc+'&keepThis=true&TB_iframe=true&height=400&width=400" class="thickbox" title="Insert table"'],
	"insertimage":    ['InsertImage',          'Insert Image',        imagesDir + 'insert_picture.gif',     imagesDir + 'insert_picture_on.gif',             'href="'+popupsDir+'insert_image.php?wysiwyg=area1&host_level='+ level+'&r_acc='+ r_acc+'&acc='+ acc+'&keepThis=true&TB_iframe=true&height=400&width=400" class="thickbox" title="Insert image"'],
	"insertform":     ['InsertForm',           'Insert Form',         imagesDir + 'insert_form.gif',        imagesDir + 'insert_form_on.gif',                'href="'+popupsDir+'insert_form.php?wysiwyg=area1&host_level='+ level+'&r_acc='+ r_acc+'&acc='+ acc+'&keepThis=true&TB_iframe=true&height=150&width=300" class="thickbox" title="Insert form"'],
	"createlink":     ['CreateLink',           'Create Link',         imagesDir + 'insert_hyperlink.gif',   imagesDir + 'insert_hyperlink_on.gif',           'href="'+popupsDir+'insert_hyperlink.php?wysiwyg=area1&host_level='+ level+'&r_acc='+ r_acc+'&acc='+ acc+'&keepThis=true&TB_iframe=true&height=340&width=400" class="thickbox" title="Insert link"'],
	"viewSource":     ['ViewSource',           'View Source',         imagesDir + 'view_source.gif',        imagesDir + 'view_source_on.gif',                ""],
	"viewText":       ['ViewText',             'View Text',           imagesDir + 'view_text.gif',          imagesDir + 'view_text_on.gif',                  ""],
	"help":           ['Help',                 'Help',               imagesDir + 'help.gif',               imagesDir + 'help_on.gif',                        ""],
	"selectstyle":    ['SelectStyle',          'Select Style',        imagesDir + 'select_style.gif',       imagesDir + 'select_style_on.gif',               ""],
	"selectfont":     ['SelectFont',           'Select Font',         imagesDir + 'select_font.gif',        imagesDir + 'select_font_on.gif',                ""],
	"selectsize":     ['SelectSize',           'Select Size',         imagesDir + 'select_size.gif',        imagesDir + 'select_size_on.gif',                ""],
	"goAdvanced":     ['GoAdvanced',           'Go Advanced',         imagesDir + 'go_advanced.gif',        imagesDir + 'go_advanced_on.gif',                ""],
	"goBasic":        ['GoBasic',              'Go Basic',            imagesDir + 'go_basic.gif',           imagesDir + 'go_basic_on.gif',                   ""],
	"components":     ['Components',           'Insert Component',    imagesDir + 'components.gif',          imagesDir + 'components_on.gif',                'href="'+popupsDir+'insert_component.php?wysiwyg=area1&host_level='+ level+'&r_acc='+ r_acc+'&acc='+ acc+'&keepThis=true&TB_iframe=true&height=400&width=600" class="thickbox" title="Insert component"'],
  "cleanwordpaste": ['WordClean',            'Word Clean (click after pasting from word)',          imagesDir + 'wordclean.gif',          imagesDir + 'wordclean_on.gif',               ""]


};


// set onoff states for certain buttons

  var onoff = new Array();
  onoff['Bold']               = 0;
  onoff['Italic']             = 0;
  onoff['Underline']          = 0;
  onoff['Justifyleft']        = 0;
  onoff['Justifyright']       = 0;
  onoff['Justifycenter']      = 0;
  onoff['Strikethrough']      = 0;
  onoff['InsertUnorderedList']= 0;
  onoff['InsertOrderedList']  = 0;
  onoff['Justifycenter']      = 0;
  onoff['Superscript']        = 0;
  onoff['Subscript']          = 0;
  onoff['Indent']             = 0;
  onoff['Outdent']            = 0;



// Create viewTextMode global variable and set to 0
// enabling all toolbar commands while in HTML mode
viewTextMode = 0;



/* ---------------------------------------------------------------------- *\
  Function    : generate_wysiwyg()
  Description : replace textarea with wysiwyg editor
  Usage       : generate_wysiwyg("textarea_id");
  Arguments   : textarea_id - ID of textarea to replace
\* ---------------------------------------------------------------------- */
function generate_wysiwyg(textareaID,style) {
 
  	// Hide the textarea 
	document.getElementById(textareaID).style.display = 'none'; 
	
  // Pass the textareaID to the "n" variable.
  var n = textareaID;
	
	// Toolbars width is 2 pixels wider than the wysiwygs
	toolbarWidth = wysiwygWidth;
	
  // Generate WYSIWYG toolbar one
  var toolbar;
  toolbar =  '<table cellpadding="0" cellspacing="0" border="0" class="toolbar1" style="width:' + toolbarWidth + ';"><tr><td style="width: 6px;"><img src="' +imagesDir+ 'seperator2.gif" alt="" hspace="3"></td>';
  
	// Create IDs for inserting Font Type and Size drop downs
	if (editor != 'super_lite'){
	   toolbar += '<td style="width: 90px;"><span id="StyleSelect' + n + '"></span></td>';
	}else{
    buttonName = buttonNameSL;
  }
  
	// Output all command buttons that belong to toolbar one
	for (var i = 0; i <= buttonName.length;) { 
    if (buttonName[i]) {
	    var buttonObj            = ToolbarList[buttonName[i]];
		  var buttonID             = buttonObj[0];
	    var buttonTitle          = buttonObj[1];
      var buttonImage          = buttonObj[2];
		  var buttonImageRollover  = buttonObj[3];
		  var ahref                = buttonObj[4];
	    
			if (buttonName[i] == "seperator") {
		    toolbar += '<td style="width: 12px;" align="center"><img src="' +buttonImage+ '" border=0 unselectable="on" width="2" height="18" hspace="2" unselectable="on"></td>';
			}else if (ahref !== "") {
		    toolbar += '<td style="width: 22px;"><a '+ahref+'><img src="' +buttonImage+ '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button");" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +buttonImageRollover+ '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="20" height="20"></a></td>';
	    }
	    else {
		    toolbar += '<td style="width: 22px;"><img src="' +buttonImage+ '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' + buttonImageRollover + '\';" onmouseout="if(onoff[\''+buttonID+'\'] == 0){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="20" height="20"></td>';
	    }
    }
    i++;
  }

  toolbar += '<td>&nbsp;</td></tr></table>';  

  // Generate WYSIWYG toolbar two
  var toolbar2;
  toolbar2 = '<table cellpadding="0" cellspacing="0" border="0" id="toolbar2" class="toolbar2" style="width:' + toolbarWidth + ';"><tr><td style="width: 6px;"><img src="' +imagesDir+ 'seperator2.gif" alt="" hspace="3"></td>';
 
   if (editor == 'super_lite'){
  	   toolbar2 += '<td style="width: 90px;"><span id="StyleSelect' + n + '"></span></td>';
  	}else if(editor == 'lite'){
      buttonName = buttonNameL;
    }
  
  // Output all command buttons that belong to toolbar two
  for (var j = 0; j <= buttonName2.length;) {
    if (buttonName2[j]) {
	    var buttonObj            = ToolbarList[buttonName2[j]];
		  var buttonID             = buttonObj[0];
	    var buttonTitle          = buttonObj[1];
      var buttonImage          = buttonObj[2];
		  var buttonImageRollover  = buttonObj[3];
		  var ahref                = buttonObj[4];
	  
		  if (buttonName2[j] == "seperator") {
		    toolbar2 += '<td style="width: 12px;" align="center"><img src="' +buttonImage+ '" border=0 unselectable="on" width="2" height="18" hspace="2" unselectable="on"></td>';
			}
			else if (buttonName2[j] == "goAdvanced"){
		    toolbar2 += '<td style="width: 27px;">';
				toolbar2 += '<span id="GoAdvanced' + n + '"><img src="'  +buttonImage+  '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="wide_button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'wide_button\'){className=\'wide_buttonOver\'}; this.src=\'' +buttonImageRollover+ '\';" onmouseout="if(className==\'wide_buttonOver\'){className=\'wide_button\'}; this.src=\'' + buttonImage + '\';" unselectable="on"  width="25" height="20"></span>';
				toolbar2 += '<span id="GoBasic' + n + '"><img src="' +imagesDir+ 'go_basic.gif" border=0 unselectable="on" title="GoBasic"          id="GoBasic"       class="wide_button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'wide_button\'){className=\'wide_buttonOver\'}; this.src=\'' +imagesDir+ 'go_basic_on.gif\';"    onmouseout="if(className==\'wide_buttonOver\'){className=\'wide_button\'}; this.src=\'' +imagesDir+ 'go_basic.gif\';" unselectable="on"  width="25" height="20"></span>';
	      toolbar2 += '</td>';
			}else if (ahref !== "") {
		    toolbar2 += '<td style="width: 22px;"><a '+ahref+'><img src="' +buttonImage+ '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button");" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +buttonImageRollover+ '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="20" height="20"></a></td>';
	    }else{
		    toolbar2 += '<td style="width: 22px;"><img src="' +buttonImage+ '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +buttonImageRollover+ '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="20" height="20"></td>';
	    }
    }
    j++;
  }

  toolbar2 += '<td>&nbsp;</td></tr></table>';  
	
	// Generate WYSIWYG toolbar three
	// do not generate if light version is enabled
  var toolbar3;
  toolbar3 =  '<table cellpadding="0" cellspacing="0" border="0" class="toolbar3" id="toolbar3' + n + '" style="width:' + toolbarWidth + 'px;"><tr><td style="width: 6px;"><img src="' +imagesDir+ 'seperator2.gif" alt="" hspace="3"></td>';
  
	// Create IDs for inserting Font Type and Size drop downs
	toolbar3 += '<td style="width: 90px;"><span id="FontSelect' + n + '"></span></td>';
	toolbar3 += '<td style="width: 60px;"><span id="FontSizes'  + n + '"></span></td>';
  
	// Output all command buttons that belong to toolbar one
	for (var i = 0; i <= buttonName3.length;) { 
    if (buttonName3[i]) {
	    var buttonObj            = ToolbarList[buttonName3[i]];
		  var buttonID             = buttonObj[0];
	    var buttonTitle          = buttonObj[1];
      var buttonImage          = buttonObj[2];
		  var buttonImageRollover  = buttonObj[3];
	    
			if (buttonName3[i] == "seperator") {
		    toolbar3 += '<td style="width: 12px;" align="center"><img src="' +buttonImage+ '" border=0 unselectable="on" width="2" height="18" hspace="2" unselectable="on"></td>';
			}
			else if (buttonName3[i] == "viewSource"){
		    toolbar3 += '<td style="width: 22px;">';
				toolbar3 += '<span id="HTMLMode' + n + '"><img src="'  +buttonImage+  '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +buttonImageRollover+ '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on"  width="20" height="20"></span>';
				toolbar3 += '<span id="textMode' + n + '"><img src="' +imagesDir+ 'view_text.gif" border=0 unselectable="on" title="viewText"          id="ViewText"       class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +imagesDir+ 'view_text_on.gif\';"    onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' +imagesDir+ 'view_text.gif\';" unselectable="on"  width="20" height="20"></span>';
	      toolbar3 += '</td>';
			}
	    else {
		    toolbar3 += '<td style="width: 22px;"><img src="' +buttonImage+ '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' + buttonImageRollover + '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="20" height="20"></td>';
	    }
    }
    i++;
  }

  toolbar3 += '<td>&nbsp;</td></tr></table>';

	// Create iframe which will be used for rich text editing
	var iframe = '<table cellpadding="0" cellspacing="0" border="0" style="width: '+ wysiwygWidth +'; height:' + wysiwygHeight + 'px;border: 1px solid #CCCCCC;"><tr><td valign="top">\n'
  + '<iframe frameborder="0" name="wysiwyg' + n + '" id="wysiwyg' + n + '" ></iframe>\n';
  + '</td></tr>';
  
  iframe += '<tr><td class="wysiwyg-statusbar" style="height:10px;" id="wysiwyg_statusbar_' + n + '">&nbsp;</td></tr></table>';    
  
  
  // Build the wysiwyg editor
  // --------------------------------------------------------------------------------------------------------------------------
  document.write( '<div id="wysiwygEditor">' + toolbar + toolbar2 + toolbar3 + iframe + '</div>');
  
  
  // if editor mode is super light then hide toolbars
  if (editor == "super_lite"){
      document.getElementById('toolbar2').style.display = 'none';
	}
	
	
  // Insert the Font Type and Size drop downs into the toolbar
	outputStyleSelect(n);
  outputFontSelect(n);
	outputFontSizes(n); 
	
  // Hide the dynamic drop down lists for the Font Types and Sizes
  hideStyles(n);
  hideFonts(n);
	hideFontSizes(n);
	
	// Hide the "Text Mode" and "goBasic" button
	document.getElementById("textMode" + n).style.display = 'none'; 
	if (editor != "lite"){
	   document.getElementById("GoBasic" + n).style.display = 'none'; 
	}
	document.getElementById('toolbar3' + n).style.display = 'none';
	
	// Give the iframe the global wysiwyg height and width
  document.getElementById("wysiwyg" + n).style.height = wysiwygHeight + "px";
  document.getElementById("wysiwyg" + n).style.width = wysiwygWidth;
	
	// Pass the textarea's existing text over to the content variable
  var content = document.getElementById(n).value;
	
	var doc = document.getElementById("wysiwyg" + n).contentWindow.document;
	
	/*if (content == "") {
    content = "&nbsp;";
  }*/
  
  
	// Write the textarea's content into the iframe
  doc.open();
  // Add the stylesheet to the iframe
  if (style != ""){
	   doc.write('<head><link rel="stylesheet" type="text/css" href="'+style+'" /></head>');
	}
  doc.write(content);
  doc.close();
	
	
	// Make the iframe editable in both Mozilla and IE
  doc.body.contentEditable = true;
  doc.designMode = "on";
  
  
  
      
  
  // LISTENERS for key presses etc
  // -------------------------------------
  
	
  // Update the textarea with content in WYSIWYG when user submits form
  var browserName = navigator.appName;
  if (browserName == "Microsoft Internet Explorer") {
    for (var idx=0; idx < document.forms.length; idx++) {
      document.forms[idx].attachEvent('onsubmit', function() { updateTextArea(n); });
      
      // keyup capture
      document.frames[idx].document.attachEvent('onkeyup', function() { catchKeyUp(n); });
      
      // capture mousedown inside wysiwyg editor
      doc.attachEvent('onclick', function() { hideAllDrops(n) });
      
      // capture mousedown inside wysiwyg editor
      doc.attachEvent('onmouseup', function() { updateStatusBar(n) });
      
    }
  }
  else {
  	for (var idx=0; idx < document.forms.length; idx++) {
    	document.forms[idx].addEventListener('submit',function OnSumbmit() { updateTextArea(n); }, true);
      
      // clean paste
      doc.addEventListener("keyup", function(event) { catchKeyUp(n) }, true);
      
      // capture mousedown inside wysiwyg editor
 	    doc.addEventListener('mousedown', function(event) { hideAllDrops(n); }, true);
 	    
 	    // capture mousedown inside wysiwyg editor
 	    doc.addEventListener('mouseup', function(event) { updateStatusBar(n); }, true);
 	    
    }
  }
 	

};


/* ---------------------------------------------------------------------- *\
  Function    : formatText()
  Description : replace textarea with wysiwyg editor
  Usage       : formatText(id, n, selected);
  Arguments   : id - The execCommand (e.g. Bold)
                n  - The editor identifier that the command 
								     affects (the textarea's ID)
                selected - The selected value when applicable (e.g. Arial)
\* ---------------------------------------------------------------------- */
function formatText(id, n, selected) {

  // hide droppys
  hideFontSizes(n);
	hideStyles(n); 
  hideFonts(n);
  
  // When user clicks toolbar button make sure it always targets its respective WYSIWYG
  document.getElementById("wysiwyg" + n).contentWindow.focus();
	
	// When in Text Mode these execCommands are disabled
	var formatIDs = new Array("GoBasic","StyleName","FontSize","FontName","Bold","Italic","Underline","Subscript","Superscript","Strikethrough","Justifyleft","Justifyright","Justifycenter","InsertUnorderedList","InsertOrderedList","Indent","Outdent","ForeColor","BackColor","InsertImage","InsertTable","CreateLink");
  
	// Check if button clicked is in disabled list
	for (var i = 0; i <= formatIDs.length;) {
		if (formatIDs[i] == id) {
			 var disabled_id = 1; 
		}
	  i++;
	}
	
	// Check if in Text Mode and disabled button was clicked
	if (viewTextMode == 1 && disabled_id == 1) {
	  alert ("You are in HTML Mode. This feature has been disabled.");	
	}
	
	else {
	
	  // StyleName
	  if (id == "StyleName") {
      document.getElementById("wysiwyg" + n).contentWindow.document.execCommand("formatblock", false, selected);
	  }
	  
	  // FontSize
	  else if (id == "FontSize") {
      document.getElementById("wysiwyg" + n).contentWindow.document.execCommand("FontSize", false, selected);
	  }
	  
		// FontName
	  else if (id == "FontName") {
      document.getElementById("wysiwyg" + n).contentWindow.document.execCommand("FontName", false, selected);
	  }
	
	  // ForeColor and BackColor
    else if (id == 'ForeColor' || id == 'BackColor') {
      var w = screen.availWidth;
      var h = screen.availHeight;
      var popW = 210, popH = 165;
      var leftPos = (w-popW)/2, topPos = (h-popH)/2;
      var currentColor = _dec_to_rgb(document.getElementById("wysiwyg" + n).contentWindow.document.queryCommandValue(id));
   
	    tb_show("",popupsDir + 'select_color.php?color=' + currentColor + '&command=' + id + '&wysiwyg=area1&level='+ level+'&TB_iframe=true&height=160&width=190',false);
    }
	  
		// InsertImage
	  else if (id == "InsertImage") {
      window.open(popupsDir + 'insert_image.php?wysiwyg=' + n + '&level='+ level ,'popup','location=0,status=0,scrollbars=0,resizable=0,width=400,height=400');
	  }
	  
		// InsertTable
	  else if (id == "InsertTable") {
	    window.open(popupsDir + 'create_table.html?wysiwyg=' + n,'popup','location=0,status=0,scrollbars=0,resizable=0,width=400,height=360');
	  }
	  
	  // InsertTable
	  else if (id == "InsertForm") {
	    window.open(popupsDir + 'insert_form.php?wysiwyg=' + n,'popup','location=0,status=0,scrollbars=0,resizable=0,width=300,height=100');
	  }
	  
		// CreateLink
	  else if (id == "CreateLink") {
	    window.open(popupsDir + 'insert_hyperlink.php?wysiwyg=' + n + '&level='+ level ,'popup','location=0,status=0,scrollbars=0,resizable=0,width=380,height=300');
	  }
	  
	  // Insert Component
	  else if (id == "Components") {
	    window.open(popupsDir + 'insert_component.php?wysiwyg=' + n + '&level='+ level ,'popup','location=0,status=0,scrollbars=1,resizable=0,width=500,height=450');
	  }
	  
		// ViewSource
    else if (id == "ViewSource") {
	    viewSource(n);
	  }
		
		// ViewText
		else if (id == "ViewText") {
	    viewText(n);
	  }
	  
	  // GoAdvanced
    else if (id == "GoAdvanced") {
	    goAdvanced(n);
	  }
		
		// GoBasic
		else if (id == "GoBasic") {
	    goBasic(n);
	  }
	  
	  // WordClean
		else if (id == "WordClean") {
		  var t = document.getElementById('wysiwyg').getselection();
	    wordclean(n);
	  }

		// Help
		else if (id == "Help") {
	    window.open(popupsDir + 'about.html','popup','location=0,status=0,scrollbars=0,resizable=0,width=400,height=330');
	  
    // all other things
    }else{
	    // stylewithCSS dosent seem to be working right but turning off and on designmode works
	    var browserName = navigator.appName;
      if (browserName !== "Microsoft Internet Explorer") {
        document.getElementById("wysiwyg" + n).contentWindow.document.execCommand.designMode = "on";
	      document.getElementById("wysiwyg" + n).contentWindow.document.execCommand('styleWithCSS',false,false);
	    }
      document.getElementById("wysiwyg" + n).contentWindow.document.execCommand(id, false, null);
	    if (browserName !== "Microsoft Internet Explorer") {
        document.getElementById("wysiwyg" + n).contentWindow.document.execCommand.designMode = "off";
	      document.getElementById("wysiwyg" + n).contentWindow.document.execCommand.designMode = "on";
      }
      buttonOnOff(id,0,n);
		}
  }
};

/* ---------------------------------------------------------------------- *\
  Function    : buttOnOff()
  Description : decide if the bold button should be set on or off
  Arguments   : id - the button id ie: bold, italic
                n  - The editor identifier that the HTML 
\* ---------------------------------------------------------------------- */
function buttonOnOff(id, ary, n) {
    if (ary==0){
        var ids = new Array();
        ids[0] = id;
    }else{
        var ids = new Array();
        ids = id; 
    
        // reset everything 
        onoff['Bold']               = 0;
        onoff['Italic']             = 0;
        onoff['Underline']          = 0;
        onoff['Justifyleft']        = 0;
        onoff['Justifyright']       = 0;
        onoff['Justifycenter']      = 0;
        onoff['Strikethrough']      = 0;
        onoff['InsertUnorderedList']= 0;
        onoff['InsertOrderedList']  = 0;
        onoff['Justifycenter']      = 0;
        onoff['Superscript']        = 0;
        onoff['Subscript']          = 0;
        onoff['Indent']             = 0;
        onoff['Outdent']            = 0;
        document.getElementById('Bold').className = "button";
        document.getElementById('Italic').className = "button";
        document.getElementById('Underline').className = "button";
        document.getElementById('Justifyleft').className = "button";
        document.getElementById('Justifyright').className = "button";
        document.getElementById('Justifycenter').className = "button";
        document.getElementById('Strikethrough').className = "button";
        document.getElementById('InsertUnorderedList').className = "button";
        document.getElementById('InsertOrderedList').className = "button";
        document.getElementById('Justifycenter').className = "button";
        document.getElementById('Superscript').className = "button";
        document.getElementById('Subscript').className = "button";
        document.getElementById('Indent').className = "button";
        document.getElementById('Outdent').className = "button";
    }
  
    
    // loop through each tag
    for (var i=ids.length - 1;i>=0;i--){
        id = ids[i];
        switch (id){
    		case 'B':
    			id = "Bold";
    			onoff[id] = 0;
    			break;
    		case 'STRONG':
    			id = "Bold";
    			onoff[id] = 0;
    			break;
    		case 'I':
    			id = "Italic";
    			onoff[id] = 0;
    			break;
    		case 'EM':
    			id = "Italic";
    			onoff[id] = 0;
    			break;
    		case 'U':
    			id = "Underline";
    			onoff[id] = 0;
    			break;
    		case 'STRIKE':
    			id = "Strikethrough";
    			onoff[id] = 0;
    			break;
    		case 'SUB':
    			id = "Subscript";
    			onoff[id] = 0;
    			break;
    		case 'SUP':
    			id = "Superscript";
    			onoff[id] = 0;
    			break;
    		case 'UL':
    			id = "InsertUnorderedList";
    			onoff[id] = 0;
    			break;
    		case 'OL':
    			id = "InsertOrderedList";
    			onoff[id] = 0;
    			break;
    	  }
    	  
        if(id == "Bold" || id == "Italic" || id == "Underline" || id == "Strikethrough" || id == "Subscript" || id == "Superscript" || id == "InsertUnorderedList" || id == "InsertOrderedList"){
          if(onoff[id] == 0){
              onoff[id] = 1;
              document.getElementById(id).className = "buttonOver";
          }else{
              onoff[id] = 0;
              document.getElementById(id).className = "button";
          }
        }
        formatOverride = false;
    }
    
    // override because of tags not yet being created
    if (ary == 0){
        if (formatOverride == true){
          if(onoff[id] == 0){
                onoff[id] = 1;
                document.getElementById(id).className = "buttonOver";
          }else{
                onoff[id] = 0;
                document.getElementById(id).className = "button";
          }
          formatOverride = true;
        }
    }
    
    
};




/* ---------------------------------------------------------------------- *\
  Function    : insertHTML()
  Description : insert HTML into WYSIWYG in rich text
  Usage       : insertHTML(<b>hello</b>, "textareaID")
  Arguments   : html - The HTML being inserted (e.g. <b>hello</b>)
                n  - The editor identifier that the HTML 
								     will be inserted into (the textarea's ID)
\* ---------------------------------------------------------------------- */
function insertHTML(html, n) {
  var browserName = navigator.appName;
	 	 
	if (browserName == "Microsoft Internet Explorer") {	  
	  document.getElementById('wysiwyg' + n).contentWindow.document.selection.createRange().pasteHTML(html);   
	} 
	 
	else {
	  var div = document.getElementById('wysiwyg' + n).contentWindow.document.createElement("div");
		 
		div.innerHTML = html;
		var node = insertNodeAtSelection(div, n);		
	}
	
}


/* ---------------------------------------------------------------------- *\
  Function    : insertNodeAtSelection()
  Description : insert HTML into WYSIWYG in rich text (mozilla)
  Usage       : insertNodeAtSelection(insertNode, n)
  Arguments   : insertNode - The HTML being inserted (must be innerHTML 
	                           inserted within a div element)
                n          - The editor identifier that the HTML will be 
								             inserted into (the textarea's ID)
\* ---------------------------------------------------------------------- */
function insertNodeAtSelection(insertNode, n) {
  // get current selection
  var sel = document.getElementById('wysiwyg' + n).contentWindow.getSelection();

  // get the first range of the selection
  // (there's almost always only one range)
  var range = sel.getRangeAt(0);

  // deselect everything
  sel.removeAllRanges();

  // remove content of current selection from document
  range.deleteContents();

  // get location of current selection
  var container = range.startContainer;
  var pos = range.startOffset;

  // make a new range for the new selection
  range=document.createRange();

  if (container.nodeType==3 && insertNode.nodeType==3) {

    // if we insert text in a textnode, do optimized insertion
    container.insertData(pos, insertNode.nodeValue);

    // put cursor after inserted text
    range.setEnd(container, pos+insertNode.length);
    range.setStart(container, pos+insertNode.length);
  } 
	
	else {
    var afterNode;
    
		if (container.nodeType==3) {
      // when inserting into a textnode
      // we create 2 new textnodes
      // and put the insertNode in between

      var textNode = container;
      container = textNode.parentNode;
      var text = textNode.nodeValue;

      // text before the split
      var textBefore = text.substr(0,pos);
      // text after the split
      var textAfter = text.substr(pos);

      var beforeNode = document.createTextNode(textBefore);
      afterNode = document.createTextNode(textAfter);

      // insert the 3 new nodes before the old one
      container.insertBefore(afterNode, textNode);
      container.insertBefore(insertNode, afterNode);
      container.insertBefore(beforeNode, insertNode);

      // remove the old node
      container.removeChild(textNode);
    } 
	
	  else {
      // else simply insert the node
      afterNode = container.childNodes[pos];
      container.insertBefore(insertNode, afterNode);
    }

    range.setEnd(afterNode, 0);
    range.setStart(afterNode, 0);
  }
  
  sel.addRange(range);
};



/* ---------------------------------------------------------------------- *\
  Function    : _dec_to_rgb
  Description : convert a decimal color value to rgb hexadecimal
  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 myByte = value & 0xFF;            // get low byte
    value >>= 8;                          // drop low byte
    var nybble2 = myByte & 0x0F;          // get low nybble (4 bits)
    var nybble1 = (myByte >> 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    : outputStyleSelect()
  Description : creates the Style Select drop down and inserts it into 
	              the toolbar
  Usage       : outputStyleSelect(n)
  Arguments   : n   - The editor identifier that the Style Select will update
	                    when making font changes (the textarea's ID)
\* ---------------------------------------------------------------------- */
function outputStyleSelect(n) {

  var StyleSelectObj        = ToolbarList['selectstyle'];
  var StyleSelect           = StyleSelectObj[2];
  var StyleSelectOn         = StyleSelectObj[3];
  
	var StyleSelectDropDown = new Array;
	StyleSelectDropDown[n] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td onMouseOver="document.getElementById(\'selectStyle' + n + '\').src=\'' + StyleSelectOn + '\';" onMouseOut="document.getElementById(\'selectStyle' + n + '\').src=\'' + StyleSelect + '\';"><img src="' + StyleSelect + '" id="selectStyle' + n + '" width="85" height="20" onClick="showStyles(\'' + n + '\');" unselectable="on"><br />';
	StyleSelectDropDown[n] += '<span id="Styles' + n + '" class="dropdown" style="width: 145px;">';

	for (var i = 0; i <= Styles1.length;) {
	  if (Styles1[i]) {
      StyleSelectDropDown[n] += '<button type="button" onClick="formatText(\'StyleName\',\'' + n + '\',\'' + Styles1[i] + '\')\; hideStyles(\'' + n + '\');" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 120px;"><table cellpadding="0" cellspacing="0" border="0"><tr><td align="left">' + Styles2[i] + '</td></tr></table></button><br />';	
    }	  
	  i++;
  }
	StyleSelectDropDown[n] += '</span></td></tr></table>';
	document.getElementById('StyleSelect' + n).innerHTML = StyleSelectDropDown[n] + document.getElementById('StyleSelect' + n).innerHTML;
};


/* ---------------------------------------------------------------------- *\
  Function    : outputFontSelect()
  Description : creates the Font Select drop down and inserts it into 
	              the toolbar
  Usage       : outputFontSelect(n)
  Arguments   : n   - The editor identifier that the Font Select will update
	                    when making font changes (the textarea's ID)
\* ---------------------------------------------------------------------- */
function outputFontSelect(n) {

  var FontSelectObj        = ToolbarList['selectfont'];
  var FontSelect           = FontSelectObj[2];
  var FontSelectOn         = FontSelectObj[3];
  
	Fonts.sort();
	var FontSelectDropDown = new Array;
	FontSelectDropDown[n] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td onMouseOver="document.getElementById(\'selectFont' + n + '\').src=\'' + FontSelectOn + '\';" onMouseOut="document.getElementById(\'selectFont' + n + '\').src=\'' + FontSelect + '\';"><img src="' + FontSelect + '" id="selectFont' + n + '" width="85" height="20" onClick="showFonts(\'' + n + '\');" unselectable="on"><br />';
	FontSelectDropDown[n] += '<span id="Fonts' + n + '" class="dropdown" style="width: 145px;">';

	for (var i = 0; i <= Fonts.length;) {
	  if (Fonts[i]) {
      FontSelectDropDown[n] += '<button type="button" onClick="formatText(\'FontName\',\'' + n + '\',\'' + Fonts[i] + '\')\; hideFonts(\'' + n + '\');" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 120px;"><table cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family:' + Fonts[i] + '; font-size: 12px;">' + Fonts[i] + '</td></tr></table></button><br />';	
    }	  
	  i++;
  }
	FontSelectDropDown[n] += '</span></td></tr></table>';
	document.getElementById('FontSelect' + n).innerHTML = FontSelectDropDown[n] + document.getElementById('FontSelect' + n).innerHTML;
};



/* ---------------------------------------------------------------------- *\
  Function    : outputFontSizes()
  Description : creates the Font Sizes drop down and inserts it into 
	              the toolbar
  Usage       : outputFontSelect(n)
  Arguments   : n   - The editor identifier that the Font Sizes will update
	                    when making font changes (the textarea's ID)
\* ---------------------------------------------------------------------- */
function outputFontSizes(n) {

  var FontSizeObj        = ToolbarList['selectsize'];
  var FontSize           = FontSizeObj[2];
  var FontSizeOn         = FontSizeObj[3];

	FontSizes.sort();
	var FontSizesDropDown = new Array;
	FontSizesDropDown[n] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td onMouseOver="document.getElementById(\'selectSize' + n + '\').src=\'' + FontSizeOn + '\';" onMouseOut="document.getElementById(\'selectSize' + n + '\').src=\'' + FontSize + '\';"><img src="' + FontSize + '" id="selectSize' + n + '" width="49" height="20" onClick="showFontSizes(\'' + n + '\');" unselectable="on"><br />';
  FontSizesDropDown[n] += '<span id="Sizes' + n + '" class="dropdown" style="width: 170px;">';

	for (var i = 0; i <= FontSizes.length;) {
	  if (FontSizes[i]) {
      FontSizesDropDown[n] += '<button type="button" onClick="formatText(\'FontSize\',\'' + n + '\',\'' + FontSizes[i] + '\')\;hideFontSizes(\'' + n + '\');" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 145px;"><table cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family: arial, verdana, helvetica;"><font size="' + FontSizes[i] + '">size ' + FontSizes[i] + '</font></td></tr></table></button><br />';	
    }	  
	  i++;
  }
	FontSizesDropDown[n] += '</span></td></tr></table>';
	document.getElementById('FontSizes' + n).innerHTML = FontSizesDropDown[n] + document.getElementById('FontSizes' + n).innerHTML;
};


/* ---------------------------------------------------------------------- *\
  Function    : hideFonts()
  Description : Hides the list of font names in the font select drop down
  Usage       : hideFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function hideStyles(n) {
  document.getElementById('Styles' + n).style.display = 'none'; 
};



/* ---------------------------------------------------------------------- *\
  Function    : hideFonts()
  Description : Hides the list of font names in the font select drop down
  Usage       : hideFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function hideFonts(n) {
  document.getElementById('Fonts' + n).style.display = 'none'; 
};



/* ---------------------------------------------------------------------- *\
  Function    : hideFontSizes()
  Description : Hides the list of font sizes in the font sizes drop down
  Usage       : hideFontSizes(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function hideFontSizes(n) {
  document.getElementById('Sizes' + n).style.display = 'none'; 
};




/* ---------------------------------------------------------------------- *\
  capture mousedown and dropdowns to hide
\* ---------------------------------------------------------------------- */


function hideAllDrops(n) {
		hideFontSizes(n);
		hideFonts(n);
		hideStyles(n);
};





/* ---------------------------------------------------------------------- *\
  Function    : showStyles()
  Description : Shows the list of font names in the font select drop down
  Usage       : showStyles(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function showStyles(n) { 
  hideFontSizes(n);
	hideFonts(n);
  if (document.getElementById('Styles' + n).style.display == 'block') {
    document.getElementById('Styles' + n).style.display = 'none';
	}
  else {
    document.getElementById('Styles' + n).style.display = 'block'; 
    document.getElementById('Styles' + n).style.position = 'absolute';		
  }
};


/* ---------------------------------------------------------------------- *\
  Function    : showFonts()
  Description : Shows the list of font names in the font select drop down
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function showFonts(n) { 
  hideFontSizes(n);
	hideStyles(n); 
  if (document.getElementById('Fonts' + n).style.display == 'block') {
    document.getElementById('Fonts' + n).style.display = 'none';
	}
  else {
    document.getElementById('Fonts' + n).style.display = 'block'; 
    document.getElementById('Fonts' + n).style.position = 'absolute';		
  }
};



/* ---------------------------------------------------------------------- *\
  Function    : showFontSizes()
  Description : Shows the list of font sizes in the font sizes drop down
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function showFontSizes(n) {
	hideFonts(n);
	hideStyles(n); 
  if (document.getElementById('Sizes' + n).style.display == 'block') {
    document.getElementById('Sizes' + n).style.display = 'none';
	}
  else {
    document.getElementById('Sizes' + n).style.display = 'block'; 
    document.getElementById('Sizes' + n).style.position = 'absolute';		
  }
};



/* ---------------------------------------------------------------------- *\
  Function    : viewSource()
  Description : Shows the HTML source code generated by the WYSIWYG editor
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function viewSource(n) {
  
  var getDocument = document.getElementById("wysiwyg" + n).contentWindow.document;
  var browserName = navigator.appName;
	
	// View Source for IE 	 
  if (browserName == "Microsoft Internet Explorer") {
    var iHTML = getDocument.body.innerHTML;
    getDocument.body.innerText = iHTML;
	}
 
  // View Source for Mozilla/Netscape
  else {
    var html = document.createTextNode(getDocument.body.innerHTML);
    getDocument.body.innerHTML = "";
    getDocument.body.appendChild(html);
	}
  
	// Hide the HTML Mode button and show the Text Mode button
  document.getElementById('HTMLMode' + n).style.display = 'none'; 
	document.getElementById('textMode' + n).style.display = 'block'; 
	
	// set the font values for displaying HTML source
	getDocument.body.style.fontSize = "12px";
	getDocument.body.style.fontFamily = "Courier New"; 
	
  viewTextMode = 1;
  
  // tell ripe that we are in htmlmode
	document.getElementById('hidden_mode').value = 1;
};



/* ---------------------------------------------------------------------- *\
  Function    : viewText()
  Description : Shows the rich text of the WYSIWYG editor
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function viewText(n) { 
  var getDocument = document.getElementById("wysiwyg" + n).contentWindow.document;
  var browserName = navigator.appName;
	
	// View Text for IE 	  	 
  if (browserName == "Microsoft Internet Explorer") {
    var iText = getDocument.body.innerText;
    getDocument.body.innerHTML = iText;
	}
  
	// View Text for Mozilla/Netscape
  else {
    var html = getDocument.body.ownerDocument.createRange();
    html.selectNodeContents(getDocument.body);
    getDocument.body.innerHTML = html.toString();
	}
  
	// Hide the Text Mode button and show the HTML Mode button
  document.getElementById('textMode' + n).style.display = 'none'; 
	document.getElementById('HTMLMode' + n).style.display = 'block';
	
	// reset the font values
  getDocument.body.style.fontSize = "";
	getDocument.body.style.fontFamily = ""; 
	viewTextMode = 0;
	
	// tell ripe that we are in textmode
	document.getElementById('hidden_mode').value = 0;
};



/* ---------------------------------------------------------------------- *\
  Function    : doAdvanced()
  Description : Switches from basic to advanced
  Usage       : doAdvanced(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function goAdvanced(n) {
	// Show the toolbar3
	document.getElementById('toolbar3' + n).style.display = 'block'; 
  document.getElementById('GoAdvanced' + n).style.display = 'none';
  document.getElementById('GoBasic' + n).style.display = 'block';
	
};

/* ---------------------------------------------------------------------- *\
  Function    : goBasic()
  Description : Switches from advanced to basic
  Usage       : goBasic(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function goBasic(n) {
	// Hide toolbar3
	document.getElementById('toolbar3' + n).style.display = 'none';
  document.getElementById('GoBasic' + n).style.display = 'none';
  document.getElementById('GoAdvanced' + n).style.display = 'block';
	
};


/* ---------------------------------------------------------------------- *\
  Function    : updateTextArea()
  Description : Updates the text area value with the HTML source of the WYSIWYG
  Usage       : updateTextArea(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function updateTextArea(n) {
  document.getElementById(n).value = document.getElementById("wysiwyg" + n).contentWindow.document.body.innerHTML;
};



/* ---------------------------------------------------------------------- *\
  Function    : word_clean_html()
  Description : Cleans up the html after word pasting
  Usage       : word_clean_html(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function wordclean(n) {
  d = document.getElementById("wysiwyg" + n).contentWindow.document.body.innerHTML;
  finalout = cleanHTML(d);
  document.getElementById("wysiwyg" + n).contentWindow.document.body.innerHTML = finalout;
};


	

	

/**
	 * Returns the node structure of the current selection as array
	 * 
	 * @param {String} n The editor identifier (the textarea's ID)
	 */
	function getNodeTree(n) {
		
		var sel = this.getSelection(n);
		var range = this.getRange(sel);	
	
			
		// get element of range
		var tag = this.getTag(range);
		if(tag == null) { 
      return; 
    }
		// get parent of element
		
		var node = this.getParent(tag);
		// init the tree as array with the current selected element
		var nodeTree = new Array(tag);
		// get all parent nodes
		var ii = 1;

    
		
		
		while(node != null && node.nodeName != "#document") {
			nodeTree[ii] = node;
			node = this.getParent(node);			
			ii++;
		}
		
		
		return nodeTree;
	};
	
	/**
	 * Removes the current node of the selection
	 *
	 * @param {String} n The editor identifier (the textarea's ID)
	 */
	function removeNode(n) {
		// get selection and range
		var sel = this.getSelection(n);
		var range = this.getRange(sel);
		// the current tag of range
		var tag = this.getTag(range);
		var parent = tag.parentNode;
		if(tag == null || parent == null) { return; }
		if(tag.nodeName == "HTML" || tag.nodeName == "BODY") { return; }

		// copy child elements of the node to the parent element before remove the node
		var childNodes = new Array();
		for(var i=0; i < tag.childNodes.length;i++)
			childNodes[i] = tag.childNodes[i];	
		for(var i=0; i < childNodes.length;i++)
			parent.insertBefore(childNodes[i], tag);	
		
		// remove node
		parent.removeChild(tag);
		// validate if parent is a link and the node is only 
		// surrounded by the link, then remove the link too
		if(parent.nodeName == "A" && !parent.hasChildNodes()) {
			if(parent.parentNode) { parent.parentNode.removeChild(parent); }
		}
		// update the status bar
		this.updateStatusBar(n);
	};
	


	/**
	 * Get the selection of the given editor
	 * 
	 * @param {String} n The editor identifier (the textarea's ID)
	 */
	function getSelection(n) {
		var ifrm = this.getEditorWindow(n);
		var doc = ifrm.document;
		var sel = null;
		if(ifrm.getSelection){
			sel = ifrm.getSelection();
		}
		else if (doc.getSelection) {
			sel = doc.getSelection();
		}
		else if (doc.selection) {
			sel = doc.selection;
		}
		return sel;
	};
	
	/**
	 * Updates the status bar with the current node tree
	 *
	 * @param {String} n The editor identifier (the textarea's ID)
	 */
	function updateStatusBar(n) {
		// get the node structure
		var nodeTree = this.getNodeTree(n);
		if(nodeTree == null) { return; }
		
		
		// format the output
		var outputTree = "";
		var max = nodeTree.length - 1;
		var formatNodes = new Array();
		for(var i=max;i>=0;i--) {
			if(nodeTree[i].nodeName != "HTML" && nodeTree[i].nodeName != "BODY") {
				// could add links here to go to that tag
        outputTree += nodeTree[i].nodeName;	
			  formatNodes[i] = nodeTree[i].nodeName;
      }
			else {
				outputTree += nodeTree[i].nodeName;
			}
			if(i > 0) { outputTree += " > "; }
		}
		
		
			
		// update the status bar 	
		var statusbar = document.getElementById("wysiwyg_statusbar_" + n);
		if(statusbar){ 
			statusbar.innerHTML = outputTree; 
		}
		
		// update toolbar on/off states
		buttonOnOff(formatNodes,1,n);
		
	};



/**
	 * Get the iframe object of the WYSIWYG editor
	 * 
	 * @param {String} n Editor identifier 
	 * @return {HtmlIframeElement} Iframe object
	 */
	function getEditor(n) {
		return document.getElementById("wysiwyg" + n);
	};
	
/**
	 * Get editors window element
	 *
	 * @param {String} n Editor identifier 
	 * @return {HtmlWindowElement} Html window object
	 */
	function getEditorWindow(n) {
		return this.getEditor(n).contentWindow;
	};


/**
	 * Get the range of the given selection
	 *
	 * @param {Selection} sel Selection object
	 * @return {Range} Range object
	 */
	function getRange(sel) {
		return sel.createRange ? sel.createRange() : sel.getRangeAt(0);
	};
	
	
/**
	 * Get the acutally tag of the given range
	 *
	 * @param {Range} range Current range
	 */
	function getTag(range) {
		try {
		    var browserName = navigator.appName;
		    if (browserName != "Microsoft Internet Explorer") {
				var node = range.startContainer;	
				var pos = range.startOffset;
				if(node.nodeType != 3) { node = node.childNodes[pos]; }
				
				if(node.nodeName && node.nodeName.search(/#/) != -1) {
					return node.parentNode;
				}
				return node;
			}else{
				if(range.length > 0) {
					return range.item(0);
				}
				else if(range.parentElement()) {
					return range.parentElement();
				}
			}
			return null;
		}
		catch(e) {
			return null;
		}
	};
	
	/**
	 * Get the parent node of the given node
	 * 
	 * @param {DOMElement} element - Element which parent will be returned
	 */
	function getParent(element) {
		if(element.parentNode) {
			return element.parentNode;
		}
		return null;
	};
	

	/**
	 * catchKeyUp
	 * 
	 * Used for updating statusbar after a textformat,
	 * For cleaning code after a paste	 
	 */
	function catchKeyUp(n) {
			updateStatusBar(n);
	};
	
	
