window.attachEvent("onload", dmxedit_init);

function checkBrowser() {
	var version = parseFloat(navigator.appVersion.split('MSIE')[1]);
	if (navigator.userAgent.indexOf('Mac') != -1) version = 0;
	if (navigator.userAgent.indexOf('Windows CE') != -1) version = 0;
	if (navigator.userAgent.indexOf('Opera') != -1) version = 0;
	if (version >= 5.5) return true;
	return false;
}

function dmxedit_init(url) {
	if (checkBrowser) {
		var el_arr = document.getElementsByTagName('textarea');
		for (var i=0; i<el_arr.length; i++) {
			var config = new Object();
			var el = el_arr[i];
			if (el.type == 'textarea' && el.getAttribute('dmxedit') == 'true') {
				if (el.getAttribute('config') != null || el.getAttribute('toolbar') != null) {
					var cfg = config[el.name] = new Object();
					if (el.getAttribute('config') != null) {
						cfg_arr = el.getAttribute('config').split(';');
						for (var c=0; c<cfg_arr.length; c++) {
							cfg_arr2 = cfg_arr[c].split(':');
							cfg[cfg_arr2[0]] = cfg_arr2[1];
						}
					}
					if (el.getAttribute('toolbar') != null) {
						cfg['toolbar'] = new Array();
						cfg_arr = el.getAttribute('toolbar').split(';');
						for (var c=0; c<cfg_arr.length; c++) {
							cfg_arr2 = cfg_arr[c].split(':');
							switch(cfg_arr2[0]) {
								case 'F': // Fonts
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'NS';
									}
									if (cfg_arr2[1].indexOf('N')>-1) {
										cfg['toolbar'].push(['fontname']);
									}
									if (cfg_arr2[1].indexOf('S')>-1) {
										cfg['toolbar'].push(['fontsize']);
									}
									break;
								case 'S': // Styles
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'S';
									}
									if (cfg_arr2[1].indexOf('S')>-1) {
										cfg['toolbar'].push(['fontstyle']);
									}
									break;
								case 'H': // Headings
									if (cfg_arr2[1].indexOf('H')>-1) {
										cfg['toolbar'].push(['formatblock']);
									}
									break;
								case 'T': // FontType
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'BIU';
									}
									if (cfg_arr2[1].indexOf('B')>-1) {
										cfg['toolbar'].push(['bold']);
									}
									if (cfg_arr2[1].indexOf('I')>-1) {
										cfg['toolbar'].push(['italic']);
									}
									if (cfg_arr2[1].indexOf('U')>-1) {
										cfg['toolbar'].push(['underline']);
									}
									cfg['toolbar'].push(['separator']);
									break;
								case 'E': // Extra FontType
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'SBU';
									}
									if (cfg_arr2[1].indexOf('S')>-1) {
										cfg['toolbar'].push(['strikethrough']);
									}
									if (cfg_arr2[1].indexOf('B')>-1) {
										cfg['toolbar'].push(['subscript']);
									}
									if (cfg_arr2[1].indexOf('U')>-1) {
										cfg['toolbar'].push(['superscript']);
									}
									cfg['toolbar'].push(['separator']);
									break;
								case 'J': // Justification
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'LCRF';
									}
									if (cfg_arr2[1].indexOf('L')>-1) {
										cfg['toolbar'].push(['justifyleft']);
									}
									if (cfg_arr2[1].indexOf('C')>-1) {
										cfg['toolbar'].push(['justifycenter']);
									}
									if (cfg_arr2[1].indexOf('R')>-1) {
										cfg['toolbar'].push(['justifyright']);
									}
									if (cfg_arr2[1].indexOf('F')>-1) {
										cfg['toolbar'].push(['justifyfull']);
									}
									cfg['toolbar'].push(['separator']);
									break;
								case 'O': // Ordering
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'LUOI';
									}
									if (cfg_arr2[1].indexOf('L')>-1) {
										cfg['toolbar'].push(['OrderedList']);
									}
									if (cfg_arr2[1].indexOf('U')>-1) {
										cfg['toolbar'].push(['UnOrderedList']);
									}
									if (cfg_arr2[1].indexOf('O')>-1) {
										cfg['toolbar'].push(['Outdent']);
									}
									if (cfg_arr2[1].indexOf('I')>-1) {
										cfg['toolbar'].push(['Indent']);
									}
									cfg['toolbar'].push(['separator']);
									break;
								case 'C': // Colors
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'FB';
									}
									if (cfg_arr2[1].indexOf('F')>-1) {
										cfg['toolbar'].push(['forecolor']);
									}
									if (cfg_arr2[1].indexOf('B')>-1) {
										cfg['toolbar'].push(['backcolor']);
									}
									cfg['toolbar'].push(['separator']);
									break;
								case 'X': // Other Objects
									if (cfg_arr2[1] == null) {
										cfg_arr2[1] = 'SXHLITCFWM';
									}
									if (cfg_arr2[1].indexOf('S')>-1) {
										cfg['toolbar'].push(['Find']);
									}
									if (cfg_arr2[1].indexOf('X')>-1) {
										cfg['toolbar'].push(['Find']);
									}
									if (cfg_arr2[1].indexOf('H')>-1) {
										cfg['toolbar'].push(['HorizontalRule']);
									}
									if (cfg_arr2[1].indexOf('L')>-1) {
										cfg['toolbar'].push(['Createlink']);
									}
									if (cfg_arr2[1].indexOf('I')>-1) {
										cfg['toolbar'].push(['InsertImage']);
									}
									if (cfg_arr2[1].indexOf('T')>-1) {
										cfg['toolbar'].push(['InsertTable']);
									}
									if (cfg_arr2[1].indexOf('C')>-1) {
										cfg['toolbar'].push(['ClearFormat']);
									}
									if (cfg_arr2[1].indexOf('F')>-1) {
										cfg['toolbar'].push(['ClearFonts']);
									}
									if (cfg_arr2[1].indexOf('W')>-1) {
										cfg['toolbar'].push(['ClearWord']);
									}
									if (cfg_arr2[1].indexOf('M')>-1) {
										cfg['toolbar'].push(['htmlmode']);
									}
							}
						}
					}
					dmxedit_create(el.name, cfg);
				} else {
					dmxedit_create(el.name);
				}
			}
		}
	}
}

