/*editor javascript*/
/*para la paleta de colores*/
	function selectColor(color) {
		self.parent.setColor(color);
	}
	
	function InitColorPalette() {
		if (document.getElementsByTagName)
			var x = document.getElementsByTagName('TD');
		else if (document.all)
			var x = document.all.tags('TD');
		for (var i=0; i < x.length; i++) {
			x[i].onmouseover = over;
			x[i].onmouseout = out;
			x[i].onclick = click;
		}
	}
	
	function over() {
		this.style.border = '1px dotted white';
	}
	
	function out() {
		this.style.border = '1px solid gray';
	}
	
	function click() {
		selectColor(this.id);
	}

/*para la tabla*/
function AddTable() {
//	var widthType = (document.tableForm.widthType.value == "pixels") ? "" : "%";
	var html;

	html = "<table border='1'>\n"; /*border="' + document.tableForm.border.value + '" cellpadding="' + document.tableForm.padding.value + '" ';*/
	html +='<caption>'+ document.tableForm.resumen.value +'</caption>\n';
	/*html += 'cellspacing="' + document.tableForm.spacing.value + '" width="' + document.tableForm.width.value + widthType + '">\n';*/
	
	for (var rows = 0; rows < document.tableForm.rows.value; rows++) {
		html += "<tr>\n";
		for (cols = 0; cols < document.tableForm.columns.value; cols++) {

		if (document.tableForm.Encaarriba.checked==true && rows==0)
			html += "<th>&nbsp;</th>\n";
			else
	if (document.tableForm.Encalado.checked==true && rows>0 &&cols==0)
			html += "<th>&nbsp;</th>\n";
else
			html += "<td>&nbsp;</td>\n";

		}
		html+= "</tr>\n";
	}
	html += "</table>\n";

	window.opener.insertHTML(html);
	window.close();
}
function dlgInsertSmile(rte, command) {
 
 parent.command = command;
 currentRTE = rte;
 InsertLink = popUpWin(includesPath + 'EditorJS/smile.htm', 'InsertLink', 220, 40, '');
 
 //get currently highlighted text and set link text value
 setRange(rte);
 var linkText = '';
 if (isIE) {
  linkText = stripHTML(rng.htmlText);
 } else {
  linkText = stripHTML(rng.toString());
 }
 setLinkText(linkText);
}


/*para insertar un link de correo*/
function dlgInsertLinkEmail(rte, command) {
 //function to open/close insert table dialog
 //save current values
 parent.command = command;
 currentRTE = rte;
 InsertLink = popUpWin(includesPath + 'EditorJS/insert_mailto.aspx', 'InsertlinkEmail', 360, 180, '');
 
 //get currently highlighted text and set link text value
 setRange(rte);
 var linkText = '';
 if (isIE) {
  linkText = stripHTML(rng.htmlText);
 } else {
  linkText = stripHTML(rng.toString());
 }
 setLinkText(linkText);
}

function dlgInsertproperties(rte, command) {
 //function to open/close insert table dialog
 //save current values
 parent.command = command;
 currentRTE = rte;
 InsertLink = popUpWin(includesPath + 'EditorJS/insert_properties.aspx', 'Insertproperties', 400, 170, '');
 
 //get currently highlighted text and set link text value
 setRange(rte);
 var linkText = '';
 if (isIE) {
  linkText = stripHTML(rng.htmlText);
 } else {
  linkText = stripHTML(rng.toString());
 }
 setLinkText(linkText);
}

/*para insertar un div*/
function dlgInsertLinkDiv(rte, command){

 //save current values
 parent.command = command;
 currentRTE = rte;
 InsertLink = popUpWin(includesPath + 'EditorJS/insert_panel.aspx', 'InsertlinkEmail', 380, 180, '');
 
 //get currently highlighted text and set link text value
 setRange(rte);
 var linkText = '';
 if (isIE) {
  linkText = stripHTML(rng.htmlText);
 } else {
  linkText = stripHTML(rng.toString());
 }
 setLinkText(linkText);
}
/*para el insertar link*/
		
function AddItem() {
var html=document.getElementById('url').value;
window.opener.insertHTML(html);
	window.close();

	return true;
}
function AddLink() {

var html=document.getElementById('url').value;

html=html.replace('target="self"','');
html=html.replace('title=""','');
html=html.replace('>','title="' + document.getElementById('txttitulo').value + '" target="'+ document.getElementById('cbotar').value  +'">');


	window.opener.insertHTML(html);
	window.close();

	return true;
}
function adddiv() {

var html='<div class="' + document.getElementById('cboclas').value  + '">' + document.getElementById('linkText').value  +'</div>';

	window.opener.insertHTML(html);
	window.close();

	return true;
}

function AddImage() {
var html;
html='';
html=document.getElementById('url').value ;
html=html.replace('classimg=""', '');
if (document.getElementById('cboclase').value!='') html=html.replace('/>', ' class="'+ document.getElementById('cboclase').value + '"/>');

if (document.getElementById('linkimagen').value !='') {
html='<a title="' + document.getElementById('linktext').value + '" href="' + document.getElementById('linkimagen').value  + '">';
html=html + document.getElementById('url').value + '</a>';
}
html=html.replace('longdesc=""','longdesc="' + document.getElementById('txtlongtext').value + '"');





window.opener.insertHTML(html);
	window.close();

	return true;
}

/*a*/

//add \n before opening tag
var need_nl_before = '|div|p|table|tbody|tr|td|th|title|head|body|script|comment|li|meta|h1|h2|h3|h4|h5|h6|hr|ul|ol|option|';
//add \n after opening tag
var need_nl_after = '|html|head|body|p|th|style|';

var re_comment = new RegExp();
re_comment.compile("^<!--(.*)-->$");

var re_hyphen = new RegExp();
re_hyphen.compile("-$");


// Convert inner text of node to xhtml
// Call: get_xhtml(node);
//       get_xhtml(node, lang, encoding) -- to convert whole page
// other parameters are for inner usage and should be omitted
// Parameters:
// node - dom node to convert
// lang - document lang (need it if whole page converted)
// encoding - document charset (need it if whole page converted)
// need_nl - if true, add \n before a tag if it is in list need_nl_before
// inside_pre - if true, do not change content, as it is inside a <pre>
function get_xhtml(node, lang, encoding, need_nl, inside_pre,eliminar) {

var plant = /width="([^"]*)"/gi;
 var plant2 = /height="([^"]*)"/gi;
 var plant3 = /style="([^"]*)"/gi;
var plant4 = /width=([^"]*)/gi;
 var plant5 = /height=([^"]*)/gi;
 if ((plant.test(node.innerHTML) ||plant3.test(node.innerHTML) ||plant4.test(node.innerHTML)||plant5.test(node.innerHTML)
||plant2.test(node.innerHTML))&& eliminar==1) {
    question = confirm("Si pulsa Aceptar, se eliminan los estilos particulares del contenido");

 if (question){
 eliminar=2;


 } else  eliminar=0;
}



	var i;
	var text = '';
	var children = node.childNodes;
	var child_length = children.length;
	var tag_name;
	var do_nl = need_nl ? true : false;
	var page_mode = true;
	
	for (i = 0; i < child_length; i++) {
		var child = children[i];

		switch (child.nodeType) {
			case 1: { //ELEMENT_NODE
				var tag_name = String(child.tagName).toLowerCase();
				
				if (tag_name == '') break;
				
				if (tag_name == 'meta') {
					var meta_name = String(child.name).toLowerCase();
					if (meta_name == 'generator') break;
				}
				
				if (!need_nl && tag_name == 'body') { //html fragment mode
					page_mode = false;
				}
				
				if (tag_name == '!') { //COMMENT_NODE in IE 5.0/5.5
					//get comment inner text
					var parts = re_comment.exec(child.text);
					
					if (parts) {
						//the last char of the comment text must not be a hyphen
						var inner_text = parts[1];
						text += fix_comment(inner_text);
					}
				} else {
					if (tag_name == 'html') {
						text = '<?xml version="1.0" encoding="'+encoding+'"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n';
					}
					
					//inset \n to make code more neat
					if (need_nl_before.indexOf('|'+tag_name+'|') != -1) {
						if ((do_nl || text != '') && !inside_pre) text += '\n';
					} else {
						do_nl = true;
					}
					
					text += '<'+tag_name;
					
					//add attributes
					var attr = child.attributes;
					var attr_length = attr.length;
					var attr_value;
					
					var attr_lang = false;
					var attr_xml_lang = false;
					var attr_xmlns = false;
					
					var is_alt_attr = false;
					
					for (j = 0; j < attr_length; j++) {
						var attr_name = attr[j].nodeName.toLowerCase();
						
						if (!attr[j].specified && 
							(attr_name != 'selected' || !child.selected) && 
							(attr_name != 'style' || child.style.cssText == '') && 
							attr_name != 'value') continue; //IE 5.0
						
						if (attr_name == '_moz_dirty' || 
							attr_name == '_moz_resizing' || 
							tag_name == 'br' && 
							attr_name == 'type' && 
							child.getAttribute('type') == '_moz') continue;
						
						var valid_attr = true;
						
						switch (attr_name) {
							case "style":
								attr_value = child.style.cssText;
								break;
							case "class":
								attr_value = child.className;
								break;
							case "http-equiv":
								attr_value = child.httpEquiv;
								break;
							case "noshade": break; //this set of choices will extend
							case "checked": break;
							case "selected": break;
							case "multiple": break;
							case "nowrap": break;
							case "disabled": break;
								attr_value = attr_name;
								break;
							default:
								try {
									attr_value = child.getAttribute(attr_name, 2);
								} catch (e) {
									valid_attr = false;
								}
								break;
						}

						//html tag attribs
						if (attr_name == 'lang') {
							attr_lang = true;
							attr_value = lang;
						}
						if (attr_name == 'xml:lang') {
							attr_xml_lang = true;
							attr_value = lang;
						}
						if (attr_name == 'xmlns') attr_xmlns = true;
						if (valid_attr) {
							//value attribute set to "0" is not handled correctly in Mozilla
							if (!(tag_name == 'li' && attr_name == 'value')) {
								text += ' '+attr_name+'="'+fix_attribute(attr_value)+'"';
							}
						}
						
						if (attr_name == 'alt') is_alt_attr = true;
					}
					if (tag_name == 'img' && !is_alt_attr) {
						text += ' alt=""';
					}
					
					if (tag_name == 'html') {
						if (!attr_lang) text += ' lang="'+lang+'"';
						if (!attr_xml_lang) text += ' xml:lang="'+lang+'"';
						if (!attr_xmlns) text += ' xmlns="http://www.w3.org/1999/xhtml"';
					}
					
					if (child.canHaveChildren || child.hasChildNodes()){
						text += '>';
//						if (need_nl_after.indexOf('|'+tag_name+'|') != -1) {
//							text += '\n';
//						}





		
						text += get_xhtml(child, lang, encoding, true, inside_pre || tag_name == 'pre' ? true : false,eliminar);
						text += '</'+tag_name+'>';
					} else {
						if (tag_name == 'style' || tag_name == 'title' || tag_name == 'script') {
					text += '>';
							var inner_text;
							if (tag_name == 'script') {
								inner_text = child.text;
							} else {
								inner_text = child.innerHTML;
							}
							
							if (tag_name == 'style') {
								inner_text = String(inner_text).replace(/[\n]+/g,'\n');
							}
							
							text += inner_text+'</'+tag_name+'>';
						} else if (tag_name == 'br') 
							text += ' />';
						else if (tag_name != '/tr' && tag_name != '/td'  && tag_name != 'tr' && tag_name != 'td') 
							text += '/>';
						else if (tag_name == '/tr' || tag_name == '/td'  || tag_name == 'tr' || tag_name == 'td') 
							text += '>';
						
					}
				}
				break;
			}
			case 3: { //TEXT_NODE
				if (!inside_pre) { //do not change text inside <pre> tag
					if (child.nodeValue != '\n') {
						text += fix_text(child.nodeValue);
					}
				} else {
					text += child.nodeValue;
				}
				break;
			}
			case 8: { //COMMENT_NODE
				text += fix_comment(child.nodeValue);
				break;
			}
			default:
				break;
		}
	}
	
	if (!need_nl && !page_mode) { //delete head and body tags from html fragment
		text = text.replace(/<\/?head>[\n]*/gi, "");
		text = text.replace(/<head \/>[\n]*/gi, "");
		text = text.replace(/<\/?body>[\n]*/gi, "");
	}
	text = text.replace(/<script\w*([^>]*)>/gi, "");
	text = text.replace(/<\/script\w*([^>]*)>/gi, "");

	text = text.replace(/<font\w*([^>]*)>/gi, "");
	 text = text.replace(/<\/?font>[\n]*/gi, "");
	text = text.replace(/<tbody\w*([^>]*)>/gi, "");
	 text = text.replace(/<\/?tbody>[\n]*/gi, "");
/*text = text.replace("'", "");*/
		if (eliminar==2)
{

 text = text.replace(/width="([^"]*)"/gi, "");
 text = text.replace(/height="([^"]*)"/gi, "");
 text = text.replace(/width=\w/gi, "");
 text = text.replace(/height=\w/gi, "");
 text = text.replace(/style="([^"]*)"/gi, "");



}
text=text.replace(location.href.substring(0,location.href.indexOf('mantenimiento')),'');



	return text;
}

//fix inner text of a comment
function fix_comment(text) {
	//delete double hyphens from the comment text
	text = text.replace(/--/g, "__");
	
	if(re_hyphen.exec(text)) { //last char must not be a hyphen
		text += " ";
	}
	
	return "<!--"+text+"-->";
}

//fix content of a text node
function fix_text(text) {
	//convert <,> and & to the corresponding entities
	return String(text).replace(/\n{2,}/g, "\n").replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\u00A0/g, "&nbsp;");
}

//fix content of attributes href, src or background
function fix_attribute(text) {
	//convert <,>, & and " to the corresponding entities
	return String(text).replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
}
/*b*/

//init variables
var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";
var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;
var generateXHTML;

var lang = "en";
var encoding = "iso-8859-1";