function dmxedit_create(objname, userConfig) {
	var config = new dmxedit_config(objname);
	var obj = document.all[objname];
	if (userConfig) { 
		for (var thisName in userConfig) {
			if (userConfig[thisName]) config[thisName] = userConfig[thisName];
		}
	}
	obj.config = config;
	obj.style.display = 'none';

	if (!config.width || config.width == 'auto') {
		if (obj.style.width) config.width = obj.style.width;
		else config.width = '100%';
	}
	if (!config.height || config.height == 'auto') {
		if (obj.style.height) config.height = obj.style.height;
		else config.height = '200';
	}

	if (config.plaintextInput) {
		var contents = obj.value;
		contents = contents.replace(/\r\n/g, '<br />');
		contents = contents.replace(/\n/g, '<br />');
		contents = contents.replace(/\r/g, '<br />');
		obj.value = contents;
	}

	var editor = '<span id="_editor_toolbar"><table class="dmx_menuBar" border="0" cellspacing="0" cellpadding="0" style="padding: 1 0 0 2" width="' + config.width + '" unselectable="on"><tr><td>\n' + dmxedit_toolbar(objname) + '</td></tr></table></span>\n';
	editor += '<iframe id="_' + objname + '_editor" style="width:' + config.width + '; height:' + config.height + ';"></iframe>';
	obj.insertAdjacentHTML('afterEnd', editor);

	if (config.language == 'auto') {
		locale.setLocale(navigator.userLanguage);
	} else {
		locale.setLocale(config.language);
	}

	dmxedit_setmode(objname, 'init');

	// call filterOutput when user submits form
	for (var idx=0; idx < document.forms.length; idx++) {
		var r = document.forms[idx].attachEvent('onsubmit', function() { dmxedit_filterOutput(objname); });
		if (!r) alert('Error attaching event to form!');
	}

	return true;
}

function dmxedit_toolbar(objname) {
	var config = document.all[objname].config;
	var tblOpen  = '<table border="0" cellspacing="0" cellpadding="0" style="float: left;" unselectable="on"><tr><td style="border: none; padding: 1 0 0 0"><nobr>';
	var tblClose = '</nobr></td></tr></table>\n';
	var toolbar = '';
	var btnGroup, btnItem;
	for (var btnGroup in config.toolbar) {
		toolbar += tblOpen;
		for (var btnItem in config.toolbar[btnGroup]) {
			var btnName = config.toolbar[btnGroup][btnItem].toLowerCase();

			switch (btnName) {
				case 'fontname':
					toolbar += '<select id="_' + objname + '_FontName" onChange="dmxedit_action(this.id)" unselectable="on" style="width:100px; margin: 1 2 0 2; font-size: 12px;">';
					for (var fontname in config.fontnames) {
						toolbar += '<option value="' + config.fontnames[fontname] + '">' + fontname + '</option>'
					}
					toolbar += '</select>';
					break;
				case 'fontsize':
					toolbar += '<select id="_' + objname + '_FontSize" onChange="dmxedit_action(this.id)" unselectable="on" style="width:65px; margin: 1 2 0 0; font-size: 12px;">';
					for (var fontsize in config.fontsizes) {
						toolbar += '<option value="' + config.fontsizes[fontsize] + '">' + fontsize + '</option>'
					}
					toolbar += '</select>\n';
					break;
				case 'fontstyle':
					toolbar += '<select id="_' + objname + '_FontStyle" onChange="dmxedit_action(this.id)" unselectable="on" style="width:100px; margin: 1 2 0 0; font-size: 12px;">';
					toolbar += '<option value="">None</option>';
					for (var i in config.fontstyles) {
						var fontstyle = config.fontstyles[i];
						toolbar += '<option value="' + fontstyle.className + '">' + fontstyle.name + '</option>'
					}
					toolbar += '</select>';
					break;
				case 'formatblock':
					toolbar += '<select id="_' + objname + '_FormatBlock" onChange="dmxedit_action(this.id)" unselectable="on" style="width:100px; margin: 1 2 0 0; font-size: 12px;">';
					for (var formatblock in config.formatblocks) {
						toolbar += '<option value="' + config.formatblocks[formatblock] + '">' + formatblock + '</option>';
					}
					toolbar += '</select>';
					break;
				case 'separator':
					toolbar += '<span style="border: 1px inset; width: 1px; font-size: 16px; height: 16px; margin: 0 3 0 3"></span>';
					break;
				default:
					var btnObj = config.btnList[btnName];
					if (!btnObj) { alert('DMXedit error: button ' + btnName + ' not found in button list when creating the visual editor for ' + objname + '.\nPlease make sure you entered the button name correctly.'); return; }
					var btnCmdID   = btnObj[0];
					var btnTitle = btnObj[1];
					var btnOnClick = btnObj[2];
					var btnImage = btnObj[3];
					toolbar += '<button title="' + btnTitle + '" id="_' + objname + '_' + btnCmdID + '" class="dmx_btn" onClick="' + btnOnClick + '" onmouseover="if(this.className==\'dmx_btn\'){this.className=\'dmx_btnOver\'}" onmouseout="if(this.className==\'dmx_btnOver\'){this.className=\'dmx_btn\'}" unselectable="on"><img src="' + config.imgURL + btnImage + '" border=0 unselectable="on"></button>';
			}
		}
		toolbar += tblClose;
	}
	return toolbar;
}

function dmxedit_config(objname) {
	this.version = "1.02";
	
	this.width = "auto";
	this.height = "auto";
	this.bodyStyle = 'background-color: #FFFFFF; font-family: "Verdana"; font-size: x-small';
	this.imgURL = BaseURL+'AdvHTML_Images/';
	
	this.replaceNextlines = 0;
	this.plaintextInput = 0;
	
	this.language = "auto";
	
	this.upload = "";
	this.resize = "";
	this.mw = 0;
	this.mh = 0;
	
	this.toolbar = [
		['fontname'],
		['fontsize'],
		['fontstyle'],
		['formatblock'],
		['bold','italic','underline','separator'],
		['strikethrough','subscript','superscript','separator'],
		['justifyleft','justifycenter','justifyright','justifyfull','separator'],
		['OrderedList','UnOrderedList','Outdent','Indent','separator'],
		['forecolor','backcolor','separator'],
		['Find','InsertChar','HorizontalRule','Createlink','InsertImage','InsertTable','clearformat','clearfonts','clearword','htmlmode','separator']
	];

	this.fontnames = {
		"Arial":           "arial, helvetica, sans-serif",
		"Courier New":     "courier new, courier, mono",
		"Georgia":         "Georgia, Times New Roman, Times, Serif",
		"Tahoma":          "Tahoma, Arial, Helvetica, sans-serif",
		"Times New Roman": "times new roman, times, serif",
		"Verdana":         "Verdana, Arial, Helvetica, sans-serif",
		"impact":          "impact",
		"WingDings":       "WingDings"
	};

	this.fontsizes = {
		"1 (8 pt)":  "1",
		"2 (10 pt)": "2",
		"3 (12 pt)": "3",
		"4 (14 pt)": "4",
		"5 (18 pt)": "5",
		"6 (24 pt)": "6",
		"7 (36 pt)": "7"
	};

	this.stylesheet = new Array(BaseURL+"ScriptLibrary/AdvHTMLEdit.css");
	
	this.fontstyles = [];
	this.globalstyles = [];
	var rules;
	for (var i=0; i<document.styleSheets.length; i++) {
		for (var j=0; j<document.styleSheets(i).rules.length; j++) {
			rules = document.styleSheets(i).rules(j);
			if (rules.selectorText.substring(1,5) != "dmx_" && rules.selectorText.substring(0,1) == ".") {
				this.fontstyles.push({name:rules.selectorText.substring(1),className:rules.selectorText.substring(1),classStyle:rules.style['cssText']});
			}
			if (rules.selectorText.substring(1,5) != "dmx_" && rules.selectorText.substring(0,1) != ".") {
				this.globalstyles.push({name:rules.selectorText,className:rules.selectorText,classStyle:rules.style['cssText']});
			}
		}
	}
	
	this.formatblocks = {
		"@{Normal}": "<p>",
		"@{Heading1}": "<h1>",
		"@{Heading2}": "<h2>",
		"@{Heading3}": "<h3>",
		"@{Heading4}": "<h4>",
		"@{Heading5}": "<h5>",
		"@{Heading6}": "<h6>",
		"@{Address}": "<address>",
		"@{Formatted}": "<pre>"
	};

	this.btnList = {
		// buttonName:    commandID,               title,                   onclick,                    image,             
		"bold":           ['Bold',                 '@{Bold}',               'dmxedit_action(this.id)',  'TB.gif'],
		"italic":         ['Italic',               '@{Italic}',             'dmxedit_action(this.id)',  'TI.gif'],
		"underline":      ['Underline',            '@{Underline}',          'dmxedit_action(this.id)',  'TU.gif'],
		"strikethrough":  ['StrikeThrough',        '@{StrikeThrough}',      'dmxedit_action(this.id)',  'ES.gif'],
		"subscript":      ['SubScript',            '@{SubScript}',          'dmxedit_action(this.id)',  'EB.gif'],
		"superscript":    ['SuperScript',          '@{SuperScript}',        'dmxedit_action(this.id)',  'EU.gif'],
		"justifyleft":    ['JustifyLeft',          '@{JustifyLeft}',        'dmxedit_action(this.id)',  'JL.gif'],
		"justifycenter":  ['JustifyCenter',        '@{JustifyCenter}',      'dmxedit_action(this.id)',  'JC.gif'],
		"justifyright":   ['JustifyRight',         '@{JustifyRight}',       'dmxedit_action(this.id)',  'JR.gif'],
		"justifyfull":    ['JustifyFull',          '@{JustifyFull}',        'dmxedit_action(this.id)',  'JF.gif'],
		"orderedlist":    ['InsertOrderedList',    '@{OrderedList}',        'dmxedit_action(this.id)',  'OL.gif'],
		"unorderedlist":  ['InsertUnorderedList',  '@{UnorderedList}',      'dmxedit_action(this.id)',  'OU.gif'],
		"outdent":        ['Outdent',              '@{Outdent}',            'dmxedit_action(this.id)',  'OO.gif'],
		"indent":         ['Indent',               '@{Indent}',             'dmxedit_action(this.id)',  'OI.gif'],
		"forecolor":      ['ForeColor',            '@{ForeColor}',          'dmxedit_action(this.id)',  'CF.gif'],
		"backcolor":      ['BackColor',            '@{BackColor}',          'dmxedit_action(this.id)',  'CB.gif'],
		"find":           ['Find',                 '@{Find}',               'dmxedit_action(this.id)',  'XS.gif'],
		"insertchar":     ['InsertChar',           '@{InsertChar}',         'dmxedit_action(this.id)',  'XX.gif'],
		"horizontalrule": ['InsertHorizontalRule', '@{HorizontalRule}',     'dmxedit_action(this.id)',  'XH.gif'],
		"createlink":     ['CreateLink',           '@{Link}',               'dmxedit_action(this.id)',  'XL.gif'],
		"insertimage":    ['InsertImage',          '@{Image}',              'dmxedit_action(this.id)',  'XI.gif'],
		"inserttable":    ['InsertTable',          '@{Table}',              'dmxedit_action(this.id)',  'XT.gif'],
		"clearformat":    ['ClearFormat',          '@{Clear}',              'dmxedit_action(this.id)',  'XC.gif'],
		"clearfonts":     ['ClearFonts',           '@{ClearFont}',          'dmxedit_action(this.id)',  'XF.gif'],
		"clearword":      ['ClearWord',            '@{Word}',               'dmxedit_action(this.id)',  'XW.gif'],
		"htmlmode":       ['HtmlMode',             '@{HtmlMode}',           'dmxedit_setmode(\'' + objname + '\')', 'XM.gif']
	};
}