function initRTE(imgPath, incPath, css, genXHTML) {
	//set browser vars
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); 
	isGecko = (ua.indexOf("gecko") != -1);
	isSafari = (ua.indexOf("safari") != -1);
	isKonqueror = (ua.indexOf("konqueror") != -1);
	
	generateXHTML = genXHTML;
	
	//check to see if designMode mode is available
	//Safari/Konqueror think they are designMode capable even though they are not
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}
	
	if (isIE) {
		document.onmouseover = raiseButton;
		document.onmouseout  = normalButton;
		document.onmousedown = lowerButton;
		document.onmouseup   = raiseButton;
	}
	
	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
	
	if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'EditorJS/css/rte.css";</style>');
	
	//for testing standard textarea, uncomment the following line
	//isRichText = false;

}
function enableDesignMode(rte, html, readOnly) {
	var frameHtml = "<html id=\"" + rte + "\">\n";
	frameHtml += "<head>\n";
	//to reference your stylesheet, set href property below to your stylesheet path and uncomment
	if (cssFile.length > 0) {
		frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
	} else {
		frameHtml += "<style>\n";
		frameHtml += "body {\n";
		frameHtml += "	background: #FFFFFF;\n";
		frameHtml += "	margin: 0px;\n";
		frameHtml += "	padding: 0px;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
	}
	frameHtml += "</head>\n";
	frameHtml += "<body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";
	
	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) {
			oRTE.designMode = "On";
			frames[rte].document.attachEvent("onkeypress", function evt_ie_keypress(event) {ieKeyPress(event, rte);});
		}
	} else {
		try {
			if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try {
				var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if (isGecko && !readOnly) {
					//attach a keyboard handler for gecko browsers to make keyboard shortcuts work
					oRTE.addEventListener("keypress", geckoKeyPress, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
}

function updateRTE(rte) {
		if (!isRichText) return;

	//check for readOnly mode
	var readOnly = false;
	if (document.all) {
		if (frames[rte].document.designMode != "On") readOnly = true;
	} else {
		if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
	}

	if (isRichText && !readOnly) {
		//if viewing source, switch back to design view
		if (document.getElementById("chkSrc" + rte).checked) document.getElementById("chkSrc" + rte).click();
//if (document.getElementById("chkSrcPrv" + rte).checked) document.getElementById("chkSrcPrv" + rte).click();

		setHiddenVal(rte);

	}

}

function getHiddenVal() {
if (isIE) {
		linkText = stripHTML(rng.htmlText);
	} else {
		linkText = stripHTML(rng.toString());
	}

	
	return linkText;

}
function setHiddenVal(rte) {

	//set hidden form field value for current rte
	var oHdnField = document.getElementById('hdn' + rte);
eli=1;
	if (oHdnField.value == null) oHdnField.value = "";
	if (document.all) {
		if (generateXHTML) {
			oHdnField.value = doCleanCode(get_xhtml(frames[rte].document.body, lang, encoding,false,false,eli)); 
		} else {;
			oHdnField.value = doCleanCode(frames[rte].document.body.innerHTML);
		}
	} else {
		if (generateXHTML) {
			oHdnField.value = doCleanCode(get_xhtml(document.getElementById(rte).contentWindow.document.body, lang, encoding,false,false,eli));
		} else {
			oHdnField.value = doCleanCode(document.getElementById(rte).contentWindow.document.body.innerHTML);
		}
	}

	//if there is no content (other than formatting) set value to nothing
	if (stripHTML(oHdnField.value.replace("&nbsp;", " ")) == "" &&
		oHdnField.value.toLowerCase().search("<hr") == -1 &&
		oHdnField.value.toLowerCase().search("<img") == -1) oHdnField.value = "";

var combo;

combo=document.getElementById('oculta_' + rte);


for (j = 0; j < combo.length; j++)
{
oHdnField.value=oHdnField.value.replace('class='+combo[j].text,'claszs="'+combo[j].text+'"');
oHdnField.value=oHdnField.value.replace('class="'+combo[j].text 
+'"','claszs="'+combo[j].text+'"');
}

    // oHdnField.value = oHdnField.value.replace(/class=([^ |>]*)([^>]*)/gi, "");
     oHdnField.value = oHdnField.value.replace(/claszs/gi, "class");


megabucle(rte);

	
}

function updateRTEs() {
	var vRTEs = allRTEs.split(";");
	for (var i = 0; i < vRTEs.length; i++) {
		updateRTE(vRTEs[i]);
	}
}



function rteCommand(rte, command, option) {
//function to perform command
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	try {
		oRTE.focus();
	  	oRTE.document.execCommand(command, false, option);
		oRTE.focus();
	} catch (e) {
//		alert(e);
//		setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 10);
	}
}

function toggleHTMLSrc(rte, buttons) {

	//contributed by Bob Hutzel (thanks Bob!)
	var oHdnField = document.getElementById('hdn' + rte);
	
	if (document.getElementById("chkSrc" + rte).checked) {
		//we are checking the box
		if (buttons) {
			showHideElement("Buttons1_" + rte, "hide");
			showHideElement("Buttons2_" + rte, "hide");
		}
		setHiddenVal(rte);
		if (document.all) {
			frames[rte].document.body.innerText = oHdnField.value;
		} else {
			var oRTE = document.getElementById(rte).contentWindow.document;
			var htmlSrc = oRTE.createTextNode(oHdnField.value);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		//we are unchecking the box
		if (buttons) {
			showHideElement("Buttons1_" + rte, "show");
			showHideElement("Buttons2_" + rte, "show");
		}
		if (document.all) {
			//fix for IE
			var output = escape(frames[rte].document.body.innerText);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
			frames[rte].document.body.innerHTML = unescape(output);
		} else {
			var oRTE = document.getElementById(rte).contentWindow.document;
			var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
	}
}

function dlgColorPalette(rte, command) {
	//function to display or hide color palettes
	setRange(rte);
	
	//get dialog position
	var oDialog = document.getElementById('cp' + rte);
	var buttonElement = document.getElementById(command + '_' + rte);
	var iLeftPos = getOffsetLeft(buttonElement);
	var iTopPos = getOffsetTop(buttonElement) + (buttonElement.offsetHeight + 4);
	oDialog.style.left = (iLeftPos) + "px";
	oDialog.style.top = (iTopPos) + "px";
	
	if ((command == parent.command) && (rte == currentRTE)) {
		//if current command dialog is currently open, close it
		if (oDialog.style.visibility == "hidden") {
			showHideElement(oDialog, 'show');
		} else {
			showHideElement(oDialog, 'hide');
		}
	} else {
		//if opening a new dialog, close all others
		var vRTEs = allRTEs.split(";");
		for (var i = 0; i < vRTEs.length; i++) {
			showHideElement('cp' + vRTEs[i], 'hide');
		}
		showHideElement(oDialog, 'show');
	}
	
	//save current values
	parent.command = command;
	currentRTE = rte;
}

function dlgInsertTable(rte, command) {
	//function to open/close insert table dialog
	//save current values
	parent.command = command;
	currentRTE = rte;
	InsertTable = popUpWin(includesPath + 'EditorJS/insert_table.aspx', 'InsertTable', 410, 200, '',rte);
}






function dlgInsertLink(rte, command) {
	//function to open/close insert table dialog


	//save current values
	parent.command = command;
	currentRTE = rte;

	InsertLink = popUpWin(includesPath + 'EditorJS/insert_link.aspx', 'InsertLink', 375, 345, '',rte);

	//get currently highlighted text and set link text value
	setRange(rte);
	var linkText = '';
	if (isIE) {
		linkText = stripHTML(rng.htmlText);
	} else {
		linkText = stripHTML(rng.toString());
	}

	setLinkText(linkText);


}
function doItem(rte, command) {


	parent.command = command;
	currentRTE = rte;

	InsertLink = popUpWin(includesPath + 'EditorJS/insert_item.aspx', 'InsertItem', 380, 270, 'scrollbars=no,',rte);

	setRange(rte);
	var linkText = '';
	if (isIE) {
		linkText = stripHTML(rng.htmlText);
	} else {
		linkText = stripHTML(rng.toString());
	}

	setLinkText(linkText);


}

function dlgInsertImage(rte, command) {
	//function to open/close insert table dialog


	//save current values
	parent.command = command;
	currentRTE = rte;

	InsertLink = popUpWin(includesPath + 'EditorJS/insert_image.aspx', 'InsertImage', 400, 350, 'scrollbars=yes,',rte);

	//get currently highlighted text and set link text value
	setRange(rte);
	var linkText = '';
	if (isIE) {
		linkText = stripHTML(rng.htmlText);
	} else {
		linkText = stripHTML(rng.toString());
	}

	setLinkText(linkText);


}
function setLinkText(linkText) {

	//set link text value in insert link dialog

	try {
		window.InsertLink.document.linkForm.linkText.value = linkText;
	} catch (e) {
		//may take some time to create dialog window.
		//Keep looping until able to set.
		setTimeout("setLinkText('" + linkText + "');", 10);
	}

}

function popUpWin (url, win, width, height, options,rte) {
	var leftPos = (screen.availWidth - width) / 2;
	var topPos = (screen.availHeight - height) / 2;
	
	options += 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;
options += 'dialogHeight:' + height + 'px,dialogWidth:' + width + 'px,dialogLeft:' + leftPos + ',dialogTop:' + topPos;

	return window.open(url, win, options);
	//return showModalDialog(url,win,options)
}

function setColor(color) {
	//function to set color
	var rte = currentRTE;
	var parentCommand = parent.command;
	
	if (document.all) {
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		
		//retrieve selected range
		rng.select();
	}
	
	rteCommand(rte, parentCommand, color);
	showHideElement('cp' + rte, "hide");
}
function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2; //the positioning div is 2 elements up the tree
	
	while(parents_up > 0) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2;
	
	while(parents_up > 0) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetLeft;
}
function dameseleccion(rte){
 setHiddenVal(rte);

 setRange(rte);
 var linkText = '';
 if (isIE) {
  linkText = stripHTML(rng.htmlText);
 } else {
  linkText = stripHTML(rng.toString());
 }
 setLinkText(linkText);
 return linkText;
}
 
function selectFont(rte, selectname) {
var cal;val=document.getElementById('formatblock_' + rte).value;
 textoseleccion=dameseleccion(rte);

 var rteaux;
 rteaux=rte;
 clase='';
 //function to handle font changes
 var idx = document.getElementById(selectname).selectedIndex;
 // First one is always a label
 if (idx != 0) {
  var selected = document.getElementById(selectname).options[idx].value;

 selectedorigin='';

  if (selected.indexOf('_')>-1) {
   clase=selected.substring(selected.indexOf('_')+1);
   selected='<' + selected.substring(0,selected.indexOf('_')) +'>';
   selected=selected.replace(' >','>');
   selectedorigin=selected;
   selected=selected.replace('<span>','<div>');
   selected=selected.replace('< span>','<div>');
  }

 
  var cmd = selectname.replace('_' + rte, '');



 rte=rteaux;
//alert(setRange(rteaux).htmlText);
 var oRTE;
 oRTE = frames[rte];
if (selected=='<p>')
  oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(re,'<p>'+ textoseleccion + '</p>');


if (selected=='<h1>' || selected=='<h2>' || selected=='<h3>' || selected=='<h4>' || selected=='<h5>' || selected=='<h6>')
  oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(textoseleccion,selected + textoseleccion + selected.replace('<h','</h'));
  else if(selected=='<p>' ) { oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(textoseleccion,'<p>'+ textoseleccion + '</p>');}
  else if(selectedorigin!='<div>' && selectedorigin!='<span>') rteCommand(rte, cmd, selected);
  
 if (clase==' lang') 
{
var re = new RegExp('<DIV class=([^ |>]*)([^>]*)>' + textoseleccion + '</DIV>');
  var m = re.exec(oRTE.document.body.innerHTML);

  oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(re,'<div>'+ textoseleccion + '</div>');
  oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace('<DIV>','<span lang="en">');

}
else
 if (selectedorigin=='<li>' || selectedorigin=='<ul>'){

var aux=selectedorigin.replace('>','');

  oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(selectedorigin.toUpperCase(),aux +' class="' + clase + '">');

 }
 else
 if (selectedorigin=='<span>'){
/*
 var re = new RegExp('<DIV class=([^ |>]*)([^>]*)>' + textoseleccion + '</DIV>');
  var m = re.exec(oRTE.document.body.innerHTML);
  oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(re,'<div>'+ textoseleccion + '</div>');
  oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace('<DIV>','<span class="' + clase + '">');
*/
oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(textoseleccion ,'<span class="' + clase + '">' + textoseleccion + '</span>'); 

 } else
 if (selectedorigin=='<div>'){

oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace(textoseleccion ,'<div class="' + clase + '">' + textoseleccion + '</div>');

 
 }

     oRTE.document.body.innerHTML = oRTE.document.body.innerHTML.replace(/<H([1-9]) class=([^ |>]*)([^>]*)/gi, "<H$1")
     oRTE.document.body.innerHTML = oRTE.document.body.innerHTML.replace(/<ADDRESS class=([^ |>]*)([^>]*)/gi, "<address")
     oRTE.document.body.innerHTML = oRTE.document.body.innerHTML.replace(/<P class=([^ |>]*)([^>]*)/gi, "<p")
     oRTE.document.body.innerHTML = oRTE.document.body.innerHTML.replace(/<PRE class=([^ |>]*)([^>]*)/gi, "<pre")

 oRTE.document.body.innerHTML=oRTE.document.body.innerHTML.replace('<DIV></DIV>','');
 
 document.getElementById(selectname).selectedIndex = 0;
 }
document.getElementById('formatblock_' + rte).value=val;
}

 
  
function insertHTML(html) {

	//function to add HTML 
	var rte = currentRTE;
	
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	oRTE.focus();
	if (document.all) {
		var oRng = oRTE.document.selection.createRange();
		oRng.pasteHTML(html);
		oRng.collapse(false);
		oRng.select();

	} else {

		oRTE.document.execCommand('insertHTML', false, html);
	}
/*alert(location.host);*/
}

function showHideElement(element, showHide) {
	//function to show or hide elements
	//element variable can be string or object
	if (document.getElementById(element)) {
		element = document.getElementById(element);
	}
	
	if (showHide == "show") {
		element.style.visibility = "visible";
	} else if (showHide == "hide") {
		element.style.visibility = "hidden";
	}
}

function setRange(rte) {
	//function to store range of current selection
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		var selection = oRTE.document.selection; 
		if (selection != null) rng = selection.createRange();

	} else {

		oRTE = document.getElementById(rte).contentWindow;
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	return rng;
}

function stripHTML(oldString) {
	//function to strip all html
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");
	
	//replace carriage returns and line feeds
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");
	
	//trim string
	newString = trim(newString);
	
	return newString;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
	
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length - 1, retValue.length);
	
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length - 1);
      ch = retValue.substring(retValue.length - 1, retValue.length);
   }
	
	// Note that there are two spaces in the string - look for multiple spaces within the string
   while (retValue.indexOf("  ") != -1) {
		// Again, there are two spaces in each of the strings
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
   }
   return retValue; // Return the trimmed string back to the user
}

//********************
//Gecko-Only Functions
//********************
function geckoKeyPress(evt) {
	//function to add bold, italic, and underline shortcut commands to gecko RTEs
	//contributed by Anti Veeranna (thanks Anti!)
	var rte = evt.target.id;
	
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			rteCommand(rte, cmd, null);
			
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}
/****************/
function buscacode(rte){

	var reemplazar,texto,texto2;texto=frames[rte].document.body.innerHTML;
texto2=frames[rte].document.body.innerHTML;
	var k2,k,i,j,li;
	var cad,cadli,cadli2;
	j=0;
	li=0;
	k2=0;
	reemplazar=0;
	k=0;
cadli='';cadli2='';cad='';
var salir;
salir=0;
//alert(frames[rte].document.body.innerHTML);
	for (i=0;i<texto.length && salir==0;i++) {
	if(reemplazar!=0){salir=1;} else{
		if ((texto.substring(i,i+1)=='<' && k==0)||(texto.substring(i,i+1)=='L' && k==1)||(texto.substring(i,i+1)=='I' && k==2)){
			cadli=cadli+texto.substring(i,i+1);k=k+1;}
		else {			cadli='';k=0;}
	//cuando encuentre un <li...
		if(cadli=='<LI') {li=li+1;}
	if ((texto.substring(i,i+1)=='<' && k2==0)||(texto.substring(i,i+1)=='/' && k2==1)||(texto.substring(i,i+1)=='L' && k2==2)||(texto.substring(i,i+1)=='I' && k2==3)){
			cadli2=cadli2+texto.substring(i,i+1);k2=k2+1;}
		else {			cadli2='';k2=0;}
		//cuando encuentre un </li...
	if(cadli2=='</LI'){ li=li-1;}


		if ((texto.substring(i,i+1)=='c' && j==0)||(texto.substring(i,i+1)=='o' && j==1)||(texto.substring(i,i+1)=='d' && j==2)||(texto.substring(i,i+1)=='e' && j==3)||(texto.substring(i,i+1)=='$' && j==4)||(texto.substring(i,i+1)=='%' && j==5))
			{cad=cad + texto.substring(i,i+1);	j=j+1;}
		else	
			{cad='';j=0;}
			
	if(cad=='code$%' && li>0) {			reemplazar=i;}
	if(cad=='code$%' && li==0) {			reemplazar=-1;}
	}
		}
	if (reemplazar>0)texto2=texto2.replace('code$%','</li><li>');
	else texto2=texto2.replace('code$%','<br />');
frames[rte].document.body.innerHTML=texto2;
//setCaretTo(rte,reemplazar);
}
function ieKeyPress(evt, rte) {

	var key = (evt.which || evt.charCode || evt.keyCode);
	var stringKey = String.fromCharCode(key).toLowerCase();
	
//the following breaks list and indentation functionality in IE (don't use)
	switch (key) {
		case 13:
//			//insert <br> tag instead of <p>
//			//change the key pressed to null
			evt.keyCode = 0;
			currentRTE = rte;

if(document.getElementById('formatblock_' + rte).value =='<li>')
{   insertHTML('code$%'); buscacode(rte);


}else    {insertHTML('<br />'); }

	//frames[rte].document.body.innerHTML=frames[rte].document.body.innerHTML.replace('code$%','');

//			insertHTML('<br />');

			break;
	};
}
function checkspell() {
	//function to perform spell check
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell no detectado.  Click Ok para ir a la web de descargas."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		} else {
			alert("Error cargando ieSpell: Excepci&oacute;n " + exception.number);
		}
	}
}

function raiseButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageLowered') {
		el.className = 'rteImageRaised';
	}
}

function normalButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImageRaised' || className == 'rteImageLowered') {
		el.className = 'rteImage';
	}
}

function lowerButton(e) {
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageRaised') {
		el.className = 'rteImageLowered';
	}
}
function setValor(i){
 
if (!i) i=0;
 
if (document.getElementById("chkSrcrte" +(i + 1)).checked==true) document.getElementById("chkSrcrte" +(i + 1)).click();
 
 var vRTEs = allRTEs.split(";");
 
// for (var i = 0; i < vRTEs.length; i++) {

var objeto;
if (document.getElementById('_ctl1_controltextoeditor' + (i+1)))
objeto=document.getElementById('_ctl1_controltextoeditor' + (i+1));
 
if (document.getElementById('_ctl2_controltextoeditor' + (i+1)))
objeto=document.getElementById('_ctl2_controltextoeditor' + (i+1));
 
if (document.getElementById('_ctl3_controltextoeditor' + (i+1)))
objeto=document.getElementById('_ctl3_controltextoeditor' + (i+1));
 

objeto.value=doCleanCode(frames[vRTEs[i]].document.body.innerHTML);


//}
}
function submitForm() {
	//make sure hidden and iframe values are in sync before submitting form
	//to sync only 1 rte, use updateRTE(rte)
	//to sync all rtes, use updateRTEs
	updateRTE('rte1');
	//updateRTEs();
	alert("rte1 = " + document.RTEDemo.rte1.value);
	
	//change the following line to true to submit form
	return false;
}