function dmxedit_action(button_id) {
	var BtnParts = Array();
	BtnParts = button_id.split('_');
	var objname = button_id.replace(/^_(.*)_[^_]*$/, '$1');
	var cmdID = BtnParts[BtnParts.length-1].toLowerCase();
	var button_obj = document.all[button_id];
	var editor_obj = document.all['_' + objname + '_editor'];
	var config = document.all[objname].config;

	if (config.mode == 'text') return;

	var editdoc = editor_obj.contentWindow.document;
	dmxedit_focus(editor_obj);

	// get index and value for pulldowns
	var idx = button_obj.selectedIndex;
	var val = (idx != null) ? button_obj[ idx ].value : null;

	switch (cmdID) {
		case 'fontname':
			if (val) {
				editdoc.execCommand(cmdID,0,val);
				break;
			}
		case 'fontsize':
			if (val) {
				editdoc.execCommand(cmdID,0,val);
				break;
			}
		case 'fontstyle':
			if (val == '') {
				editdoc.execCommand('RemoveFormat');
				break;
			}
			if (val) {
				editdoc.execCommand('RemoveFormat');
				editdoc.execCommand('FontName',0,'636c6173734e616d6520706c616365686f6c646572');
				var fontArray = editdoc.all.tags('FONT');
				for (i=0; i<fontArray.length; i++) {
					if (fontArray[i].face == '636c6173734e616d6520706c616365686f6c646572') {
						fontArray[i].face = '';
						fontArray[i].className = val;
						fontArray[i].outerHTML = fontArray[i].outerHTML.replace(/face=['"]+/, '');
					}
				}
				button_obj.selectedIndex =0;
				break;
			}
		case "formatblock":
			if (val) {
				editdoc.execCommand(cmdID, false, val);
				button_obj.selectedIndex =0;
				break;
			}
		case 'forecolor':
			var oldcolor = _dec_to_rgb(editdoc.queryCommandValue(cmdID));
			var newcolor = showModalDialog(BaseURL+'AdvHTML_Popups/select_color.html', oldcolor, 'resizable: no; help: no; status: no; scroll: no;');
			if (newcolor != null) editdoc.execCommand(cmdID, false, '#' + newcolor);
			break;
		case 'backcolor':
			var oldcolor = _dec_to_rgb(editdoc.queryCommandValue(cmdID));
			var newcolor = showModalDialog(BaseURL+'AdvHTML_Popups/select_color.html', oldcolor, 'resizable: no; help: no; status: no; scroll: no;');
			if (newcolor != null) editdoc.execCommand(cmdID, false, '#' + newcolor);
			break;
		case 'createlink':
			editdoc.execCommand(cmdID, 1);
			break;
		case 'insertimage':
			if (config.resize.length>0 && (config.mw>0 || config.mh>0)) {
				showModalDialog(BaseURL+'AdvHTML_Popups/insert_image.html?'+BaseURL+';'+config.upload.toLowerCase()+';'+config.mw+';'+config.mh, editdoc, 'resizable: no; help: no; status: no; scroll: no;');
			} else {
				showModalDialog(BaseURL+'AdvHTML_Popups/insert_image.html?'+BaseURL+';'+config.upload.toLowerCase(), editdoc, 'resizable: no; help: no; status: no; scroll: no;');
			}
			break;
		case 'inserttable':
			showModalDialog(BaseURL+'AdvHTML_Popups/insert_table.html?' + objname, window, 'resizable: yes; help: no; status: no; scroll: no;');
			break;
		case 'clearformat':
			clearFormat(objname);
			break;
		case 'clearfonts':
			clearFonts(objname);
			break;
		case 'clearword':
			clearWord(objname);
			break;
		case 'find':
			if (editdoc.body.createTextRange().htmlText != "") {
				// var TxtRange = editor_obj.contentWindow.document.body.createTextRange();
				showModalDialog(BaseURL+'AdvHTML_Popups/find.html?' + objname, window, 'resizable: no; help: no; status: no; scroll: no;');
			} else {
				alert('\nEditor is empty.\n\nNothing to find or replace.!');
			}
			break;
		case 'insertchar':
			var newchar = showModalDialog(BaseURL+'AdvHTML_Popups/insert_char.html', '', 'dialogWidth:630px; dialogHeight: 180px; resizable: no; help: no; status: no; scroll: no;');
			if (newchar == '') {
				return;
			} else {
				dmxedit_insertHTML(objname, newchar);
			}
			break;
		default:
			editdoc.execCommand(cmdID);
	}
	dmxedit_event(objname);
}

function dmxedit_event(objname, runDelay) {
	var config = document.all[objname].config;
	var editor_obj = document.all['_' + objname +  '_editor'];
	if (runDelay == null) runDelay = 0;
	var editdoc;
	var editEvent = editor_obj.contentWindow ? editor_obj.contentWindow.event : event;

	if (editEvent && editEvent.keyCode) {
		var ord = editEvent.keyCode;
		var ctrlKey = editEvent.ctrlKey;
		var altKey = editEvent.altKey;
		var shiftKey = editEvent.shiftKey;

		if (ord == 16) return; // ignore shift key by itself
		if (ord == 17) return; // ignore ctrl key by itself
		if (ord == 18) return; // ignore alt key by itself

		if (ctrlKey && (ord == 122 || ord == 90)) { // catch ctrl-z (UNDO)
			// TODO: Add our own undo/redo functionality
			return;
		}
		if ((ctrlKey && (ord == 121 || ord == 89)) || (ctrlKey && shiftKey && (ord == 122 || ord == 90))) { // catch ctrl-y, ctrl-shift-z (REDO)
			// TODO: Add our own undo/redo functionality
			return;
		}
	}
	// setup timer for delayed updates (some events take time to complete)
	if (runDelay > 0) return setTimeout(function(){ dmxedit_event(objname); }, runDelay);

	// don't execute more than 3 times a second (eg: too soon after last execution)
	if (this.tooSoon == 1 && runDelay >= 0) {
		this.queue = 1;
		return;
	}
	this.tooSoon = 1;
	setTimeout(function() {
		this.tooSoon = 0;
		if (this.queue) dmxedit_event(objname,-1);
		this.queue = 0;
	}, 333);

	dmxedit_updateOutput(objname);
	dmxedit_updateToolbar(objname);
}

function dmxedit_updateToolbar(objname, action) {
	var config = document.all[objname].config;
	var editor_obj  = document.all['_' + objname +  '_editor'];

	if (action == 'enable' || action == 'disable') {
		var tbItems = new Array('FontName','FontSize','FontStyle','FormatBlock');
		for (var btnName in config.btnList) tbItems.push(config.btnList[btnName][0]);

		for (var idxN in tbItems) {
			var cmdID = tbItems[idxN].toLowerCase();
			var tbObj = document.all['_' + objname + '_' + tbItems[idxN]];
			if (cmdID == 'htmlmode') continue;
			if (tbObj == null) continue;
			var isBtn = (tbObj.tagName.toLowerCase() == 'button') ? true : false;

			if (action == 'enable') { tbObj.disabled = false; if (isBtn) tbObj.className = 'dmx_btn'; }
			if (action == 'disable') { tbObj.disabled = true; if (isBtn) tbObj.className = 'dmx_btnNA'; }
		}
		return;
	}

	if (config.mode == 'text') return;
	var editdoc = editor_obj.contentWindow.document;

	var fontname_obj = document.all['_' + objname + '_FontName'];
	if (fontname_obj) {
		var fontname = editdoc.queryCommandValue('FontName');
		if (fontname == null) {
			fontname_obj.value = null;
		} else {
			var found = 0;
			for (i=0; i<fontname_obj.length; i++) {
				if (fontname.toLowerCase() == fontname_obj[i].text.toLowerCase()) {
					fontname_obj.selectedIndex = i;
					found = 1;
				}
			}
			if (found != 1) fontname_obj.value = null;
		}
	}

	var fontsize_obj = document.all['_' + objname + '_FontSize'];
	if (fontsize_obj) {
		var fontsize = editdoc.queryCommandValue('FontSize');
		if (fontsize == null) {
			fontsize_obj.value = null;
		} else {
			var found = 0;
			for (i=0; i<fontsize_obj.length; i++) {
				if (fontsize == fontsize_obj[i].value) {
					fontsize_obj.selectedIndex = i;
					found=1;
				}
			}
			if (found != 1) fontsize_obj.value = null;
		}
	}

	var formatblock_obj = document.all['_' + objname + '_FormatBlock'];
	if (formatblock_obj) {
		var curRange = editdoc.selection.createRange();

		var pElement;
		if (curRange.length) {
			pElement = curRange[0];
		} else {
			pElement = curRange.parentElement();
		}
		while (pElement) {
			var found = 0;			
			for (i=0; i<formatblock_obj.length; i++) {
				if (pElement.tagName == formatblock_obj[i].value.replace(/[<>]/g,"").toUpperCase()) {
					formatblock_obj.selectedIndex = i;
					found=1;
					break;
				}
			}
			if (found == 1) break; 
		  pElement = pElement.parentElement;
		}
		
	}

	var classname_obj = document.all['_' + objname + '_FontStyle'];
	if (classname_obj) {
		var curRange = editdoc.selection.createRange();
	
		var pElement;
		if (curRange.length) {
			pElement = curRange[0];
		} else {
			pElement = curRange.parentElement();
		}
		while (pElement && !pElement.className) pElement = pElement.parentElement;
	
		var thisClass = pElement ? pElement.className.toLowerCase() : '';
		if (!thisClass && classname_obj.value) {
			classname_obj.value = null;
		} else {
			var found = 0;
			for (i=0; i<classname_obj.length; i++) {
				if (thisClass == classname_obj[i].value.toLowerCase()) {
					classname_obj.selectedIndex = i;
					found=1;
				}
			}
			if (found != 1) classname_obj.value = null;
		}
	}

	var IDList = Array('Bold','Italic','Underline','StrikeThrough','SubScript','SuperScript','JustifyLeft','JustifyCenter','JustifyRight','JustifyFull','InsertOrderedList','InsertUnorderedList');
	for (i=0; i<IDList.length; i++) {
		var btnObj = document.all['_' + objname + '_' + IDList[i]];
		if (btnObj == null) continue;
		var cmdActive = editdoc.queryCommandState( IDList[i] );

		if (!cmdActive)  {
			if (btnObj.className != 'dmx_btn') btnObj.className = 'dmx_btn';
			if (btnObj.disabled != false) btnObj.disabled = false;
		} else if (cmdActive) {
			if (btnObj.className != 'dmx_btnDown') btnObj.className = 'dmx_btnDown';
			if (btnObj.disabled != false) btnObj.disabled = false;
		}
	}
}

function dmxedit_htmlToXhtml(contents) {
	// contents = contents.replace(/<.*>?>/g,function(m,p,s){return m.replace(/(\w+=)([#\w]+)/g,function(m,p,s){return p.toLowerCase() + '"' + s + '"';});});
	contents = contents.replace(/<.*>?>/g,function(m,p,s){return m.replace(/(\w+=)([#\w]+)/g,function(m,p,s){return p.toLowerCase() + '"' + s + '"';});});
	contents = contents.replace(/<(\/?\w+)([^>]*>)/g,function(m,p,s){return '<' + p.toLowerCase() + s;});
	contents = contents.replace(/<(meta|base|basefont|param|link|img|br|hr|area|input)([^>]*[^/]?)>/gi,'<$1$2 />');

	return contents;
}

function dmxedit_updateOutput(objname) {
	var config = document.all[objname].config;
	var editor_obj = document.all['_' + objname + '_editor'];
	var editEvent = editor_obj.contentWindow ? editor_obj.contentWindow.event : event;
	//var isTextarea = (config.mode == 'text');
	var editdoc = editor_obj.contentWindow.document;
	
	//allObjects[a].runtimeStyle.border = "1px dotted #0000FF"
	var edit_Tables = editdoc.body.getElementsByTagName("TABLE");
	for (i=0; i < edit_Tables.length; i++) {
		if (edit_Tables[i].border == '' || edit_Tables[i].border == '0' ) {
			edit_Tables[i].runtimeStyle.border = "1px dotted #C0C0C0";
		} else {
			edit_Tables[i].runtimeStyle.cssText = "";
		}
		edit_Rows = edit_Tables[i].rows;
		for (j=0; j < edit_Rows.length; j++) {
			edit_Cells = edit_Rows[j].cells;
			for (k=0; k < edit_Cells.length; k++) {
				if (edit_Tables[i].border == '' || edit_Tables[i].border == '0' ) {
					if (!edit_Cells[k].border || edit_Cells[k].border == '' || edit_Cells[k].border == '0' ) {
						edit_Cells[k].runtimeStyle.border = "1px dotted #C0C0C0";
					} else {
					  edit_Cells[k].runtimeStyle.cssText = "";
					}
				}	else {
					if ( edit_Cells[k].border == '0' ) {
						edit_Cells[k].runtimeStyle.border = "1px dotted #C0C0C0";
					}	else {
						edit_Cells[k].runtimeStyle.cssText = "";
					}
				}
			}
		}
	}
	
	var contents;
	//if (isTextarea) {
	//	contents = editor_obj.value;
	//} else {
		contents = editdoc.body.innerHTML;
	//}
	
	if (config.lastUpdateOutput && config.lastUpdateOutput == contents) {
		return;
	} else {
		config.lastUpdateOutput = cleanUpHtml(contents);
	}

	document.all[objname].value = cleanUpHtml(contents);
}

function dmxedit_filterOutput(objname) {
	var config   = document.all[objname].config;

	if (config.mode == 'text') {
		dmxedit_setmode(objname, 'html');
	}
	dmxedit_updateOutput(objname);

	var contents = document.all[objname].value;

	if (contents.toLowerCase() == '<p>&nbsp;</p>') contents = '';

	var filterTag = function(tagBody, tagName, tagAttr) {
		tagName = tagName.toLowerCase();
		var closingTag = (tagBody.match(/^<\//)) ? true : false;

		// fix placeholder URLS - remove absolute paths that IE adds
		if (tagName == 'img') tagBody = tagBody.replace(/(src\s*=\s*.)[^*]*(\*\*\*)/, "$1$2");
		if (tagName == 'a') tagBody = tagBody.replace(/(href\s*=\s*.)[^*]*(\*\*\*)/, "$1$2");

		return tagBody;
	};

	RegExp.lastIndex = 0;
	var matchTag = /<\/?(\w+)((?:[^'">]*|'[^']*'|"[^"]*")*)>/g;

	contents = contents.replace(matchTag, filterTag);

	// remove nextlines from output (if requested)
	if (config.replaceNextlines) { 
		contents = contents.replace(/\r\n/g, ' ');
		contents = contents.replace(/\n/g, ' ');
		contents = contents.replace(/\r/g, ' ');
	}

	// update output with filtered content
	document.all[objname].value = contents;
}

function dmxedit_setmode(objname, mode) {
	var config = document.all[objname].config;
	var editor_obj = document.all['_' + objname + '_editor'];
	var editdoc = editor_obj.contentWindow.document;

	if (document.readyState != 'complete') {
		setTimeout(function() { dmxedit_setmode(objname, mode) }, 25);
		return;
	}

	if (mode == 'textedit' || config.mode == 'html') {
		config.mode = 'text';

		editdoc.body.innerText = cleanUpHtml(editdoc.body.innerHTML);
		editdoc.body.style.fontFamily = 'Courier New';
		editdoc.body.style.fontSize = '10pt';
		editdoc.body.innerHTML = ccParser(editdoc.body.innerHTML);

		dmxedit_event(objname);

		dmxedit_updateToolbar(objname, 'disable');

		// set event handlers
		editor_obj.onkeydown   = function() { dmxedit_event(objname); }
		editor_obj.onkeypress  = function() { dmxedit_event(objname); }
		editor_obj.onkeyup     = function() { dmxedit_event(objname); }
		editor_obj.onmouseup   = function() { dmxedit_event(objname); }
		editor_obj.ondrop      = function() { dmxedit_event(objname, 100); }
		editor_obj.oncut       = function() { dmxedit_event(objname, 100); }
		editor_obj.onpaste     = function() { dmxedit_event(objname, 100); }
		editor_obj.onblur      = function() { dmxedit_event(objname, -1); }
		
		dmxedit_updateOutput(objname);
		dmxedit_focus(editor_obj);
	} else {
		config.mode = 'html';
		
		if (mode == 'init') {
			var html = '<html><head>\n';
			for (var i=0; i<config.stylesheet.length; i++) {
				html += '<link href="' + config.stylesheet[i] + '" rel="stylesheet" type="text/css">\n';
			}
			html += '<style>\nbody {' + config.bodyStyle + '} \n';
			for (var i in config.fontstyles) {
				var fontstyle = config.fontstyles[i];
				if (fontstyle.classStyle) {
					html += '.' + fontstyle.className + ' {' + fontstyle.classStyle + '}\n';
				}
			}
			for (var i in config.globalstyles) {
				var globalstyle = config.globalstyles[i];
				if (globalstyle.classStyle) {
					html += globalstyle.className + ' {' + globalstyle.classStyle + '}\n';
				}
			}
			html += '</style>\n</head>\n<body contenteditable="true" topmargin="1" leftmargin="1">' + document.all[objname].value + '</body>\n</html>\n';
			editdoc.open();
			editdoc.write(html);
			editdoc.close();
		} else {
   		  editdoc.body.innerHTML = editdoc.body.innerText;
		}
   		editdoc.body.style.fontFamily = '';
   		editdoc.body.style.fontSize = '';

		dmxedit_updateToolbar(objname, 'enable');

		editdoc.objname = objname;

		// set event handlers
		editdoc.onkeydown      = function() { dmxedit_event(objname); }
		editdoc.onkeypress     = function() { dmxedit_event(objname); }
		editdoc.onkeyup        = function() { dmxedit_event(objname); }
		editdoc.onmouseup      = function() { dmxedit_event(objname); }
		editdoc.body.ondrop    = function() { dmxedit_event(objname, 100); }
		editdoc.body.oncut     = function() { dmxedit_event(objname, 100); }
		editdoc.body.onpaste   = function() { dmxedit_event(objname, 100); }
		editdoc.body.onblur    = function() { dmxedit_event(objname, -1); }

		if (mode != 'init') {
			dmxedit_focus(editor_obj);
		}
	}

	if (mode != 'init') {
		dmxedit_event(objname);
	}
	
	if (mode == 'init') {
		dmxedit_updateOutput(objname);
	}
}

function dmxedit_focus(editor_obj) {
	var editdoc = editor_obj.contentWindow.document;
	var editorRange = editdoc.body.createTextRange();
	var curRange    = editdoc.selection.createRange();

	if (curRange.length == null && !editorRange.inRange(curRange)) {
		editorRange.collapse();
		editorRange.select();
		curRange = editorRange;
	}
}

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 dmxedit_insertHTML(objname, str1, str2, reqSel) {
	var config = document.all[objname].config;
	var editor_obj = document.all['_' + objname + '_editor'];
	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;
	}

	dmxedit_focus(editor_obj);

	var tagname = editor_obj.tagName.toLowerCase();
	var sRange;

	if (config.mode == 'html') {
		var editdoc = editor_obj.contentWindow.document;
		sRange = editdoc.selection.createRange();
		var sHtml = sRange.htmlText;

		if (sRange.length) return alert("Unable to insert HTML.  Try highlighting content instead of selecting it.");

		var oldHandler = window.onerror;
		window.onerror = function() { alert("Unable to insert HTML for current selection."); return true; };
		if (sHtml.length) {
			if (str2) {
				sRange.pasteHTML(str1 +sHtml+ str2)
			} else {
				sRange.pasteHTML(str1);
			}
		} else {
			if (reqSel) return alert("Unable to insert HTML.  You must select something first.");
			sRange.pasteHTML(str1 + str2);
		}
		window.onerror = oldHandler;
	} else if (config.mode == 'text') {
		editor_obj.focus();
		sRange = document.selection.createRange();
		var sText = sRange.text;

		if (sText.length) {
			if (str2) {
				sRange.text = str1 + sText + str2;
			} else {
				sRange.text = str1;
			}
		} else {
			if (reqSel) return alert("Unable to insert HTML.  You must select something first.");
			sRange.text = str1 + str2;
		}
	} else {
		alert("Unable to insert HTML.  Unknown object tag type '" + tagname + "'.");
	}

	sRange.collapse(false);
	sRange.select();
}

function dmxedit_getHTML(objname) {
	var editor_obj = document.all['_' + objname + '_editor'];
	return editor_obj.contentWindow.document.body.innerHTML;
}

function dmxedit_setHTML(objname, html) {
	var editor_obj = document.all['_' + objname + '_editor'];
	editor_obj.contentWindow.document.body.innerHTML = html;
}

function dmxedit_appendHTML(objname, html) {
	var editor_obj = document.all['_' + objname + '_editor'];
	editor_obj.contentWindow.document.body.innerHTML += html;
}

/* ---------------------------------------------------------------- */

function _isMouseOver(obj,event) {       // determine if mouse is over object
  var mouseX    = event.clientX;
  var mouseY    = event.clientY;

  var objTop    = obj.offsetTop;
  var objBottom = obj.offsetTop + obj.offsetHeight;
  var objLeft   = obj.offsetLeft;
  var objRight  = obj.offsetLeft + obj.offsetWidth;

  if (mouseX >= objLeft && mouseX <= objRight &&
      mouseY >= objTop  && mouseY <= objBottom) { return true; }

  return false;
}

/* ---------------------------------------------------------------- */

function editor_cMenu_generate(editorWin,objname) {
  var parentWin = window;
  editorWin.event.returnValue = false;  // cancel default context menu

  // define content menu options
  var cMenuOptions = [ // menu name, shortcut displayed, javascript code
    ['Cut', 'Ctrl-X', function() {}],
    ['Copy', 'Ctrl-C', function() {}],
    ['Paste', 'Ctrl-C', function() {}],
    ['Delete', 'DEL', function() {}],
    ['---', null, null],
    ['Select All', 'Ctrl-A', function() {}],
    ['Clear All', '', function() {}],
    ['---', null, null],
    ['About this editor...', '', function() {
      alert("about this editor");
    }]];
    editor_cMenu.options = cMenuOptions; // save options

  // generate context menu
  var cMenuHeader = ''
    + '<div id="_'+objname+'_cMenu" onblur="editor_cMenu(this);" oncontextmenu="return false;" onselectstart="return false"'
    + '  style="position: absolute; visibility: hidden; cursor: default; width: 167px; background-color: threedface;'
    + '         border: solid 1px; border-color: threedlightshadow threeddarkshadow threeddarkshadow threedlightshadow;">'
    + '<table border=0 cellspacing=0 cellpadding=0 width="100%" style="width: 167px; background-color: threedface; border: solid 1px; border-color: threedhighlight threedshadow threedshadow threedhighlight;">'
    + ' <tr><td colspan=2 height=1></td></tr>';

  var cMenuList = '';

  var cMenuFooter = ''
    + ' <tr><td colspan=2 height=1></td></tr>'
    + '</table></div>';

  for (var menuIdx in editor_cMenu.options) {
    var menuName = editor_cMenu.options[menuIdx][0];
    var menuKey  = editor_cMenu.options[menuIdx][1];
    var menuCode = editor_cMenu.options[menuIdx][2];

    // separator
    if (menuName == "---" || menuName == "separator") {
      cMenuList += ' <tr><td colspan=2 class="cMenuDivOuter"><div class="cMenuDivInner"></div></td></tr>';
    }

    // menu option
    else {
      cMenuList += '<tr class="cMenu" onMouseOver="editor_cMenu(this)" onMouseOut="editor_cMenu(this)" onClick="editor_cMenu(this, \'' +menuIdx+ '\',\'' +objname+ '\')">';
      if (menuKey) { cMenuList += ' <td align=left class="cMenu">' +menuName+ '</td><td align=right class="cMenu">' +menuKey+ '</td>'; }
      else         { cMenuList += ' <td colspan=2 class="cMenu">' +menuName+ '</td>'; }
      cMenuList += '</tr>';
    }
  }

  var cMenuHTML = cMenuHeader + cMenuList + cMenuFooter;


  document.all['_'+objname+'_cMenu'].outerHTML = cMenuHTML;

  editor_cMenu_setPosition(parentWin, editorWin, objname);

  parentWin['_'+objname+'_cMenu'].style.visibility = 'visible';
  parentWin['_'+objname+'_cMenu'].focus();

}

/* ---------------------------------------------------------------- */

function editor_cMenu_setPosition(parentWin, editorWin, objname) {      // set object position that won't overlap window edge
  var event    = editorWin.event;
  var cMenuObj = parentWin['_'+objname+'_cMenu'];
  var mouseX   = event.clientX + parentWin.document.all['_'+objname+'_editor'].offsetLeft;
  var mouseY   = event.clientY + parentWin.document.all['_'+objname+'_editor'].offsetTop;
  var cMenuH   = cMenuObj.offsetHeight;
  var cMenuW   = cMenuObj.offsetWidth;
  var pageH    = document.body.clientHeight + document.body.scrollTop;
  var pageW    = document.body.clientWidth + document.body.scrollLeft;

  // set horzontal position
  if (mouseX + 5 + cMenuW > pageW) { var left = mouseX - cMenuW - 5; } // too far right
  else                            { var left = mouseX + 5; }

  // set vertical position
  if (mouseY + 5 + cMenuH > pageH) { var top = mouseY - cMenuH + 5; } // too far down
  else                            { var top = mouseY + 5; }

  cMenuObj.style.top = top;
  cMenuObj.style.left = left;

}

/* ---------------------------------------------------------------- */

function editor_cMenu(obj,menuIdx,objname) {
  var action = event.type;
  if      (action == "mouseover" && !obj.disabled && obj.tagName.toLowerCase() == 'tr') {
    obj.className = 'cMenuOver';
    for (var i=0; i < obj.cells.length; i++) { obj.cells[i].className = 'cMenuOver'; }
  }
  else if (action == "mouseout" && !obj.disabled && obj.tagName.toLowerCase() == 'tr')  {
    obj.className = 'cMenu';
    for (var i=0; i < obj.cells.length; i++) { obj.cells[i].className = 'cMenu'; }
  }
  else if (action == "click" && !obj.disabled) {
    document.all['_'+objname+'_cMenu'].style.visibility = "hidden";
    var menucode = editor_cMenu.options[menuIdx][2];
    menucode();
  }
  else if (action == "blur") {
    if (!_isMouseOver(obj,event)) { obj.style.visibility = 'hidden'; }
    else {
      if (obj.style.visibility != "hidden") { obj.focus(); }
    }
  }
  else { alert("editor_cMenu, unknown action: " + action); }
}

function cleanUpHtml(html) {
	
	// Remove Word crap
  html = html.replace(/<\?xml:.*?\/>/gi, "");
  html = html.replace(/<o:p>&nbsp;<\/o:p>/gi, "");
  html = html.replace(/<st1:.*?>/gi, ""); 
  html = html.replace(/<w:.*?>/gi, "");   
  
  // Remove all vetors - here are the image references as well  
  html = html.replace(/<v:[^>]*>/gi, "");     
  html = html.replace(/<\/v:[^>]*>/gi, "");     

  html = html.replace(/<o:[^>]*>/gi, "");     
  html = html.replace(/<\/o:[^>]*>/gi, "");     

  // Remove empty SPAN
  html = html.replace(/<span\s*>(.*?)<\/span>/gi, "$1");     
  
  // Remove empty DIV
  html = html.replace(/<div\s*>(.*?)<\/div>/gi, "$1");     
  
  // Remove LOCK tag
  html = html.replace(/<lock[^>]*>(.*?)<\/lock>/gi, "$1");       
  
  // Remove empty tags
  html = html.replace(/<(\w)+([^>]*)>\s*<\/\1>/gi, "");  
  
  // Remove empty fonts
  html = html.replace(/<font[^>]*>\s*(\s*?|&nbsp;)\s*<\/font>/gi, "");     

  // Join adjacent fonts
  html = html.replace(/<font([^>]*)><font([^>]*)>(.*?)<\/font><\/font>/gi, "<font$1$2>$3</font>");     

  // Take only inner Hx tags
	var reH = /<h([^>]*)>\s*<h([^>]*)>(.*?)<\/h\2>\s*<\/h\1>/gi;
	while(reH.test(html)) {
		html = html.replace(reH,"<H$2>$3</H$2>");
  	while(reH.test(html)) {
	  	html = html.replace(reH,"<H$2>$3</H$2>");
  	}    
	}
  
  // Remove empty P 
	var re = /<p[^>]*>\s*<\/p>/gi;
	while(re.test(html)) {
		html = html.replace(re,"");
  	while(re.test(html)) {
	  	html = html.replace(re,"");
  	}    
	}
  
  // Remove empty Hx
	var re = /<(h\d)[^>]*>\s*<\/\1>/gi;
	while(re.test(html)) {
		html = html.replace(re,"");
  	while(re.test(html)) {
	  	html = html.replace(re,"");
  	}    
	}
  
  
  html = replaceCharacters(html);
  html = dmxedit_htmlToXhtml(html);
  
  return html;
}

function clearFormat(objname) {
	var editor_obj = document.all['_' + objname + '_editor'];
	var editdoc = editor_obj.contentWindow.document;
	var edit = editdoc.selection.createRange();
  var selHTML = edit.htmlText.replace(/(\r|\n)/g,"");  
  var newHTML = selHTML;
  var theContent = editdoc.body;
  var fullHTML = theContent.innerHTML;
  var begHTML = fullHTML.indexOf(selHTML);
  var endHTML = begHTML + selHTML.length;

  if (begHTML != -1) {
    //Clear Formating in the selected html
    // Remove LOCK tag
    newHTML = newHTML.replace(/<(font|span|div|h\d)[^>]*>/gi, "");     
    newHTML = newHTML.replace(/<\/(font|span|div|h\d)>/gi, "");     
  
    newHTML = newHTML.replace(/<([^>]*)class=(\w+)([^>]*)>/gi, "<$1$3>");       
    
   	theContent.innerHTML = fullHTML.substring(0,begHTML) + newHTML + fullHTML.substring(endHTML,fullHTML.length);
  }  
}

function clearFonts(objname) {
	var editor_obj = document.all['_' + objname + '_editor'];
	var editdoc = editor_obj.contentWindow.document;
  var theContent = editdoc.body;
  var sHTML = theContent.innerHTML;

  sHTML = sHTML.replace(/<font[^>]*>/gi, "");     
  sHTML = sHTML.replace(/<\/font>/gi, "");     

 	theContent.innerHTML = sHTML;

}


function clearWord(objname) {
	var editor_obj = document.all['_' + objname + '_editor'];
	var editdoc = editor_obj.contentWindow.document;
  var theContent = editdoc.body;
  for (var i = 0; i < theContent.all.length; i++) {
		theContent.all[i].removeAttribute("className","",0);
		theContent.all[i].removeAttribute("style","",0);
		theContent.all[i].removeAttribute("lang","",0);    
	}
  var sHTML = theContent.innerHTML;

  sHTML = cleanUpHtml(sHTML);

 	theContent.innerHTML = sHTML;
}

function replaceCharacters(html) {
	// First check if chinese
	var dbcsTest="‚ ";
 
	if ((dbcsTest.length)!=1){
		// Special characters and their HTML equivelent
		var set = [
		["€","‘","’","’","“","”","–","—","¡","¢","£","£","¤","¥","¦","§","¨","©","ª","«","¬","­","®","¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ü","ý","þ","ÿ"],
		["&euro;","&lsquo;","&rsquo;","&rsquo;","&ldquo;","&rdquo;","&ndash;","&mdash;","&iexcl;","&cent;","&pound;","&pound;","&curren;","&yen;","&brvbar;","&sect;","&uml;","&copy;","&ordf;","&laquo;","&not;","­","&reg;","&macr;","&deg;","&plusmn;","&sup2;","&sup3;","&acute;","&micro;","&para;","&middot;","&cedil;","&sup1;","&ordm;","&raquo;","&frac14;","&frac12;","&frac34;","&iquest;","&Agrave;","&Aacute;","&Acirc;","&Atilde;","&Auml;","&Aring;","&AElig;","&Ccedil;","&Egrave;","&Eacute;","&Ecirc;","&Euml;","&Igrave;","&Iacute;","&Icirc;","&Iuml;","&ETH;","&Ntilde;","&Ograve;","&Oacute;","&Ocirc;","&Otilde;","&Ouml;","&times;","&Oslash;","&Ugrave;","&Uacute;","&Ucirc;","&Uuml;","&Yacute;","&THORN;","&szlig;","&agrave;","&aacute;","&acirc;","&atilde;","&auml;","&aring;","&aelig;","&ccedil;","&egrave;","&eacute;","&ecirc;","&euml;","&igrave;","&iacute;","&icirc;","&iuml;","&eth;","&ntilde;","&ograve;","&oacute;","&ocirc;","&otilde;","&ouml;","&divide;","&oslash;","&ugrave;","&uacute;","&ucirc;","&uuml;","&uuml;","&yacute;","&thorn;","&yuml;"]
		];

		// Replace each instance of one of the above special characters with it's HTML equivelent
		if (html) {
			for(var j = 0; j < set[0].length; j++){
				html = html.replace(eval("/"+set[0][j]+"/g"),set[1][j]);
			}
		}
	}
	// Return the HTML or an empty string if no HTML was supplied
	return html || "";
}

function ccParser(html) {
	html = html.replace(/@/gi,"_AT_");
	html = html.replace(/#/gi,"_HASH_");
  html = html.replace(/%/gi,"_PERC_");	

	var htmltag = /(&lt;[\w\/]+[ ]*[\w\=\"\'\.\/\;\: \)\(-]*&gt;)/gi;
	//var htmltag = /(&lt;.*?&gt;)/gi;
	html = html.replace(htmltag,"<span class=ccp_tag>$1</span>");

	var imgtag = /<span class=ccp_tag>(&lt;IMG[ ]*[\w\=\"\'\.\/\;\: \)\(-]*&gt;)<\/span>/gi;
	html = html.replace(imgtag,"<span class=ccp_img>$1</span>");

	var formtag = /<span class=ccp_tag>(&lt;[\/]*(form|input){1}[ ]*[\w\=\"\'\.\/\;\: \)\(-]*&gt;)<\/span>/gi;
	html = html.replace(formtag,"<br><span class=ccp_form>$1</span>");

	var tabletag = /<span class=ccp_tag>(&lt;[\/]*(table|tbody|th|tr|td){1}([ ]*[\w\=\"\'\.\/\;\:\)\(-]*){0,}&gt;)<\/span>/gi;
	html = html.replace(tabletag,"<span class=ccp_table>$1</span>");

	//var Atag = /<span class=ccp_tag>(&lt;(\/a&gt;|[\W _\w\=\"\'\.\/\;\:\)\(-]&gt;){1})<\/span>/gi;
	var Atag = /<span class=ccp_tag>(&lt;\/a&gt;){1}<\/span>/gi;
	html = html.replace(Atag,"<span class=ccp_A>$1</span>");

	var Atag = /<span class=ccp_tag>(&lt;a [\W _\w\=\"\'\.\/\;\:\)\(-]+&gt;){1,}<\/span>/gi;
	html = html.replace(Atag,"<span class=ccp_A>$1</span>");

	var parameter = /=("[ \w\'\.\/\;\:\)\(-]+"|'[ \w\"\.\/\;\:\)\(-]+')/gi;
	//var parameter = /=("(.|\\"|\\\r\n)*?((\\\\)+"|[^\\]{1}"))/gi;
	html = html.replace(parameter,"=<span class=ccp_paramvalue>$1</span>");

	var entity = /&amp;([\w]+);/gi;
	html = html.replace(entity,"<span class=ccp_entity>&amp;$1;</span>");

	var comment = /(&lt;\!--[\W _\w\=\"\'\.\/\;\:\)\(-]*--&gt;)/gi;
	html = html.replace(comment,"<br><span class=ccp_htmlcomment>$1</span>");

	html = html.replace(/_AT_/gi,"@");
	html = html.replace(/_HASH_/gi,"#");
	html = html.replace(/_PERC_/gi,"%");	

	return html;
}