function writeRichText(rte, html, width, height, buttons, readOnly,textoadicional,combo2,smileis) {
//if(!allRTEs)allRTEs="";
	if (isRichText) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;
		if (readOnly) buttons = false;
		//adjust minimum table widths
		if (isIE) {
			var tablewidth = width;
		} else {
			var tablewidth = width + 4;
		}

		document.writeln('<div class="rteDiv">');
		if (buttons == true) {
			document.writeln('<table class="rteBack" cellpadding=2 cellspacing=0 id="Buttons1_' + rte + '" width="' + tablewidth + '">');
			document.writeln('	<tr>');
			document.writeln('		<td>');
			document.writeln('			<select id="formatblock_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);">');
			document.writeln('				<option value="">Estilo</option>');
			document.writeln('				<option value="<p>">P&aacute;rrafo &lt;p&gt;</option>');
			document.writeln('				<option value="<h1>">Cabecera 1 &lt;h1&gt;</option>');
			document.writeln('				<option value="<h2>">Cabecera 2 &lt;h2&gt;</option>');
			document.writeln('				<option value="<h3>">Cabecera 3 &lt;h3&gt;</option>');
			document.writeln('				<option value="<h4>">Cabecera 4 &lt;h4&gt;</option>');
			document.writeln('				<option value="<h5>">Cabecera 5 &lt;h5&gt;</option>');
			document.writeln('				<option value="<h6>">Cabecera 6 &lt;h6&gt;</option>');
			document.writeln('				<option value="<address>">Direcci&oacute;n &lt;ADDR&gt;</option>');
			document.writeln('    <option value="<li>">Elemento de lista</option>');

			document.writeln('				<option value="<pre>">Formateado &lt;pre&gt;</option>');
document.writeln(textoadicional);
			document.writeln('			</select>');
			document.writeln('		</td>');
			document.writeln('		<td>');
			document.writeln(combo2);
/*		document.writeln('			<select id="fontname_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id)">');
			document.writeln('				<option value="Arial, Helvetica, sans-serif">Arial</option>'); 
			document.writeln('				<option value="Book Antiqua, Times New Roman, Times, serif">Book Antiqua</option>'); 
			document.writeln('				<option value="Bookman Old Style, Times New Roman, Times, serif">Bookman Old Style</option>'); 
			document.writeln('				<option value="Comic Sans MS, Arial, Helvetica, sans-serif">Comic Sans MS</option>'); 
			document.writeln('				<option value="Courier New, Courier, monospace">Courier</option>'); 
			document.writeln('				<option value="Times New Roman, Times, serif">Times</option>'); 
			document.writeln('				<option value="Trebuchet MS, Arial, Helvetica, sans-serif">Trebuchet MS</option>'); 
			document.writeln('				<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>'); 
			document.writeln('			</select>');
*/			document.writeln('		</td>');
			document.writeln('		<td>');
/*
			document.writeln('			<select unselectable="on" id="fontsize_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);">');
			document.writeln('				<option value="Size">Tama&ntilde;o</option>');
			document.writeln('				<option value="1">1</option>');
			document.writeln('				<option value="2">2</option>');
			document.writeln('				<option value="3">3</option>');
			document.writeln('				<option value="4">4</option>');
			document.writeln('				<option value="5">5</option>');
			document.writeln('				<option value="6">6</option>');
			document.writeln('				<option value="7">7</option>');
			document.writeln('			</select>');
*/			document.writeln('		</td>');
			document.writeln('		<td width="100%">');
			document.writeln('		</td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
			document.writeln('<table class="rteBack" cellpadding="0" cellspacing="0" id="Buttons2_' + rte + '" width="' + tablewidth + '">');
			document.writeln('	<tr>');
			document.writeln('		<td><img id="bold" class="rteImage" src="' + imagesPath + 'bold.gif" width="25" height="24" alt="Negrita" title="Negrita" onClick="rteCommand(\'' + rte + '\', \'bold\', \'\')" /></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'italic.gif" width="25" height="24" alt="It&aacute;lica" title="It&aacute;lica" onClick="rteCommand(\'' + rte + '\', \'italic\', \'\')"/></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'underline.gif" width="25" height="24" alt="Subrayado" title="Subrayado" onClick="rteCommand(\'' + rte + '\', \'underline\', \'\')"/></td>');
			document.writeln('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');

			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'left_just.gif" width="25" height="24" alt="Alinear Izquierda" title="Alinear Izquierda" onClick="rteCommand(\'' + rte + '\', \'justifyleft\', \'\')" /></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'centre.gif" width="25" height="24" alt="Centrar" title="Centrar" onClick="rteCommand(\'' + rte + '\', \'justifycenter\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'right_just.gif" width="25" height="24" alt="Alinear derecha" title="Alinear derecha" onClick="rteCommand(\'' + rte + '\', \'justifyright\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'justifyfull.gif" width="25" height="24" alt="Justificar" title="Justificar" onclick="rteCommand(\'' + rte + '\', \'justifyfull\', \'\')"></td>');
			document.writeln('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'hr.gif" width="25" height="24" alt="Regla Horizontal" title="Regla Horizontal" onClick="rteCommand(\'' + rte + '\', \'inserthorizontalrule\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'numbered_list.gif" width="25" height="24" alt="Lista Ordenada" title="Lista Ordenada" onClick="rteCommand(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'list.gif" width="25" height="24" alt="Lista Desordenada" title="Lista Desordenada" onClick="rteCommand(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'outdent.gif" width="25" height="24" alt="Reducir sangr&iacute;a" title="Reducir sangr&iacute;a" onClick="rteCommand(\'' + rte + '\', \'outdent\', \'\')"></td>');

			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'indent.gif" width="25" height="24" alt="Aumentar sangr&iacute;a" title="Aumentar sangr&iacute;a" onClick="rteCommand(\'' + rte + '\', \'indent\', \'\')"></td>');
			document.writeln('<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'button_superscript.gif" width="25" height="24" alt="Superscript" title="Superscript" onClick="rteCommand(\'' + rte + '\', \'Superscript\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'button_subscript.gif" width="25" height="24" alt="Subscript" title="Subscript" onClick="rteCommand(\'' + rte + '\', \'Subscript\', \'\')"></td>');
	document.writeln("</tr><tr>");			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'button_strikethrough.gif" width="25" height="24" alt="Tachado" title="Superscript" onClick="rteCommand(\'' + rte + '\', \'strikethrough\', \'\')"></td>');

  document.writeln('  <td><img class="rteImage" src="' + imagesPath + 'email.gif" alt="Insertar Link de correo" title="Insertar Link de correo" onClick="dlgInsertLinkEmail(\'' + rte + '\', \'\', \'\')"></td>');

/*  document.writeln('  <td><div id="table_' + rte + '"><img class="rteImage" src="' + imagesPath + 'button_properties.gif" width="25" height="24" alt="Insertar propiedades de página" title="Insertar propiedades de página" onClick="dlgInsertproperties(\'' + rte + '\', \'\', \'\')"></div></td>');
 
*/
/*			document.writeln('		<td>');
 document.writeln('<div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'textcolor.gif" width="25" height="24" alt="Color del Texto" title="Color del texto" onClick="dlgColorPalette(\'' + rte + '\', \'forecolor\', \'\')"></div>');*/
		//	document.writeln('		<td>');
/* document.writeln('<div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'button_form_down.gif" width="25" height="24" alt="Insertar panel" title="Insertar panel" onClick="dlgInsertLinkDiv(\'' + rte + '\', \'\', \'\')">');
*/

if (smileis!=0)   document.writeln('  <td><img class="rteImage" src="' + imagesPath + 'smiley.gif" width="25" height="24" alt="Insert Smile" title="Insertar smile" onClick="dlgInsertSmile(\'' + rte + '\', \'smile\')"></td>');


//			document.writeln('<td>');
/* document.writeln('<div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" width="25" height="24" alt="Color de Fondo" title="Color de fondo" onClick="dlgColorPalette(\'' + rte + '\', \'hilitecolor\', \'\')"></div>');*/
//document.writeln('</td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'hyperlink.gif" width="25" height="24" alt="Insertar V&iacute;nculo" title="Insertar V&iacute;nculo" onClick="dlgInsertLink(\'' + rte + '\', \'link\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'image.gif" width="25" height="24" alt="A&ntilde;adir Imagen" title="A&ntilde;adir Imagen" onClick="dlgInsertImage(\'' + rte + '\', \'image\')"></td>');
			document.writeln('		<td><div id="table_' + rte + '"><img class="rteImage" src="' + imagesPath + 'insert_table.gif" width="25" height="24" alt="Insertar Tabla" title="Insertar Tabla" onClick="dlgInsertTable(\'' + rte + '\', \'table\', \'\')"></div></td>');
		//	if (isIE) {
		//		document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="25" height="24" alt="Correci&oacute;n ortogr&aacute;fica" title="Correci&oacute;n ortogr&aacute;fica" onClick="checkspell()"></td>');
		//	}

					document.writeln('<td><img class="rteImage" src="' + imagesPath + 'cut.gif" width="25" height="24" alt="Cortar" title="Cortar" onClick="rteCommand(\'' + rte + '\', \'cut\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'copy.gif" width="25" height="24" alt="Copiar" title="Copiar" onClick="rteCommand(\'' + rte + '\', \'copy\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'paste.gif" width="25" height="24" alt="Pegar" title="Pegar" onClick="rteCommand(\'' + rte + '\', \'paste\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'caracteres.gif" alt="S&iacute;mbolos especiales" title="S&iacute;mbolos especiales" onClick="dochars(\'' + rte + '\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'undo.gif" width="25" height="24" alt="Hacer" title="Deshacer" onClick="rteCommand(\'' + rte + '\', \'undo\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'redo.gif" width="25" height="24" alt="Rehacer" title="Rehacer" onClick="rteCommand(\'' + rte + '\', \'redo\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'noticias.gif"  alt="Insertar elementos web" title="Insertar elementos web" onClick="doItem(\'' + rte + '\', \'\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'help.gif"  alt="Ayuda" title="Ayuda" onClick="doHelp()"></td>');
			document.writeln('		<td width="100%"></td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
		}
		
		document.writeln('<iframe id="' + rte + '" name="' + rte + '" width="' + width + 'px" height="' + height + 'px" src="' + includesPath + 'EditorJS/blank.htm"></iframe>');

		if (!readOnly) document.writeln('<br /><input style="border:0px" type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\',' + buttons + ');" />&nbsp;<label for="chkSrc' + rte + '">HTML</label>');
/*  if (!readOnly) document.writeln('<input type="checkbox" id="chkSrcPrv' + rte + '" onclick="Previa(\'' + rte + '\',' + buttons + ');" />&nbsp;<label for="chkSrcPrv' + rte + '">Previa</label>');
*/

if (!readOnly) document.writeln('<img src="Editorjs/imagesediver/pre.jpg" title="Vista Previa" alt="Vista Previa" onclick="Previa(\'' + rte + '\',' + buttons + 
');" />&nbsp;Vista Previa');


		document.writeln('<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + 'EditorJS/palette.aspx" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; position: absolute;"></iframe>');
		document.writeln('<input type="hidden"  id="hdn' + rte + '" name="' + rte + '" value="">');
		document.writeln('<input type="hidden" id="texto" name="texto" value="">');

		document.writeln('</div>');

		document.getElementById('hdn' + rte).value =  doCleanCode(html);
		enableDesignMode(rte, html, readOnly);

	} else {
		if (!readOnly) {
		
			document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;"   >' + doCleanCode(html) + '</textarea>');
		} else {
				document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;"   readonly>' + doCleanCode(html) + '</textarea>');
		}
		
	}
		
}


function enableDesignMode(rte, html, readOnly) {
	var frameHtml = "<html id=\"" + rte + "\">\n";
	frameHtml += "<head>\n";
	//to reference your stylesheet, set href property below to your stylesheet path and uncomment
	if (cssFile.length > 0) {
		frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
	} else {
		frameHtml += "<style>\n";
		frameHtml += "body {\n";
		frameHtml += "	background: #FFFFFF;\n";
		frameHtml += "	margin: 0px;\n";
		frameHtml += "	padding: 0px;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
	}
	frameHtml += "</head>\n";
	frameHtml += "<body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";
	
	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) {
			oRTE.designMode = "On";
			frames[rte].document.attachEvent("onkeypress", function evt_ie_keypress(event) {ieKeyPress(event, rte);});
		}
	} else {
		try {
			if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try {
				var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if (isGecko && !readOnly) {
					//attach a keyboard handler for gecko browsers to make keyboard shortcuts work
					oRTE.addEventListener("keypress", geckoKeyPress, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
}

/*de_xhtml*/
function getXHTML(content) {
  //alert(content);
  var html = new cls_html();
  html.setHTML(content);
  //return (content);
  return (html.toXHTML());
}

/**
 * Copyright 2004, Interspire. @author Jorgen Horstink <jorgen@interspire.com>
 */
Array.prototype.clone = __prototype_array_clone;
function __prototype_array_clone() {
  var temp = [];
  for(var i in this) {
    if (typeof this[i] == "object") {
      temp[i] = this[i].clone();
    } else {
      temp[i] = this[i];
    }
  }
  return temp;
}

var XHTML_TEMP_VAR = a;
a = null;
var a = new Array();
a['p'] = 1;             a['span'] = 1;		    a['a'] = 1;	          a['div'] = 1;
a['b'] = 1;		          a['u'] = 1;	          a['i'] = 1;	          a['td'] = 1;
a['img'] = 1;		        a['table'] = 1;	      a['input'] = 1;	      a['li'] = 1;
a['ol'] = 1;	          a['script'] = 1;	    a['br'] = 1;	        a['textarea'] = 1;
a['strong'] = 1;		    a['center'] = 1;	    a['cite'] = 1;	      a['code'] = 1;
a['col'] = 10;		      a['colgroup'] = 1;	  a['dd'] = 1;	        a['del'] = 1;
a['dir'] = 1;  		      a['dfn'] = 1; 	      a['acronym'] = 1;	    a['dl'] = 1;
a['dt'] = 1;		        a['em'] = 1;	        a['fieldset'] = 1;	  a['font'] = 1;
a['form'] = 1;		      a['frame'] = 1;	      a['frameset'] = 1;	  a['h1'] = 1;
a['h2'] = 1;		        a['h3'] = 1;	        a['h4'] = 1;	        a['h5'] = 1;
a['h6'] = 1;		        a['head'] = 1;	      a['hr'] = 1;	        a['html'] = 1;
a['area'] = 1;		      a['iframe'] = 1;	    a['base'] = 1;	      a['bdo'] = 1;
a['ins'] = 1;	  	      a['isindex'] = 1;	    a['kbd'] = 1;	        a['label'] = 1;
a['legend'] = 1;		    a['big'] = 1;	        a['link'] = 1;	      a['map'] = 1;
a['menu'] = 1;		      a['meta'] = 1;	      a['noframes'] = 1;	  a['noscript'] = 1;
a['object'] = 1;		    a['blockquote'] = 1;	a['optgroup'] = 1;	  a['option'] = 1;
a['!doctype'] = 1;      a['param'] = 1;	      a['pre'] = 1;	        a['q'] = 1;
a['s'] = 1;             a['samp'] = 1;	      a['body'] = 1;	      a['select'] = 1;
a['small'] = 1; 		    a['abbr'] = 1;	      a['strike'] = 1;	    a['caption'] = 1;
a['style'] = 1; 	      a['sub'] = 1;	        a['sup'] = 1;	        a['basefont'] = 1;
a['tbody'] = 1;	        a['address'] = 1;	    a['button'] = 1;	    a['tfoot'] = 1;
a['th'] = 1;		        a['thead'] = 1;	      a['title'] = 1;	      a['tr'] = 1;
a['tt'] = 1;		        a['applet'] = 1;	    a['ul'] = 1;	        a['v'] = 1;
a['embed'] = 1;         a['marquee'] = 1;     a['!doctype'] = 1;    a['!--'] = 1;
var _xhtml_parser_aTags = a;
a = null;
a = XHTML_TEMP_VAR;

/**
 * HTML : <hr noshade>
 * XHTML: <hr noshade="noshade" />
 */
var aEmptyAttributes = new Array();
aEmptyAttributes['compact'] = 1;
aEmptyAttributes['nowrap'] = 1;
aEmptyAttributes['ismap'] = 1;
aEmptyAttributes['declare'] = 1;
aEmptyAttributes['noshade'] = 1;
aEmptyAttributes['checked'] = 1;
aEmptyAttributes['disabled'] = 1;
aEmptyAttributes['readonly'] = 1;
aEmptyAttributes['multiple'] = 1;
aEmptyAttributes['selected'] = 1;
aEmptyAttributes['noresize'] = 1;
aEmptyAttributes['defer'] = 1;
aEmptyAttributes['nosave'] = 1;
var _xhtml_parser_aEmptyAttributes = aEmptyAttributes;

/**
 * Alle tags die geen sluittag hebben. Die tags moeten een slash aan het eind krijgen
 *
 * HTML : <br>
 * XHTML: <br />
 */
var aEmptyTags = new Array();
aEmptyTags['br'] = 1;
aEmptyTags['img'] = 1;
aEmptyTags['input'] = 1;
aEmptyTags['hr'] = 1;
aEmptyTags['link'] = 1;
aEmptyTags['meta'] = 1;
aEmptyTags['area'] = 1;
aEmptyTags['param'] = 1;
aEmptyTags['base'] = 1;
aEmptyTags['basefont'] = 1;
var _xhtml_parser_aEmptyTags = aEmptyTags;

var aFlushAfter = new Array();
aFlushAfter['td'] = 1;
aFlushAfter['tr'] = 1;
aFlushAfter['table'] = 1;
aFlushAfter['ul'] = 1;
aFlushAfter['select'] = 1;
aFlushAfter['html'] = 1;
aFlushAfter['body'] = 1;
_xhtml_parser_aFlushAfter = aFlushAfter;

var _xhtml_parser_aNoNestedTags = new Array();
_xhtml_parser_aNoNestedTags["li"] = 1;
_xhtml_parser_aNoNestedTags["option"] = 1;

var aDoNotAnalyse = new Array();
aDoNotAnalyse['script'] = 1;
aDoNotAnalyse['style'] = 1;
aDoNotAnalyse['textarea'] = 1;
var _xhtml_parser_aDoNotAnalyse = aDoNotAnalyse;

var aIgnoreTags = new Array();
aIgnoreTags["dl"] = 1;
aIgnoreTags["dd"] = 1;
aIgnoreTags["dt"] = 1;
_xhtml_parser_aIgnoreTags = aIgnoreTags;

/**
 * Alle HTML entiteiten moeten omgezet worden in XHTML.
 * Dezelfde omleiding wordt hier gebruikt als bij het zetten van
 * alle HTML tags.
 */
XHTML_TEMP_VAR = a;
a = null;
var a = new Array();
a['&nbsp;']   = '&nbsp;'; // Moet &nbsp; blijven!
a['&quot;']   = '&#34;';
a['&amp;']    = '&#38;';
a['&lt;']     = '&#60;';
a['&gt;']     = '&#62;';
a['&iexcl;']  = '&#161;';
a['&cent;']   = '&#162;';
a['&pound;']  = '&#163;';
a['&curren;'] = '&#164;';
a['&yen;']    = '&#165;';
a['&brvbar;'] = '&#166;';
a['&brkbar;'] = '&#166;';
a['&sect;']   = '&#167;';
a['&uml;']    = '&#168;';
a['&die;']    = '&#168;';
a['&copy;']   = '&#169;';
a['&ordf;']   = '&#170;';
a['&laquo;']  = '&#171;';
a['&not;']    = '&#172;';
a['&reg;']    = '&#174;';
a['&macr;']   = '&#175;';
a['&hibar;']  = '&#175;';
a['&deg;']    = '&#176;';
a['&plusmn;'] = '&#177;';
a['&sup2;']   = '&#178;';
a['&sup3;']   = '&#179;';
a['&acute;']  = '&#180;';
a['&micro;']  = '&#181;';
a['&para;']   = '&#182;';
a['&middot;'] = '&#183;';
a['&cedil;']  = '&#184;';
a['&sup1;']   = '&#185;';
a['&ordm;']   = '&#186;';
a['&raquo;']  = '&#187;';
a['&frac14;'] = '&#188;';
a['&frac12;'] = '&#189;';
a['&frac34;'] = '&#190;';
a['&iquest;'] = '&#191;';
a['&Agrave;'] = '&#192;';
a['&Aacute;'] = '&#193;';
a['&Acirc;']  = '&#194;';
a['&Atilde;'] = '&#195;';
a['&Auml;']   = '&#196;';
a['&Aring;']  = '&#197;';
a['&AElig;']  = '&#198;';
a['&Ccedil;'] = '&#199;';
a['&Egrave;'] = '&#200;';
a['&Eacute;'] = '&#201;';
a['&Ecirc;']  = '&#202;';
a['&Euml;']   = '&#203;';
a['&Igrave;'] = '&#204;';
a['&Iacute;'] = '&#205;';
a['&Icirc;']  = '&#206;';
a['&Iuml;']   = '&#207;';
a['&ETH;']    = '&#208;';
a['&Ntilde;'] = '&#209;';
a['&Ograve;'] = '&#210;';
a['&Oacute;'] = '&#211;';
a['&Ocirc;']  = '&#212;';
a['&Otilde;'] = '&#213;';
a['&Ouml;']   = '&#214;';
a['&times;']  = '&#215;';
a['&Oslash;'] = '&#216;';
a['&Ugrave;'] = '&#217;';
a['&Uacute;'] = '&#218;';
a['&Ucirc;']  = '&#219;';
a['&Uuml;']   = '&#220;';
a['&Yacute;'] = '&#221;';
a['&THORN;']  = '&#222;';
a['&szlig;']  = '&#223;';
a['&agrave;'] = '&#224;';
a['&aacute;'] = '&#225;';
a['&acirc;']  = '&#226;';
a['&atilde;'] = '&#227;';
a['&auml;']   = '&#228;';
a['&aring;']  = '&#229;';
a['&aelig;']  = '&#230;';
a['&ccedil;'] = '&#231;';
a['&egrave;'] = '&#232;';
a['&eacute;'] = '&#233;';
a['&ecirc;']  = '&#234;';
a['&euml;']   = '&#235;';
a['&igrave;'] = '&#236;';
a['&iacute;'] = '&#237;';
a['&icirc;']  = '&#238;';
a['&iuml;']   = '&#239;';
a['&eth;']    = '&#240;';
a['&ntilde;'] = '&#241;';
a['&ograve;'] = '&#242;';
a['&oacute;'] = '&#243;';
a['&ocirc;']  = '&#244;';
a['&otilde;'] = '&#245;';
a['&ouml;']   = '&#246;';
a['&divide;'] = '&#247;';
a['&oslash;'] = '&#248;';
a['&ugrave;'] = '&#249;';
a['&uacute;'] = '&#250;';
a['&ucric;']  = '&#251;';
a['&uuml;']   = '&#252;';
a['&yacute;'] = '&#253;';
a['&thorn;']  = '&#254;';
a['&yuml;']   = '&#255;';
var _xhtml_parser_aEntities = a;
a = null;
a = XHTML_TEMP_VAR;

/**
 * Alle modi:
 *
 * - 0: TEXT
 * - 1: OPEN TAG
 * - 2: CLOSE TAG
 * - 3: EMPTY TAG
 * - 4: COMMENT
 * - 5: CDATA
 * - 6: DOCTYPE
 */

function _xhtml_array() {
  /**
   * Haal alle Tags op en zet ze in de locale variabele this.aTags
   */
  this.aTags = _xhtml_parser_aTags;
  this.aEntities = _xhtml_parser_aEntities
  this.aEmptyAttributes = _xhtml_parser_aEmptyAttributes;
  this.aEmptyTags = _xhtml_parser_aEmptyTags;
  this.aDoNotAnalyse = _xhtml_parser_aDoNotAnalyse;
  /**
   * Als er een SCRIPT tag gevonden wordt, dan moet de inhoud ervan
   * niet ge-analyseerd worden. Gewoon domweg doorlopen totdat er
   * een </script> gevonden wordt.
   */
  this.bInScriptTag = false;
  this.bDoNotAnalyse = false;
  this.sDoNotAnalyseTill = "";

  this.aRet = new Array();
  /**
   * Variabele met de HTML
   */
  this.sHTML = "";
  /**
   * Zet de HTML tekenreeks waarvan een Array moet worden gemaakt.
   */
  this.setHTML = function (sHTML) {
    this.sHTML = sHTML;
  }

  this.toArray = function () {
    /**
     * Dit is een zeer belangrijke variabele. Deze variabele houdt
     * bij in welke modus de parser zit. Er zijn verschillende
     * modi: 0=>IN_TEXT, 1=>IN_OPEN_TAG, 2=>IN_CLOSE_TAG, IN_ATTRIBUTE
     */
    var iMode = 0;

    var s = this.sHTML;
    var isl = s.length;

    this.currentEntry;

    /**
     * Zorg dat er altijd een parent tag paar is. Het algoritme
     * is afhankelijk van zo'n parent tagpaar.
     */
    this.setEntry();
    this.currentEntry["type"] = 1;
    this.currentEntry["tagname"] = "XHTML_PARENT_TAG";
    /**
     * Door de value op "" te zetten zorg je ervoor dat de waarde
     * bij het genereren van de output string niet beďnvloed wordt.
     */
    this.currentEntry["value"] = "";

    /**
     * Zet de eerste entry en geef hem als type "text" mee
     */
    this.setEntry();
    this.currentEntry["type"] = 0;
//    this.setEntryValue("type", 0, false);

    /**
     * Deze lus, leest de tekenreeks, teken voor teken in. Bij
     * bepaalde tekens, zoals <, > en :, wordt er gekeken in
     * welke modus de parser zit. Die modus is afhankelijk voor het
     * verdere gedrag van de parser. Bijvoorbeeld constateren dat
     * een nieuwe tag geopend wordt, of dat er een tag afgesloten
     * wordt.
     */
    for (var i = 0; i < isl; i++) {
      var c = s.substr(i, 1);
      switch (c) {
        case "<":
          /**
           * Er is een < geopend. Dat kan betekenen dat er een HTML
           * tag aankomt. Alleen als de parser in text modus is kan
           * de < het begin van een tag betekenen.
           */
          if (iMode == 0) {

            /**
             * posType houdt bij of het mogelijke type een OPEN tag
             * of een CLOSE tag kan zijn.
             */
            var posType = 1;
            /**
             * Hier wordt een tijdelijke variabele aangemaakt. i+1
             * houdt in dat je niet het < teken erbij wil hebben. Er
             * wordt expres voor lengte 12 gekozen, omdat een HTML
             * tagname nooit langer is dan 12 karakters.
             */
            var sTemp = s.substr(i + 1, 12);

            /**
             * Als het teken na de < een slash is dan kan het een
             * sluit tag zijn.
             */
            if (sTemp.charCodeAt() == 47) {
              sTemp = sTemp.substr(1);
              posType = 2;
            }
            var iTempLength = sTemp.length;
            /**
             * Analyseer elk teken van de tijdelijke variabele. Als
             * er geen cijfer of nummer gevonden wordt, dan moet er
             * gestopt worden. 
             */
            for (var j = 0; j < iTempLength; j++) {
              code = sTemp.charCodeAt(j);
              if (!((code > 96 && code < 123) || (code > 64 && code < 91) || (code > 47 && code < 58) || (code == 33) || (code == 45))) {
                break;
              }
            }
            var posTag = sTemp.substr(0, j);
            posTag = posTag.toLowerCase();

            if (this.bDoNotAnalyse == true && posTag != this.sDoNotAnalyseTill) {
              this.currentEntry["value"] += "<";
              break;
            }

            /**
             * Controleer op commentaar blokken
             */
            if (s.substr(i + 1, 3) == "!--") {
              iStart = i;
              i += 3;
              bFound = false;
              code = s.charCodeAt(i);
              while (bFound == false) {
                i++;
                code = s.charCodeAt(i);
                /**
                 * als het teken een - is en het volgende teken ook een - en het teken daarna een > dan is het het einde van
                 * een commentaar blok
                 */
                if (code == 45 && s.charCodeAt(i+1) == 45 && s.charCodeAt(i+2) == 62) {
                  bFound = true;
                  i += 3;
                }
              }
              if (this.currentEntry && !(this.currentEntry['type'] == 0 && this.currentEntry['value'] == '')) {
                this.setEntry();
              }
              this.currentEntry["type"] = 4;
              this.currentEntry["tagname"] = "";
              this.currentEntry["value"]   = s.substr(iStart, i - iStart);
              this.setEntry();
              this.currentEntry["type"]  = 0;
              this.currentEntry["value"] = "";
              i--;
              break;
            }

            if (posTag == "!doctype") {
              i += posTag.length + 1;
              iStart = i;
              code = s.charCodeAt(i);
              while (code != 62) {
                i++;
                code = s.charCodeAt(i);
              }
              if (this.currentEntry && !(this.currentEntry['type'] == 0 && this.currentEntry['value'] == '')) {
                this.setEntry();
              }
              this.currentEntry["type"] = 6;
              this.currentEntry["tagname"] = "!doctype";
              this.currentEntry["value"]   = s.substr(iStart, i - iStart);
              this.setEntry();
              this.currentEntry["type"] = 0;
              this.currentEntry["value"] = "";
              iMode = 0;
              break;
            }

            if (this.bDoNotAnalyse == true && this.sDoNotAnalyseTill == posTag) {
              this.bDoNotAnalyse = false;
            }

            /**
             * Als het inderdaad de opening van een tag is, voeg dan
             * een nieuwe entry toe, zet het type, tagnaam en de
             * eerste "<". 
             */
            if (this.aTags[posTag] == 1) {
              /**
               * Als de vorige entry nog leeg is en van het type text, dan kan die entry
               * gebruikt worden.
               */
              if (this.currentEntry && !(this.currentEntry['type'] == 0 && this.currentEntry['value'] == '')) {
                this.setEntry();
              }

              this.currentEntry["tagname"] = posTag;
              if (this.aEmptyTags[posTag] == 1) {
                this.currentEntry["type"] = 3;
              } else {
                this.currentEntry["type"] = posType;
              }
              if (posType == 1) {
                this.currentEntry["value"] += "<" + posTag;
                i += posTag.length;
                iMode = 1;
              }
              if (posType == 2) {
                this.currentEntry["value"] += "</" + posTag;
                i += posTag.length + 1;
                iMode = 2;
              }

            } else {
              /**
               * De modus is IN_TEXT en er is geen tag. Vervang de <
               * daarom voor zijn HTML entiteit.
               */
              this.currentEntry["value"] += "&#60;";
            }
            break;
          }
          break;
        case ">":
          if (this.aDoNotAnalyse[posTag] == 1 && posType == 1) {
            this.sDoNotAnalyseTill = posTag;
            this.bDoNotAnalyse = true;
            this.currentEntry["value"] += ">";
            this.setEntry();
            this.currentEntry["type"] = 5;
            iMode = 0;
            break;
          }
          /**
           * Als de modus IN_OPEN_TAG is, dan wordt nu de tag afgesloten.
           * Voeg daarom nog het > toe aan de entry en open een nieuwe
           * entry en zet het type van die entry.
           */
          if (iMode != 0) {
            if (this.currentEntry["type"] == 3) {
              this.currentEntry["value"] += "/>";

            } else {
              this.currentEntry["value"] += ">";
            }
            iMode = 0;
            this.setEntry();
            this.currentEntry["type"] = 0;
            break;
          }

          if (this.bDoNotAnalyse == true) {
            this.currentEntry["value"] += ">";
            break;
          }
          /**
           * Als de modus IN_TEXT modus is, voeg dan gewoon het teken toe
           * Het is geen afsluiting van een tag, maar gewoon het teken.
           */
          if (iMode == 0) {
            this.currentEntry["value"] += "&#62;";
          }
          break;
        default:
          /**
           * Als de modus IN_TEXT is, voeg dat het teken toe aan de
           * laatste entry waarde
           */
          if (iMode == 0) {
            this.currentEntry["value"] += c;
            break;
          }

          if (iMode == 1) {
            /**
             * Het volgende teken is een whitespace, zo ja, loop dan net
             * zo lang totdat alle whitespaces weg zijn. 
             */
            code = s.charCodeAt(i);
            if (code == 32 || code == 10 || code == 13 || code == 9) {
              while (code == 32 || code == 10 || code == 13 || code == 9) {
                if (i > isl) {break;}
                i++;
                code = s.charCodeAt(i);
              }
            }
            /**
             * Nadat alle whitespaces verwijderd zijn, moet er gekeken worden
             * of er een attribuut is.
             */
            if ((code > 96 && code < 123) || (code > 64 && code < 91) || (code > 47 && code < 58) || code == 45) {
              /**
               * Zoek een mogelijk attribuut, een attribuut mag alleen bestaan
               * uit letters en cijfers.
               */
              var posAttrBegin = i;
              while ((code > 96 && code < 123) || (code > 64 && code < 91) || (code > 47 && code < 58) || code == 45) {
                if (i > isl) {break;}
                i++;
                code = s.charCodeAt(i);
              }
              var posAttr = s.substr(posAttrBegin, i - posAttrBegin);
              /**
               * Na de mogelijke attribuut naam, kunnen nog spaties voorkomen.
               * spaties voor het = teken, doorloop dus ook eerst die spaties.
               *
               * vb: <b onClick     ="">
               */
              if (code == 32 || code == 10 || code == 13 || code == 9) {
                while (code == 32 || code == 10 || code == 13 || code == 9) {
                  if (i > isl) {break;}
                  i++;
                  code = s.charCodeAt(i);
                }
              }
              /**
               * Is het gevonden teken een is-teken? Zo ja, dan is er een
               * attribuut gevonden. Dan moet er op zoek worden gegaan
               * naam de waarde van het attribuut.
               * 61 => "="
               */
              if (code == 61) {
                /**
                 * Nu eenmaal zeker is dat er een attribuut is, moet er dus
                 * op zoek worden gegaan naar de waarde van het attribuut. Na het
                 * is-teken kunnen opnieuw spaties voorkomen. Doorloop dus eerst
                 * die spaties.
                 */
                i++;
                code = s.charCodeAt(i);
                if (code == 32 || code == 10 || code == 13 || code == 9) {
                  while (code == 32 || code == 10 || code == 13 || code == 9) {
                    if (i > isl) {break;}
                    i++;
                    code = s.charCodeAt(i);
                  }
                }
                c = s.substr(i, 1);
                /**
                 * Het volgende teken dat gevonden is, is geen teken voor het
                 * openen van een attribuut.
                 *
                 * vb: <b onClick=alert('foo');>
                 *
                 * Er moet nu doorgezocht worden totdat er een whitespace gevonden is
                 * elk teken mag, behalve whitespace en een sluit teken mag niet >
                 */
                if (code != 39 && code != 34) {
                  var attrValueBegin = i
                  while (!(code == 32 || code == 10 || code == 13 || code == 9) && code != 62) {
                    if (i > isl) {break;}
                    i++;
                    code = s.charCodeAt(i);
                  }
                  var attrValue = s.substr(attrValueBegin, i - attrValueBegin);
                  if (attrValue.match("/\"/g")) {
                    attrValue = "'" + attrValue + "'";
                  } else {
                    attrValue = "\"" + attrValue + "\"";
                  }
                  /**
                   * Voeg het attribuut en zijn waarde toe
                   */
                  this.currentEntry["value"] += " " + posAttr.toLowerCase() + "=" + attrValue;
                  //this.addAttribute(posAttr, attrValue);
                } else {
                  /**
                   * Het volgende teken is wel een " of een '. Nu moet er net zolang
                   * worden doorgezocht totdat er nog zo'n teken gevonden wordt; dat
                   * is het einde van het attribuut.
                   */
                  var end = code;
                  i++;
                  code = s.charCodeAt(i);
                  var attrValueBegin = i;
                  while (code != end) {
                    if (i > isl) {break;}
                    i++;
                    code = s.charCodeAt(i);
                  }
                  /**
                   * Deze regel gebruiken als je om de waarde van het attribuut alvast de "
                   * of ' wil hebben
                   */
                  var attrValue = s.substr(attrValueBegin - 1, i - attrValueBegin + 2);
                  //var attrValue = s.substr(attrValueBegin, i - attrValueBegin);

                  /**
                   * Voeg het attribuut en zijn waarde toe
                   */
                  this.currentEntry["value"] += " " + posAttr.toLowerCase() + "=" + attrValue;
                  //this.addAttribute(posAttr, attrValue);
                }

              } else {
                /**
                 * Dat er geen is-teken gevonden is, kan twee dingen betekenen:
                 * het is geen attribuut, of het is een leeg attribuut.
                 *
                 * vb: <hr noshade>
                 *
                 * Er moet dus gecontroleerd worden, of "posAttr" voorkomt in
                 * de array met attributen die leeg kunnen zijn. Zo ja, dan is het
                 * wel een attribuut. Zo nee, dan is het geen attribuut.
                 */
                if (this.aEmptyAttributes[posAttr] == 1) {
                  this.currentEntry["value"] += " " + posAttr.toLowerCase() + "=\"" + posAttr + "\"";
                  //this.addAttribute(posAttr, posAttr);
                }
              }

              i--;
            } else {
              /**
               * Dit kan soms voorkomen: voorbeeld: <hr   >
               */
              if (code == 62) {
                if (this.currentEntry["type"] == 3) {
                  this.currentEntry["value"] += " />";

                } else {
                  this.currentEntry["value"] += ">";
                }
                this.setEntry();
                this.currentEntry["type"] = 0;
                iMode = 0;
              }
            }
            break;
          }
      }
    }
    if (this.aRet[this.aRet.length - 1]["value"] == "") {
      this.aRet.length--;
    }

    /**
     * Zorg dat er altijd een parent tag paar is. Het algoritme
     * is afhankelijk van zo'n parent tagpaar. Deze code voegt
     * de sluittag toe.
     */
    this.setEntry();
    this.currentEntry["type"] = 2;
    this.currentEntry["tagname"] = "XHTML_PARENT_TAG";
    this.currentEntry["value"] = "";

    return this.aRet;
  }

  /**
   * Maak een nieuwe entry aan in de return Array.
   */
  this.setEntry = function () {
    var i = this.aRet.length;
    this.aRet[i]               = new Array();
    this.aRet[i]["tagname"]    = "";
    //this.aRet[i]["attributes"] = new Array();
    this.aRet[i]["type"]       = "";
    this.aRet[i]["value"]      = "";
    this.currentEntry = this.aRet[i];
  }

  this.addAttribute = function (sAttribute, sValue) {
/**

Tijdens het optimaliseren is gekozen om geen array van attributen bij
te houden. Het is mogelijk. Dan moet dit commentaar verwijderd
worden.

    var ai = this.currentEntry['attributes'].length;
    this.currentEntry['attributes'][ai] = new Array();
    this.currentEntry['attributes'][ai]['name']  = sAttribute.toLowerCase();;
    this.currentEntry['attributes'][ai]['value'] = sValue;
*/
  }
}

function _xhtml_nesting() {
  this.aData;
  this.setArray = function (a) {
    this.aData = a;
  }
  /**
   * Deze functie corrigeert de nesting van een gegeven array. Het algoritme
   * voor het corrigeren gaat er vanuit dat er een alles omvattend paar tags
   * is. In de meeste gevallen is dat de <HTML> tag.
   */
  this.correct = function () {
    var aReturn = new Array();
    var a = this.aData;
    var al = this.aData.length;

    var aNoNestedTags = _xhtml_parser_aNoNestedTags;
    var aFlushAfter = _xhtml_parser_aFlushAfter;
    var aIgnoreTags = _xhtml_parser_aIgnoreTags;
    /**
     * Een array met alle tags die zijn geopend
     */
    var aStack = new Array();
    //aStack[aStack.length] = a[0].clone();
    /**
     * Een array met alle tags die zijn gesloten voordat de juiste tag
     * gevonden werd.
     */
    var aFixStack = new Array();

    /**
     * Een array met alle tags die zijn geopend, verschil met de stack array
     * is dat in deze array de index van de array de tagname is. Zo kan snel
     * gekeken worden of een tag geopend (1) is of niet (0)
     */
    var aOpenTags = new Array();
    /**
     * Voeg de eerste tag toe aan de stack. En voeg een sluit paar toe aan het
     * einde van de invoer Array. Dit zorgt ervoor dat de array een parent
     * tag paar heeft.
     */
    //aStack[aStack.length] = new Array();
    //aStack[aStack.length - 1]["tagname"] = "parent_node";
    //aStack[aStack.length - 1]["type"]    = 1;
    //a[a.length] = aStack[aStack.length - 1].clone();
    //a[a.length - 1]["type"] = 2;
    /**
     * Doorloop alle items in de Array
     */
    for (var i = 0; i < al; i++) {
      var iType       = a[i]["type"];
      var sTagName    = a[i]["tagname"];
      switch (iType) {
        case 0: // TEXT NODE
          /**
           * Wanneer het een text node betreft kan de data gewoon direct aan de return
           * Array toegevoegd worden. De nesting hoeft niet geanalyseerd te worden.
           */
          aReturn[aReturn.length] = a[i].clone();
          break;
        case 1: // OPEN TAG NODE
          /**
           * Als de tag voor het eerst voorkomt, dan bestaat de entry aOpenTags[sTagName]
           * nog niet. Die moet dan aangemaakt worden en op nul gezet worden.
           */
          if (!aOpenTags[sTagName]) {
            aOpenTags[sTagName] = 0;
          }
          if (aIgnoreTags[sTagName]) {
            aReturn[aReturn.length] = a[i].clone();
            break;
          }

          if (aNoNestedTags[sTagName] == 1 && aOpenTags[sTagName] != 0) {
            /**
             * Bouw de stack af totdat de tag gevonden is
             */
            for (var j = aStack.length - 1; j > -1; j--) {
              if (aReturn[aReturn.length - 1]["algorithm"] == 1 && aReturn[aReturn.length - 1]["tagname"] == aStack[j]["tagname"]) {
                aReturn.length--;
                aStack.length--;
                //aReturn[aReturn.length] = a[i].clone();
                //alert('foo');
                break;
              }
              aOpenTags[aStack[aStack.length - 1]["tagname"]]--;
              aReturn[aReturn.length] = aStack[j].clone();
              aReturn[aReturn.length - 1]["type"] = 2;
              if (aStack[aStack.length - 1]["tagname"] == sTagName) {
                aStack.length--;
                break;
              }
              aFixStack[aFixStack.length] = aStack[j].clone();
              aStack.length--;
            }
            if (aStack.length == 0) {
              break;
            }
            /**
             * Heropen UL en OL tags voordat de LI tag geopend wordt...
             */
            for (var j = aFixStack.length - 1; j > -1; j--) {
              var tag = aFixStack[j]["tagname"];
              if (tag == "ul" || tag == "ol") {
                aOpenTags[tag]++;
                aReturn[aReturn.length] = aFixStack[j].clone();
                aStack[aStack.length] = aFixStack[j].clone();
              }
            }
            aOpenTags[sTagName]++;
            aReturn[aReturn.length] = a[i].clone();
            aStack[aStack.length] = a[i].clone();
            for (var j = aFixStack.length - 1; j > -1; j--) {
              /**
               * Negeer de UL en OL tags
               */
              var tag = aFixStack[j]["tagname"];
              if (tag == "ul" || tag == "ol") {
                continue;
              }
              for (var k = i + 1; k < al; k++) {
                if (!a[k]["value"].match("/^(\w)+$/gi")) {
                  /**
                   * Bug solve
                   */
                  if (a[k]["tagname"] == "") {
                    i=k-1;
                  } else {
                    i=k;
                  }
                  break;
                }
              }
              if (a[k]["tagname"] == aFixStack[j]["tagname"]) {;
                continue;
              }
              aOpenTags[aFixStack[j]["tagname"]]++;
              aReturn[aReturn.length] = aFixStack[j].clone();
              aReturn[aReturn.length - 1]["algorithm"] = 1;
              /**
               * Geef aan dat dit Item is ingevoegd door het algoritme. Wanneer de volgende
               * open tag merkt dat de laatste tag dezelfde naam heeft en de vorige tag is ingevoegd
               * door het algoritme. Dan moet de laatste uit de array gegooid worden en moet die
               * tag ook genegeerd worden.
               */
              aStack[aStack.length] = aFixStack[j].clone();
            }
            aFixStack.length = 0;
            break;
          }

          aOpenTags[sTagName]++;
          aReturn[aReturn.length] = a[i].clone();
          aStack[aStack.length] = a[i].clone();
          break;
        case 2: // CLOSE TAG NODE
          /**
           * De tag die gesloten wordt, is niet geopend. Daarom moet de tag genegeerd
           * worden; hij doet niet mee.
           */
          if (!(aOpenTags[sTagName] > 0)) {
            aOpenTags[sTagName] = 0;
            break;
          }
          for (var j = aStack.length - 1; j > -1; j--) {
            if (aReturn[aReturn.length - 1]["algorithm"] == 1 && aReturn[aReturn.length - 1]["tagname"] == aStack[j]["tagname"]) {
              aReturn.length--;
              aStack.length--;
              //aReturn[aReturn.length] = a[i].clone();
              //alert('foo');
              break;
            }
            aOpenTags[aStack[aStack.length - 1]["tagname"]]--;
            aReturn[aReturn.length] = aStack[j].clone();
            aReturn[aReturn.length - 1]["type"] = 2;
            if (aStack[aStack.length - 1]["tagname"] == sTagName) {
              aStack.length--;
              break;
            }
            aFixStack[aFixStack.length] = aStack[j].clone();
            aStack.length--;
          }
          if (aStack.length == 0) {
            break;
          }
          if (aFlushAfter[sTagName] != 1) {
            for (var j = aFixStack.length - 1; j > -1; j--) {
              if (aNoNestedTags[aFixStack[j]["tagname"]] == 1) {
                continue;
              }
              for (var k = i + 1; k < al; k++) {
                if (!a[k]["value"].match("/^(\w)+$/gi")) {
                  /**
                   * Bug solve
                   */
                  if (a[k]["tagname"] == "") {
                    i=k-1;
                  } else {
                    i=k;
                  }
                  break;
                }
              }
              if (a[k]["tagname"] == aFixStack[j]["tagname"]) {;
                continue;
              }
              aOpenTags[aFixStack[j]["tagname"]]++;
              aReturn[aReturn.length] = aFixStack[j].clone();
              aReturn[aReturn.length - 1]["algorithm"] = 1;
              /**
               * Geef aan dat dit Item is ingevoegd door het algoritme. Wanneer de volgende
               * open tag merkt dat de laatste tag dezelfde naam heeft en de vorige tag is ingevoegd
               * door het algoritme. Dan moet de laatste uit de array gegooid worden en moet die
               * tag ook genegeerd worden.
               */
              aStack[aStack.length] = aFixStack[j].clone();
            }
          }
          aFixStack.length = 0;
          /**
           * Verminder het aantal tags dat geopend is van tag sTagName met 1. Hij is namelijk
           * afgesloten. Het aantal open tags is nu nog oud - 1.
           */

          //aReturn[aReturn.length] = a[i].clone();
          break;
        case 3: // EMPTY TAG NODE
          /**
           * Wanneer het een empty tag betreft kan de data gewoon direct aan de return
           * Array toegevoegd worden. De nesting hoeft niet geanalyseerd te worden.
           */
          aReturn[aReturn.length] = a[i].clone();
          break;
        case 4: // COMMENT NODE
          aReturn[aReturn.length] = a[i].clone();
          break;
        case 5: // CDATA NODE
          aReturn[aReturn.length] = a[i].clone();
          break;
        case 6: // DOCTYPE NODE
          aReturn[aReturn.length] = a[i].clone();
          break;
      }
      if (aStack.length == 0) {
        break;
      }
    }
    /*alert(aOpenTags["table"]);
    alert(aOpenTags["td"]);
    alert(aOpenTags["tr"]);
    */
    return (aReturn);
  }
}

function _xhtml_string_builder() {
  this.a = new Array();
  this.setArray = function (a) {
    this.a = a
  }

  this.build = function () {
    var v = "";
    for (var i = 0; i < this.a.length - 1; i++) {
/**

Testje:

      v += this.a[i]["tagname"] + "\n";
      v += this.a[i]["type"] + "\n";
      v += this.a[i]["value"] + "\n---------------------------------------\n\n";
*/
      switch (this.a[i]["type"]) {
        case 0:
          v += this.a[i]["value"];
          break
        case 1:
          v += this.a[i]["value"];
          break;
        case 2:
          v += "</" + this.a[i]["tagname"] + ">";
          break;
        case 3:
          v += this.a[i]["value"];
          break;
        case 4:
          v += this.a[i]["value"];
          break;
        case 5:
          v += this.a[i]["value"];
          break;
        case 6:
          v += "<" + this.a[i]["tagname"] + this.a[i]["value"] + " />";

          break;
      }
    }
    v = this.removeEmptyTags (v)

    return (v);
  }

  this.removeEmptyTags = function (v) {
    v = v.replace(/(<font[^>]*>)([\s]*?)(<\/font[^>]*>)/gi, "");
    v = v.replace(/(<ul[^>]*>)([\s]*?)(<\/ul[^>]*>)/gi, "");
    v = v.replace(/(<ol[^>]*>)([\s]*?)(<\/ol[^>]*>)/gi, "");
    v = v.replace(/(<p[^>]*>)([\s]*?)(<\/p[^>]*>)/gi, "");
    //v = v.replace(/(<i[^>]*>)([\s]*?)(<\/i[^>]*>)/gi, "");
    //v = v.replace(/(<u[^>]*>)([\s]*?)(<\/u[^>]*>)/gi, "");
    return (v);
  }
}

function cls_html() {
  this.sHTML = "";
  this.sRet = "";

  this.setHTML = function (s) {
    this.sHTML = s;
  }

  this.toXHTML = function () {
    var xhtml_array = new _xhtml_array();
    xhtml_array.setHTML(this.sHTML);
    var xhtml_nesting = new _xhtml_nesting();
    xhtml_nesting.setArray(xhtml_array.toArray());
    this.aNesting = xhtml_nesting.correct();

    var xhtml_string_builder = new _xhtml_string_builder();
    xhtml_string_builder.setArray(this.aNesting);
    this.sRet = xhtml_string_builder.build();
    return this.sRet;
  }
}
/*de_functions*/
	var imageWin
	var propWin
	var inserttableWin
	var previewWin
	var modifytableWin
	var insertFormWin
	var textFieldWin
	var hiddenWin
	var buttonWin
	var checkboxWin
	var radioWin
	var linkWin
	var emailWin
	var anchorWin
	var showHelpWin
	var customInsertWin
	var charWin

	var selectedTD
	var selectedTR
	var selectedTBODY
	var selectedTable
	var selectedImage
	var selectedForm
	var selectedTextField
	var selectedTextArea
	var selectedHidden
	var selectedbutton
	var selectedCheckbox
	var selectedRadio

	var controlName

	var doSave = 0
	var zoomSize = 100

	// URL of StyleSheet used when adding StyleSheet with CodeSnippet
	var myStyleSheet = ""

	var fileCache
	fileCache = 0

	var statusMode = ""
	var statusBorders = ""
	var toggle = "off"
	var borderShown = "no"
	var fooURL
	var reloaded
	var justSwitched = false
	reloaded = 0
	var colorType = 0

	window.onload = doLoad
	window.onerror = stopError

	var loaded = false

	function saveDevEdit() {
	 updateValue(true)
	 parent.document.forms[0].submit()
	}

	function stopError() {
		return true;
	}

	function doLoad() {
		foo.document.designMode = 'On';
		setValue()

		if (tableDefault != 0) {
			toggleBorders();
		}
		fooURL = foo.location.href

		saveHistory(false)
		initFoo()
		setTimeout("updateValue();",1000); 
		doZoom(zoomSize)

		// set default background color of color drop down
		document.getElementById("fontColor").style.backgroundColor = "#000000"
		document.getElementById("fontHighlight").style.backgroundColor = "#FFFF00"
	}

	var stylesDisplayed = 0
	function doStyles() {
		if (foo.document.styleSheets.length > 0) {
			
			if (stylesDisplayed != 1)
			{
				displayUserStyles()
				stylesDisplayed = 1
			}

		}
	}

	function initFoo() {

		var iframes = document.all.tags("IFRAME");
		el = iframes[0];

		el.frameWindow = document.frames[el.id];

		el.frameWindow.document.oncontextmenu = function () {
			if (!el.frameWindow.event.ctrlKey){
				showContextMenu(el.frameWindow.event)
				return false;
			}
		}

		el.frameWindow.document.onerror = function () {
			return true;
		}

		el.frameWindow.document.onselectionchange = function () {
			if (doSave == 0)
			{
				doToolbar();
			}
		}

		el.frameWindow.document.onkeydown = function ()
		{
			if (el.frameWindow.event.keyCode == 13)
			{
				if (useBR)
				{

					var sel = el.frameWindow.document.selection;
					if (sel.type == "Control")
						return;

					if (!el.frameWindow.event.shiftKey)
					{

						var r = sel.createRange();	

						r.pasteHTML("<br />");
						
						el.frameWindow.event.cancelBubble = true; 
						el.frameWindow.event.returnValue = false; 

						r.select();
						r.moveEnd("character", 1);
						r.moveStart("character", 1);
						r.collapse(false);
						
						return false;

					} else
					{
					
						if (isCursorInList())
						{
							var r = sel.createRange();	
							r.pasteHTML("<li>&nbsp;</li>");
							el.frameWindow.event.cancelBubble = true; 
							el.frameWindow.event.returnValue = false; 
							
							r.moveStart("character", -1);
							r.collapse(true);
							r.select();

							return false;
						} else
						{
							var r = sel.createRange();	
							r.pasteHTML("<p>");
							el.frameWindow.event.cancelBubble = true; 
							el.frameWindow.event.returnValue = false; 

							r.collapse(true);
							r.select();
						
							return false;
						}
					}
				} else {
					var sel = el.frameWindow.document.selection;
					if (sourceModeOn)
					{
						var r = sel.createRange();	

						r.pasteHTML("<BR />");
						el.frameWindow.event.cancelBubble = true; 
						el.frameWindow.event.returnValue = false; 

						r.select();
						r.moveEnd("character", 1);
						r.moveStart("character", 1);
						r.collapse(false);
						
						return false;
					}
				}

			}

			if(el.frameWindow.event.ctrlKey) {
				if(el.frameWindow.event.keyCode == 90) {
					if (editModeOn) {

				      goHistory(-1);
					  return false;
					}
				} else if(el.frameWindow.event.keyCode == 89) {
					if (editModeOn) {
				      goHistory(1);
					  return false;
					}
				// Ctrl + Tab key
				} else if(el.frameWindow.event.keyCode == 9) {
				  var oSel = foo.document.selection.createRange();
				  oSel.pasteHTML("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
				  return false;
				} else if(el.frameWindow.event.keyCode == 68) {
			      pasteWord();
				  return false;
				} else if(el.frameWindow.event.keyCode == 66) {
			      doCommand("bold");
				  return false;
				} else if(el.frameWindow.event.keyCode == 85) {
			      doCommand("underline");
				  return false;
				} else if(el.frameWindow.event.keyCode == 73) {
			      doCommand("italic");
				  return false;
				} else if(el.frameWindow.event.keyCode == 75) {
					if (document.getElementById("toolbarLink_on") != null) {
				      doLink();
					  return false;
					} else {
					  return false;
					}
				}
			}

			if(!el.frameWindow.event.ctrlKey && el.frameWindow.event.keyCode != 90 && el.frameWindow.event.keyCode != 89) {
				if (el.frameWindow.event.keyCode == 32 || el.frameWindow.event.keyCode == 13)
				{
					saveHistory()
				}
			}

			if (el.frameWindow.event.keyCode == 118) {
				if (document.getElementById("toolbarSpell") != null)
				{
					spellCheck();
					return false;
				}
			}
		}

		el.frameWindow.document.onkeyup = function() {
			showCutCopyPaste()
			showPosition()
			showLink()
			showUndoRedo()
		}

		foo.document.execCommand("2D-Position",false, true)
	}

	function doColor(td) {
		if (colorType == 2) {
			myCommand = 'BackColor'
			oMenu = document.getElementById("fontHighlight")
		} else {
			myCommand = 'ForeColor'
			oMenu = document.getElementById("fontColor")
		}

		if (td)
		{
			oColor = td.childNodes(0).style.backgroundColor
			oMenu.style.backgroundColor = oColor
		} else {
			oColor = ''
			if (colorType == 2)
			{
				oMenu.style.backgroundColor = "#FFFFFF"
			} else {
				oMenu.style.backgroundColor = "#000000"
			}
		}
		
		foo.document.execCommand(myCommand,false,oColor);
		oPopup.hide()
	}

	function doColorDirectly(whichColor) {
		if (whichColor == 2) {
			myCommand = 'BackColor'
			oColor = document.getElementById("fontHighlight").style.backgroundColor
		} else {
			myCommand = 'ForeColor'
			oColor = document.getElementById("fontColor").style.backgroundColor
		}

		foo.document.execCommand(myCommand,false,oColor);
		oPopup.hide()
	}

	var oPopup = window.createPopup();

	function showMenu(menu, width, height)
	{
    
	var lefter = event.clientX;
	var leftoff = event.offsetX
	var topper = event.clientY;
	var topoff = event.offsetY;
	var oPopBody = oPopup.document.body;
	moveMe = 0

	if (menu == "pasteMenu")
	{
		moveMe = 22
	}

	if (menu == "zoomMenu")
	{
		lefter = lefter-18
		topper = topper - 203
	}

	if (menu == "colorMenu") {
		colorType = "0"
		moveMe = 22
	}

	if (menu == "colorMenu2") {
		colorType = "2"
		menu = "colorMenu"
		moveMe = 22
	}

	if (menu == "formMenu")
	{
		if (isCursorInForm()) {
			document.getElementById("modifyForm1").disabled = false
		} else {
			document.getElementById("modifyForm1").disabled = true
		}
	}

	if (menu == "tableMenu")
	{
	
		if (isCursorInTableCell() || isTableSelected()) {
			document.getElementById("modifyTable").disabled = false
		} else {
			document.getElementById("modifyTable").disabled = true
		}

		if (isCursorInTableCell())
		{
			document.getElementById("modifyCell").disabled = false
			document.getElementById("rowAbove").disabled = false
			document.getElementById("rowBelow").disabled = false
			document.getElementById("deleteRow").disabled = false
			document.getElementById("colAfter").disabled = false
			document.getElementById("colBefore").disabled = false
			document.getElementById("deleteCol").disabled = false
			document.getElementById("increaseSpan").disabled = false
			document.getElementById("decreaseSpan").disabled = false

		} else {
			document.getElementById("modifyCell").disabled = true
			document.getElementById("rowAbove").disabled = true
			document.getElementById("rowBelow").disabled = true
			document.getElementById("deleteRow").disabled = true
			document.getElementById("colAfter").disabled = true
			document.getElementById("colBefore").disabled = true
			document.getElementById("deleteCol").disabled = true
			document.getElementById("increaseSpan").disabled = true
			document.getElementById("decreaseSpan").disabled = true

		}
	}

	var HTMLContent = eval(menu).innerHTML
	oPopBody.innerHTML = HTMLContent
	oPopup.show(lefter - leftoff - 2 - moveMe, topper - topoff + 22, width, height, document.body);

	return false;
	}

	var oPopup2 = window.createPopup();
	function showContextMenu(event)
	{
    
		menu = "contextMenu"
		width = ContextMenuWidth
		height = "67"

		var lefter = event.clientX;
		var topper = event.clientY;
	
		var oPopBody = oPopup2.document.body;

		height = parseInt(height)

		if (foo.document.queryCommandEnabled("cut"))
		{
			document.getElementById("cmCut").disabled = false
		} else {
			document.getElementById("cmCut").disabled = true
		}

		if (foo.document.queryCommandEnabled("paste"))
		{
			document.getElementById("cmPaste").disabled = false
		} else {
			document.getElementById("cmPaste").disabled = true
		}

		if (foo.document.queryCommandEnabled("copy"))
		{
			document.getElementById("cmCopy").disabled = false
		} else {
			document.getElementById("cmCopy").disabled = true
		}

		var HTMLContent = "<table style='BORDER-LEFT: threedface 1px solid; BORDER-TOP: threedface 1px solid; BORDER-RIGHT: #404040 1px solid; BORDER-BOTTOM: #404040 1px solid;' cellpadding=0 cellspacing=0><tr><td>"
		HTMLContent = HTMLContent + eval(menu).innerHTML

		if (isImageSelected())
		{
			HTMLContent = HTMLContent + eval("cmImageMenu").innerHTML
			height = height + 23

			if (document.getElementById("toolbarLink_on") != null)
			{
			HTMLContent = HTMLContent + eval("cmLinkMenu").innerHTML
			height = height + 23
			}
			
		}

		if (isTextSelected() && (sourceModeView != true))
		{
			if (document.getElementById("toolbarLink_on") != null)
			{
			HTMLContent = HTMLContent + eval("cmLinkMenu").innerHTML
			height = height + 23
			}
		}

		if (isTableSelected() || isCursorInTableCell())
		{
			if (document.getElementById("toolbarTables") != null)
			{
				HTMLContent = HTMLContent + eval("cmTableMenu").innerHTML
				height = height + 23
			}
		}
		
		if (isCursorInTableCell())
		{
			if (document.getElementById("toolbarTables") != null)
			{

			HTMLContent = HTMLContent + eval("cmTableFunctions").innerHTML
			height = height + 199

			}
		}

		if (document.getElementById("toolbarSpell") != null)
		{
			HTMLContent = HTMLContent + eval("cmSpellMenu").innerHTML
			height = height + 23
		}

		HTMLContent = HTMLContent + "</td></tr></table>"
		oPopBody.innerHTML = HTMLContent
		
		oPopup2.show(lefter + 2,topper + 2, width, height, foo.document.body)
	}

	function doCommand(cmd) {

		if (isAllowed())
		{
			document.execCommand(cmd)
		}
		oPopup.hide()
		doToolbar()

		if (cmd == "AbsolutePosition")
		{
			foo.document.execCommand("2D-Position",false, true)
		}
	}

	function doFont(oFont) {
		if (isAllowed())
		{
			foo.document.execCommand('FontName',false,oFont)
		}
		foo.focus()
		doToolbar()
	}

	function doSize(oSize) {
		if (isAllowed())
		{
			foo.document.execCommand('FontSize',false,oSize)
		}
		foo.focus()
		doToolbar()
	}
	
	function doFormat(oFormat) {
		if (isAllowed())
		{
			foo.document.execCommand('formatBlock',false,oFormat)
		}
		foo.focus()
		doToolbar()
	}

	function doZoom(size) {

		foo.document.body.runtimeStyle.zoom = size + "%"

		document.getElementById("zoom500_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;500%&nbsp";
		document.getElementById("zoom200_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;200%&nbsp";
		document.getElementById("zoom150_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;150%&nbsp";
		document.getElementById("zoom100_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;100%&nbsp";
		document.getElementById("zoom75_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;75%&nbsp";
		document.getElementById("zoom50_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;50%&nbsp";
		document.getElementById("zoom25_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;25%&nbsp";
		document.getElementById("zoom10_").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;10%&nbsp";

		document.getElementById("zoom" + size + "_").innerHTML = "&nbsp;&nbsp;&nbsp;&#149;&nbsp;" + size + "%&nbsp";
		zoomSize = size
		oPopup.hide()
	}

	function doTextbox() {
		foo.focus()
		var oSel = foo.document.selection.createRange();
		oSel.pasteHTML("<table id=de_textBox style='position:absolute;'><tr><td>Text box</td></tr></table>");

		textBox = foo.document.getElementById("de_textBox")

		if (borderShown == "yes")
		{
			textBox.runtimeStyle.border = "1px dotted #BFBFBF"
			allRows = textBox.rows
				for (y=0; y < allRows.length; y++) {
			 	allCellsInRow = allRows[y].cells
					for (x=0; x < allCellsInRow.length; x++) {
							allCellsInRow[x].runtimeStyle.border = "1px dotted #BFBFBF"
					}
				}
		}

		textBox.removeAttribute("id")
	}

	function isTextSelected() {
			if (foo.document.selection.type == "Text") {
				return true;
			} else {
				return false;
			}
	}

	function doCleanCode(code) {

		// removes all Class attributes on a tag eg. '<p class=asdasd>xxx</p>' returns '<p>xxx</p>'
//		code = code.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, "<$1$3")
		//code = code.replace(/<([\w]+) futuclass=([^ |>]*)([^>]*)/gi, "<$1 class=$2$3")
		// removes all style attributes eg. '<tag style="asd asdfa aasdfasdf" something else>' returns '<tag something else>'
		code = code.replace(/<b>/gi, "<STRONG>");
		code = code.replace(/<\/b>/gi, "</STRONG>");
		code = code.replace(/<B>/gi, "<STRONG>");
		code = code.replace(/<\/B>/gi, "</STRONG>");
		code = code.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, "<$1$3")
		// gets rid of all xml stuff... <xml>,<\xml>,<?xml> or <\?xml>
		code = code.replace(/<\\?\??xml[^>]>/gi, "")
        // get rid of ugly colon tags <a:b> or </a:b>
		code = code.replace(/<\/?\w+:[^>]*>/gi, "")
		// removes all empty <p> tags
		code = code.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi,"")
		// removes all empty span tags
		code = code.replace(/<span([^>])*>(&nbsp;)*\s*<\/span>/gi,"")
		
		// Uncomment if you would like to create <BR> tags instead of <P> tags, therefore removing extra line spaces in generated code.
		// code = code.replace(/<p>/gi,"")
		 //code = code.replace(/<\/p>/gi,"<br />");
		 code = code.replace(location.href.substring(0,location.href.indexOf("index")),"");
		 code = code.replace(location.href.substring(0,location.href.indexOf("default")),"");

		return code
	}

	function pasteWord() {

		foo.focus()
		oPopup.hide()

		var oSel = foo.document.selection.createRange()
		if(oSel.parentElement)
		{
			TempArea = document.getElementById("myTempArea")
			TempArea.focus()
			TempArea.document.execCommand("SelectAll")
			TempArea.document.execCommand("Paste")
			// Remove ALL formatting as well as MS specific code
			// TempArea.document.execCommand("SelectAll")
			// TempArea.document.execCommand("RemoveFormat")
			// TempArea.document.execCommand("Unselect")
			code = doCleanCode(TempArea.innerHTML)
			oSel.pasteHTML(doCleanCode(myTempArea.innerHTML))
			oSel.select()
		}
	}

	function isAllowed() {
		var sel
		var obj
			
			sel = foo.document.selection
			
			if (sel.type != "Control")
			{
				obj = sel.createRange().parentElement()
			} else {
				obj = sel.createRange()(0)
			}
			
			if (obj.isContentEditable) {
				foo.focus()
				return true
			} else {
				return false
			}
	}
			
	function scrollUp() {
		foo.scrollBy(0,0);
	}
	
	var editModeOn = true;
	var editModeView = true;

	function editMe() {
		if (editModeView == false)
		{
			toolbar_full.className = "bevel3";
			toolbar_code.className = "hide";
			toolbar_preview.className = "hide"

			document.all.foo.style.display = "";
			document.all.previewFrame.style.display = "none";

			if (sourceModeOn)
			{
				SwitchMode()
			}

			editModeView = true;
			sourceModeView = false;
			previewModeView = false;

			sourceModeOn = false;
			editModeOn = true;

			document.getElementById("editTab").src = deveditPath1 + "/de_images/status_edit_up.gif"
			document.getElementById("sourceTab").src = deveditPath1 + "/de_images/status_source.gif"
			document.getElementById("previewTab").src = deveditPath1 + "/de_images/status_preview.gif"
			initFoo()
			foo.focus()
		}
	}

	var sourceModeOn = false;
	var sourceModeView = false;
	function sourceMe() {
		if (sourceModeView == false)
		{

			if (isEditingHTMLPage == 0)
			{
				if (foo.document.styleSheets.length > 0)
				{
					myStyleSheet = foo.document.styleSheets(0).href
				}
			}

			toolbar_full.className = "hide";
			toolbar_code.className = "bevel3";
			toolbar_preview.className = "hide"

			document.all.foo.style.display = "";
			document.all.previewFrame.style.display = "none";

			if (editModeOn)
			{
				SwitchMode()
			}

			sourceModeView = true;
			editModeView = false;
			previewModeView = false;

			editModeOn = false;
			sourceModeOn = true;

			document.getElementById("editTab").src = deveditPath1 + "/de_images/status_edit.gif"
			document.getElementById("sourceTab").src = deveditPath1 + "/de_images/status_source_up.gif"
			document.getElementById("previewTab").src = deveditPath1 + "/de_images/status_preview.gif"

			// update value breaks redo / undo buffer
			updateValue()
			foo.focus()
		}
	}

	var previewModeView = false;
	function previewMe() {
		if (previewModeView == false)
		{

			toolbar_full.className = "hide";
			toolbar_code.className = "hide";
			toolbar_preview.className = "bevel3"

			document.all.foo.style.display = "none";
			document.all.previewFrame.style.display = "";

			sourceModeView = false;
			editModeView = false;
			previewModeView = true;

			if (sourceModeOn) {
				ShowPreview(1)
			} else {
				ShowPreview(0)
			}

			document.getElementById("editTab").src = deveditPath1 + "/de_images/status_edit.gif"
			document.getElementById("sourceTab").src = deveditPath1 + "/de_images/status_source.gif"
			document.getElementById("previewTab").src = deveditPath1 + "/de_images/status_preview_up.gif"
		}
	}

	var Mode = "1";
	var toggleWasOn
	
	function SwitchMode () {
		var scriptcode

		 if (Mode == "1") {
			if (borderShown == "yes") {
				toggleBorders()
				toggleWasOn = "yes"
			} else {
				toggleWasOn = "no"
			}
			
			toolbar_full.className = "hide";
			toolbar_code.className = "bevel3";

			// Put HTML in editor
			if (isEditingHTMLPage == "0") {
				
				if (useXHTML == "1") {
					code = getXHTML(document.frames('foo').document.body.innerHTML)
				} else {
					code = foo.document.body.innerHTML
				}

			} else {

				if (useXHTML == "1") {
					code = getXHTML(document.frames('foo').document.documentElement.outerHTML)
				} else {
					code = foo.document.documentElement.outerHTML
				}
			}

			re = /&amp;/g
			code = code.replace(re,'&')

			if (pathType == "1") {
	
				// replaceHref = 'href="'
				replaceImage = 'src="'

				// code = code.replace(re2,replaceHref)
				code = code.replace(re3,replaceImage)
			}

			code = ConvertSSLImages(code)

			foo.document.body.innerText = code
			foo.document.body.innerHTML = colourCode(foo.document.body.innerHTML);

			// nice looking source editor
			foo.document.body.runtimeStyle.fontFamily = "Verdana"
			foo.document.body.runtimeStyle.fontSize = "11px"
			foo.document.body.runtimeStyle.color = "#000000"
			foo.document.body.runtimeStyle.bgColor = '#FFFFFF';
			foo.document.body.runtimeStyle.text = '#000000';
			foo.document.body.runtimeStyle.background = '';
			foo.document.body.runtimeStyle.marginTop = '10px';
			foo.document.body.runtimeStyle.marginLeft = '10px';
			
			Mode = "2";
		} else {
			if (isEditingHTMLPage == "0") {
				code = "<body>"

				if (myBaseHref != "")
				{
					code = "<base href=" + myBaseHref + ">" + code
				}

				code = code + foo.document.body.innerText + "</body>"

			} else
				code = foo.document.body.innerText

			if (myStyleSheet != "")
			{
				code = "<link rel='stylesheet' href='" + myStyleSheet + "' type='text/css'>" + code
			}

			code = RevertSSLImages(code)

			foo.document.write(code);
			foo.document.close()

			foo.document.body.runtimeStyle.cssText = ""

			toolbar_full.className = "bevel3";
			toolbar_code.className = "hide";

			Mode = "1";

			if (toggleWasOn == "yes") {
				toggleBorders()
				toggleWasOn = "no"
			}
		}
	}

	function SaveHTMLPage() {
		var code = ""

		if (sourceModeView) {
			code = foo.document.body.innerText;
		}

		if (editModeView)
		{
			if (isEditingHTMLPage == "0") {

				if (useXHTML == "1") {
					code = getXHTML(document.frames('foo').document.body.innerHTML)
				} else {
					code = foo.document.body.innerHTML
				}

			} else {

				if (useXHTML == "1") {
					code = getXHTML(document.frames('foo').document.documentElement.outerHTML)
				} else {
					code = foo.document.documentElement.outerHTML
				}
			}
		}
		
		if (previewModeView)
		{
			if (isEditingHTMLPage == "0") {

				if (useXHTML == "1") {
					code = getXHTML(document.frames('previewFrame').document.body.innerHTML)
				} else {
					code = previewFrame.document.body.innerHTML
				}

			} else {

				if (useXHTML == "1") {
					code = getXHTML(document.frames('previewFrame').document.documentElement.outerHTML)
				} else {
					code = previewFrame.document.documentElement.outerHTML
				}
			}
		}

		re = /&amp;/g
		code = code.replace(re,'&')
		
		if (pathType == "1")
		{
			// replaceHref = 'href="'
			replaceImage = 'src="'

			// code = code.replace(re2,replaceHref)
			code = code.replace(re3,replaceImage)
		}

		code = ConvertSSLImages(code)

		return code;
	}

	// convert src=https to just src=http
	function ConvertSSLImages(code) {
		replaceImage = 'src=\"http://' + URL
		code = code.replace(re4,replaceImage)
		return code;
	}

	function RevertSSLImages(code) {
		replaceImage = 'src=\"' + HTTPStr + '://' + URL
		code = code.replace(re5,replaceImage)
		return code;
	}

	function button_over(eButton){
		if (eButton.style.borderBottom != "buttonhighlight 1px solid")
		{
		// eButton.style.border = "ButtonShadow  bevel 1px";
		eButton.style.borderBottom = "ButtonShadow solid 1px";
		eButton.style.borderLeft = "ButtonHighlight solid 1px";
		eButton.style.borderRight = "ButtonShadow solid 1px";
		eButton.style.borderTop = "ButtonHighlight solid 1px";
		}
	}
			
	function button_out2(eButton){
		if (eButton.style.borderBottom != "buttonhighlight 1px solid")
		{
		eButton.style.borderColor = "ButtonFace";
		}
	}
				
	function button_out(eButton){
		eButton.style.borderColor = "ButtonFace";
	}

	function char_out(eButton){
		eButton.style.borderColor = "#666666";
	}

	function button_down(eButton){
		eButton.style.borderBottom = "ButtonHighlight solid 1px";
		eButton.style.borderLeft = "ButtonShadow solid 1px";
		eButton.style.borderRight = "ButtonHighlight solid 1px";
		eButton.style.borderTop = "ButtonShadow solid 1px";
	}

	function button_up(eButton){
		eButton.style.borderBottom = "ButtonShadow solid 1px";
		eButton.style.borderLeft = "ButtonHighlight solid 1px";
		eButton.style.borderRight = "ButtonShadow solid 1px";
		eButton.style.borderTop = "ButtonHighlight solid 1px";
		eButton = null; 
	}

	function contextHilite(menu){
	    menu.runtimeStyle.backgroundColor = "Highlight";
	    if (menu.state){
	        menu.runtimeStyle.color = "GrayText";
	    } else {
	        menu.runtimeStyle.color = "HighlightText";
	    }
	}

	function contextDelite(menu){
	    menu.runtimeStyle.backgroundColor = "";
	    menu.runtimeStyle.color = "";
	}

	function toggleTick(tick, state) {

		if(tick.id.indexOf("zoom" + zoomSize + "_") > -1)
		{
			if(state == 1)
			{
				// We are over the selected zoom
				tick.src = 'de/de_images/button_tick_inverted.gif'
			}
			else
			{
				// We are over the selected zoom
				tick.src = 'de/de_images/button_tick.gif'
			}
		}
	}

	function closePopups() {
		if (imageWin) imageWin.close()
		if (propWin) propWin.close()
		if (inserttableWin) inserttableWin.close()
		if (previewWin) previewWin.close()
		if (modifytableWin) modifytableWin.close()
		if (insertFormWin) insertFormWin.close()
		if (textFieldWin) textFieldWin.close()
		if (hiddenWin) hiddenWin.close()
		if (buttonWin) buttonWin.close()
		if (checkboxWin) checkboxWin.close()
		if (radioWin) radioWin.close()
		if (linkWin) linkWin.close()
		if (emailWin) emailWin.close()
		if (anchorWin) anchorWin.close()
		if (showHelpWin) showHelpWin.close()
		if (charWin) charWin.close()
	}

	function isSelection() {
			if ((foo.document.selection.type == "Text") || (foo.document.selection.type == "Control")) {
				return true;
			} else {
				return false;
			}
	}

	function isTextSelected() {
			if (foo.document.selection.type == "Text") {
				return true;
			} else {
				return false;
			}
	}

	function selectImage(image) {
			document.execCommand("InsertImage",false,image);
	}

	function setBackgd(image) {
			foo.document.body.background = image
	}

	function ShowPreview(source) {

		var previewHTML
		if (source == 1)
		{
			previewHTML = foo.document.body.innerText
		} else {
			previewHTML = foo.document.documentElement.outerHTML
		}

		if (myStyleSheet != "")
		{
			previewHTML = "<link rel='stylesheet' href='" + myStyleSheet + "' type='text/css'>" + previewHTML
		}

		re = /<!DOCTYPE([^>])*>/
		previewHTML = previewHTML.replace(re,"")

		previewHTML = RevertSSLImages(previewHTML)

		if (myBaseHref != "")
		{
			previewHTML = "<base href=" + myBaseHref + ">" + previewHTML
		}

		previewFrame.document.write(previewHTML)
		previewFrame.document.close()
		previewFrame.focus()

	}

	function doLink() {

		if (isAllowed())
		{
			if (isSelection()) { 
				var leftPos = (screen.availWidth-400) / 2
				var topPos = (screen.availHeight-285) / 2
		 		linkWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertLink&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=285,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
			} else
				return
		}
	}

	var imageEdit = false
	function doImage() {
		if (isAllowed())
		{

			if (isImageSelected()) {	 
				imageEdit = true
			} else {
				imageEdit = false
			}
		
			var leftPos = (screen.availWidth-770) / 2
			var topPos = (screen.availHeight-660) / 2 
			imageWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertImage&DEP1='+deveditPath1+'&DEP='+deveditPath + '&imgDir=' + imageDir + '&wi=' + HideWebImage + '&tn=' + showThumbnails + '&du=' + disableImageUploading + '&dd=' + disableImageDeleting + '&dt=' + isEditingHTMLPage,'','width=755,height=630,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);

		}
	}

	var flashEdit = false
	function doFlash() {
		if (isAllowed())
		{

			if (isFlashSelected()) {
				flashEdit = true
			} else {
				flashEdit = false
			}

			var leftPos = (screen.availWidth-770) / 2
			var topPos = (screen.availHeight-660) / 2 
			imageWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertFlash&DEP1='+deveditPath1+'&DEP='+deveditPath +'&flashDir=' + flashDir + '&wi=' + HideWebFlash + '&tn=' + showFlashThumbnails + '&du=' + disableFlashUploading + '&dd=' + disableFlashDeleting + '&dt=' + isEditingHTMLPage,'','width=755,height=630,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);

		}
	}

	function ModifyProperties() {
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-400) / 2
		var topPos = (screen.availHeight-410) / 2 
	 	propWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=PageProperties&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=410,scrollbars=no,resizable=yes,titlebar=0,top=' + topPos + ',left=' + leftPos);
		
		}
	}

	function ShowInsertTable() {
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-450) / 2
		var topPos = (screen.availHeight-295) / 2 
 		inserttableWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertTable&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=450,height=293,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);

		}
	}

	function ModifyTable() {
		if (isAllowed())
		{

		if (isTableSelected() || isCursorInTableCell()) {
			var leftPos = (screen.availWidth-450) / 2
			var topPos = (screen.availHeight-293) / 2 
	 		modifytableWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyTable&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=450,height=262,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function ModifyCell() {
		if (isAllowed())
		{

		if (isCursorInTableCell()) {
			var leftPos = (screen.availWidth-400) / 2
			var topPos = (screen.availHeight-230) / 2 
	 		modifytableWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyCell&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=234,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function modifyForm() {
		if (isAllowed)
		{

		if (isCursorInForm()) {
			var leftPos = (screen.availWidth-500) / 2
			var topPos = (screen.availHeight-300) / 2 
	 		modifyFormWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyForm&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=223,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function insertForm() {
		if (isAllowed())
		{
			var leftPos = (screen.availWidth-400) / 2
			var topPos = (screen.availHeight-223) / 2 
	 		insertFormWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertForm&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=223,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}
	}

	function doCustomInserts() {
		if (isAllowed())
		{
			var leftPos = (screen.availWidth-450) / 2
			var topPos = (screen.availHeight-297) / 2 
	 		customInsertWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=CustomInsert&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=450,height=297,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}
	}
	function doAnchor() {
			if (isAllowed())
			{

			var leftPos = (screen.availWidth-400) / 2
			var topPos = (screen.availHeight-162) / 2 
		
			if ((foo.document.selection.type == "Control") && (foo.document.selection.createRange()(0).tagName == "A") && (foo.document.selection.createRange()(0).href == ""))
			{
				anchorWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyAnchor&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=162,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
			} else {
	 			anchorWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertAnchor&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=162,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
			}

			}
	}

	function doEmail() {

		if (isAllowed())
		{
			if (isSelection()) { 
				var leftPos = (screen.availWidth-400) / 2
				var topPos = (screen.availHeight-223) / 2

	 			emailWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertEmail&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=223,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
			} else
				return
		}
	}


	popupColorWin = HTTPStr + '://' + URL + ScriptName + '?ToDo=MoreColors&DEP1='+deveditPath1+'&DEP='+deveditPath
	function doMoreColors() {
		var leftPos = (screen.availWidth-420) / 2
		var topPos = (screen.availHeight-400) / 2
		colorWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=MoreColors&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=420,height=370,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
	}

	function ShowFindDialog() {
		if (isAllowed())
		{
		showModelessDialog(HTTPStr + "://" + URL + ScriptName + "?ToDo=FindReplace&DEP1='+deveditPath1+'&DEP="+deveditPath, foo, "dialogWidth:385px; dialogHeight:165px; scroll:no; status:no; help:no;" );
		}
	}
	
	function spellCheck(){
		var leftPos = (screen.availWidth-300) / 2
		var topPos = (screen.availHeight-220) / 2 
		arr = getWords();
	    rng = getRange();
	    spellcheckWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=SpellCheck&DEP1='+deveditPath1+'&DEP='+deveditPath, "spellwin", "width=300,height=220,scrollbars=no, top=" + topPos + ",left=" + leftPos);
	}


	function doTextField() {
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-400) / 2
		var topPos = (screen.availHeight-230) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if ((oControlRange(0).type.toUpperCase() == "TEXT") || (oControlRange(0).type.toUpperCase() == "PASSWORD")) {
					selectedTextField = foo.document.selection.createRange()(0);
					textFieldWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyTextField&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=230,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			textFieldWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertTextField&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=230,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function doHidden() {
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-350) / 2
		var topPos = (screen.availHeight-192) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if (oControlRange(0).type.toUpperCase() == "HIDDEN") {
					selectedHidden = foo.document.selection.createRange()(0);
					hiddenWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyHidden&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=350,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			hiddenWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertHidden&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=350,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function doTextArea() {
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-400) / 2
		var topPos = (screen.availHeight-230) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "TEXTAREA") {
					selectedTextArea = foo.document.selection.createRange()(0);
					textFieldWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyTextArea&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=230,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				return true;
			}	
		} else {
			textFieldWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertTextArea&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=230,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function doButton() {
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-500) / 2
		var topPos = (screen.availHeight-300) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if ((oControlRange(0).type.toUpperCase() == "RESET") || (oControlRange(0).type.toUpperCase() == "SUBMIT") || (oControlRange(0).type.toUpperCase() == "BUTTON")) {
					selectedButton = foo.document.selection.createRange()(0);
					buttonWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyButton&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			buttonWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertButton&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}
	function dochars(rte) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}	
	
	try{
		oRTE.focus();

	} catch (e) {
	}


			var leftPos = (screen.availWidth-480) / 2
			var topPos = (screen.availHeight-420) / 2 

popUpWin(includesPath + 'EditorJS/popups.htm', 'InsertTable', 380,350, '','');
//	 		charWin = window.open(HTTPStr + '://' + URL + ScriptName + //'?ToDo=Chars&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=420,height=400,scrollbars=no,resizable=no,titl//ebar=0,top=' + topPos + ',left=' + leftPos);
		
	}


	function doHelp() {


			var leftPos = (screen.availWidth-480) / 2
			var topPos = (screen.availHeight-420) / 2 

popUpWin(includesPath + 'EditorJS/ayudaeditor.aspx', 'Help', 480,450,',scrollbars=yes,','');
		
	}

	function doCheckbox() {
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-400) / 2
		var topPos = (screen.availHeight-192) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if (oControlRange(0).type.toUpperCase() == "CHECKBOX") {
					selectedCheckbox = foo.document.selection.createRange()(0);
					checkboxWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyCheckbox&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			checkboxWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertCheckbox&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function doSelect() 
		{
			var leftPos = (screen.availWidth-520) / 2
			var topPos = (screen.availHeight-340) / 2 

			if (foo.document.selection.type == "Control") 
				{
				var oControlRange = foo.document.selection.createRange();
				if (oControlRange(0).tagName.toUpperCase() == "SELECT") 
					{
					selectedSelectBox = foo.document.selection.createRange()(0);
					selectBoxWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifySelect&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=520,height=340,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
					return true;
					}
				}
			else
				{
				selectBoxWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertSelect&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=520,height=340,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
	
		}

	function doRadio() {
		if (isAllowed()) {

		var leftPos = (screen.availWidth-400) / 2
		var topPos = (screen.availHeight-192) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if (oControlRange(0).type.toUpperCase() == "RADIO") {
					selectedRadio = foo.document.selection.createRange()(0);
					radioWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=ModifyRadio&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			radioWin = window.open(HTTPStr + '://' + URL + ScriptName + '?ToDo=InsertRadio&DEP1='+deveditPath1+'&DEP='+deveditPath,'','width=400,height=192,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

	function cleanCode() {
		if (confirm(sTxtClean)){

			var borderwason

			if (borderShown == "yes") {
			 	toggleBorders()
			 	borderwason = true
			}

			foo.document.write(doCleanCode(foo.document.body.innerHTML));
			foo.document.close()

			if (borderwason) {
			 	toggleBorders()
			}
		}
	}

// Colorize Code in Source Mode
function colourCode(code) {

	htmlTag = /(&lt;([\s\S]*?)&gt;)/gi
	tableTag = /(&lt;(table|tbody|th|tr|td|\/table|\/tbody|\/th|\/tr|\/td)([\s\S]*?)&gt;)/gi
	commentTag = /(&lt;!--([\s\S]*?)&gt;)/gi
	imageTag = /(&lt;img([\s\S]*?)&gt;)/gi
	objectTag = /(&lt;(object|\/object)([\s\S]*?)&gt;)/gi
	linkTag = /(&lt;(a|\/a)([\s\S]*?)&gt;)/gi
	scriptTag = /(&lt;(script|\/script)([\s\S]*?)&gt;)/gi

	code = code.replace(htmlTag,"<font color=#000080>$1</font>")
	code = code.replace(tableTag,"<font color=#008080>$1</font>")
	code = code.replace(commentTag,"<font color=#808080>$1</font>")
	code = code.replace(imageTag,"<font color=#800080>$1</font>")
	code = code.replace(objectTag,"<font color=#840000>$1</font>")
	code = code.replace(linkTag,"<font color=#008000>$1</font>")
	code = code.replace(scriptTag,"<font color=#800000>$1</font>")

	return code;
}
// End colorize

function Previa(rte, buttons) {
if (document.getElementById("chkSrc" + rte).checked) document.getElementById("chkSrc" + rte).click();


 //contributed by Bob Hutzel (thanks Bob!)
 var oHdnField = document.getElementById('hdn' + rte);

 //----------if (document.getElementById("chkSrcPrv" + rte).checked) {
  //we are checking the box
  if (buttons) {
   showHideElement("Buttons1_" + rte, "hide");
   showHideElement("Buttons2_" + rte, "hide");
  }
  setHiddenVal(rte);
  var oRTE = document.getElementById(rte).contentWindow.document;

  var htmlSrc = oRTE.createTextNode(oHdnField.value);
   oRTE.body.innerHTML = "";
   oRTE.body.appendChild(htmlSrc);
   aux=oRTE.body.innerText;
   texto=aux;

   dlgPreview(rte,'preview',texto);


//----------- } else {
  //we are unchecking the box
  if (buttons) {
   showHideElement("Buttons1_" + rte, "show");
   showHideElement("Buttons2_" + rte, "show");
  }
  if (document.all) {
   //fix for IE
   var output = escape(frames[rte].document.body.innerText);
   output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
   output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
   frames[rte].document.body.innerHTML = unescape(output);
  } else {
   var oRTE = document.getElementById(rte).contentWindow.document;
   var htmlSrc = oRTE.body.ownerDocument.createRange();
   htmlSrc.selectNodeContents(oRTE.body);
   oRTE.body.innerHTML = htmlSrc.toString();
  }

 //}
	

}


function dlgPreview(rte, command,texto) {
document.getElementById('texto').value=texto;

 parent.command = command;
 currentRTE = rte;

 InsertLink = popUpWin(includesPath + 'EditorJS/preview.htm', 'InsertLink', 700, 580, 
',scrollbars=yes,','');



}
function setPreview(linkText) {
 //set link text value in insert link dialog
 try {

window.InsertLink.document.linkForm.outerHTML = linkText;


 } catch (e) {
  //may take some time to create dialog window.
  //Keep looping until able to set.
  setTimeout("setPreview('" + linkText + "');", 10);
 }
}



function megabucle (rte){
var cad;
cad='';
var anterior;
var texto;
var i;
var error,div,level,table,tr,td,b,strong,errortable;
div=0;table=0;tr=0;td=0;b=0;strong=0;
errortable=0;
errorencabezado=0;
var abrir;
error='';
abrir=0;

var j,k,h;
j=0;
k=0;
h=0;
elh=0;
var l,p,elh,div,leveldiv,errorencabezado,leveltabla,levelfila,nivelt,nivelt2,nivelhc;
nivelt=new Array(20);
nivelt2=new Array(20);
nivelh=new Array(20);
nivelhc=new Array(20);
leveltabla=0;
leveldiv=0;
levelfila=0;
div=0;
p=0;

for (j=0;j<20;j++) nivelt[j]=0;
for (k=0;k<20;k++) nivelt2[k]=0;
for (h=0;h<20;h++) nivelh[h]=0;
for (l=0;l<20;l++) nivelhc[l]=0;

texto=frames[rte].document.body.innerHTML;

for (i=0;i<texto.length;i++) {
if (abrir==1) { cad=cad+'<';abrir=0;}
if (texto.substring(i,i+1)==' ' || texto.substring(i,i+1)=='>' || 
texto.substring(i,i+1)=='<' ) {

if(texto.substring(i,i+1)=='<') abrir=1;

/**/
if (cad.toUpperCase()=='<DIV') {div=div+1;leveldiv = leveldiv+1;}
if (cad.toUpperCase()=='</DIV') {div=div-1;leveldiv = leveldiv-1;}


if (cad.toUpperCase()=='<P') {p=p+1;}
if (cad.toUpperCase()=='</P') {p=p-1;}

if (cad.substring(0,2).toUpperCase()=='<H') {elh=cad.substring(3,2);
if (nivelh[leveldiv]>elh) errorencabezado=1;
nivelhc[leveldiv]=nivelhc[leveldiv]+1;
if (nivelh[leveldiv]<elh-1) errorencabezado=1;
nivelh[leveldiv]=elh;
}

if (cad.substring(0,3).toUpperCase()=='</H') {nivelhc[leveldiv]=nivelhc[leveldiv]-1;}


if (cad.toUpperCase()=='<TABLE') {table=table+1;leveltabla = leveltabla+1;}


if (cad.toUpperCase()=='<TR') {tr=tr+1;nivelt[leveltabla]=nivelt[leveltabla]+1;levelfila=levelfila+1;}
if (cad.toUpperCase()=='<TD') {td=td+1;nivelt2[levelfila]=nivelt2[levelfila]+1;}
if (cad.toUpperCase()=='</TD') {td=td-1;nivelt2[levelfila]=nivelt2[levelfila]-1;}


if (cad.toUpperCase()=='</TR') {tr=tr-1;nivelt[leveltabla]=nivelt[leveltabla]-1;levelfila=levelfila-1;}
if (cad.toUpperCase()=='</TABLE') {table=table-1;leveltabla = leveltabla-1; 
for (k=0;k<20;k++) {if (nivelt2[k]!=0) errortable=1;nivelt2[k]=0;}
}


if(tr!=0 && table<=0) errortable=1;
if(td!=0 && table<=0) errortable=1;
/**/

cad='';
}
else

cad =cad + texto.substring(i,i+1);
}

for (j=0;j<20;j++) if (nivelt[j]!=0) errortable=1;
for (l=0;l<20;l++) if (nivelhc[l]!=0) errorencabezado=1;

//for (h=0;h<20;h++) if (nivelh[h]!=1) errorencabezado=1;
if(div>0) error = error + ' paneles ';
if(errorencabezado>0) error = error + ' encabezados ';
if((table>0 || tr>0 )||errortable==1) error=error+' tablas ';
if(p>0) error=error+' etiquetas P ';
if (error!='') alert('Se detectaron malas construcciones en los siguientes elementos:' + error );
}

/********/
function setCaretTo (control,i) {
if (control.createTextRange) {
var range = control.createTextRange();
range.collapse(true);
range.select();
}
else if (control.setSelectionRange) {
control.focus();
control.setSelectionRange(1, 1);
}

}

