// Name: Special commands file
// Info: Contain special commands(these commands don't directly support by standard editor component) for Gecko browsers.


function documentPreprocessing(){
	var t = E._frame.getElementsByTagName("td");
	for (var i = 0; i < t.length; i++) {
		x = t[i];
		if (x.innerHTML == undefined || x.innerHTML == "" || x.innerHTML.toLowerCase() == "<br>" || x.innerHTML.toLowerCase() == "<br/>"){
			x.innerHTML = "&nbsp;";
		}
	}	
}

// Save command
var Save = function()
{
	this.Name = 'save' ;
};

Save.prototype.execute = function(isUpdate)
{
	if (loading_in_progress && !isUpdate){
		parent.document.getElementById(E.InstanceName+"_html").value = parent.document.getElementById(E.InstanceName+"_input").value;
		parent.document.getElementById(E.InstanceName+"_save").click();
		loading_in_progress = false;
		return;
	}

	aed = E._frame;
	removeSafariStyles();
	var code = "";
	if (E.mode=="source") {
		var html = aed.body.innerHTML;
		html = html.replace(/<br\/?>/gi,"\n");
		html = html.replace(/<br\/?>/gi,"\n");
		html = html.replace(/<[^>]+>/g,"");

		html = html.replace(/&lt;/g,"<");
		html = html.replace(/&gt;/g,">");
		code = removeStyle(html);
	} else {
		E.commands.getCommand("Paragraph").hideChar();
		documentPreprocessing();
		code = E.HTMLTags[1]+removeWrap(img2embed(aed.documentElement.innerHTML))+E.HTMLTags[3];
		E.commands.getCommand("Paragraph").showChar();
		code = removeBase(code);
		code = removeSpellSpan(code);
	    code = code.replace(/de_href=\"[^\"]+\"/gi, "");

	}

//?
	if (deEngine)code = deEngine.restore(code);
	if (useXHTML==1) {
		code = getXHTML(code);
	}

	re = /&amp;/g;
	code = code.replace(re,'&');

	if (pathType == "1") {
		replaceImage = 'src="';
		code = code.replace(re3,replaceImage);
	}

	if (E.mode == "edit") {
		code = convert_param_tag_to_xhtml(unescape_href(code));
	}

	code = ConvertSSLImages(code);
	if (E.mode=="source") {
		code = _de_save_special_char2(code);
	} else {
		code = _de_save_special_char(code);
	}

	parent.document.getElementById(E.InstanceName+"_html2").value = code;

	if (docType!=1 && E.mode=="edit") { // for snippet mode
		h = code.match(BodyContents);
		code = h[2];
	}
	code = formatSaveCode(code);

	var donotformat = 0;
// the following line seems to be reformatting snippets when you have editable regions
// finding the doctype seems to fix this problem
// fulvio
//	if (E.isbegin && E.isend) {
	if (E.isbegin && E.isend && docType==1) {
		code = replace_editable(code);
		donotformat=1;
	}
	
	parent.document.getElementById(E.InstanceName+"_html").value = code;
	if (isUpdate!=="no") {
		parent.document.getElementById(E.InstanceName+"_save").click();
	}
}

Save.prototype.getMode = function()
{
	return OFF;
};
// ***** end of Save command *****

// Paste as Plain Text
var PasteText = function()
{
	this.Name = "PasteText";
};

PasteText.prototype.execute = function()
{
/*

	var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
	} catch (e){
		alert(security_error);
	}
	if (!clip) {
		return;
	}
	var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
	if (!trans) {
		return;
	}
	trans.addDataFlavor('text/unicode');
	clip.getData(trans,clip.kGlobalClipboard);
	var str = new Object();
	var len = new Object();
	try {
		trans.getTransferData('text/unicode',str,len);
	}
	catch(error) { return; }
	if (str) {
		if (Components.interfaces.nsISupportsWString) {
			str=str.value.QueryInterface(Components.interfaces.nsISupportsWString);
		} else if (Components.interfaces.nsISupportsString) {
			str=str.value.QueryInterface(Components.interfaces.nsISupportsString);
		} else {
			str = null;
		}
	}

	if (str) {
		var code = str.data.substring(0,len.value / 2);
	}
*/
	var new_frame = parent.document.createElement("IFRAME");
	new_frame.style.visibility = "hidden";
	new_frame.style.position = "absolute";
	new_frame.style.top = "0px";
	new_frame.style.left = "0px";
	new_frame.id = "temp_frame_for_paste";
	parent.document.body.appendChild(new_frame);
	var frame = parent.document.getElementById("temp_frame_for_paste").contentDocument;
	frame.designMode = "on";
	frame.open();
	frame.write("");
	frame.close();
	try{
		frame.execCommand("Paste", false, null );
	} catch (ee){
		if (confirm(security_error_allow)) {
			window.ShortCutKeys.pop();
		}
	}	
	c = frame.body.innerHTML;
	c = c.replace(/(\n)/gi,"");
	c = c.replace(/(\r)/gi,"");
	c = c.replace(/<br\/?>/gi,"\n");
	c = c.replace(/<\/p>/g,"\n");
	c = c.replace(/&lt;/g,"<");
	c = c.replace(/&gt;/g,">");
	c = c.replace(/&nbsp;/g," ");
	c = c.replace(/<[^>]+>/g,"");
	code = c.replace( /\n/g, '<br/>' ) ;
	E._inserthtml( code ) ;
	buffer[E.mode].saveHistory();
};

PasteText.prototype.getMode = function()
{
	try
	{
		if (!E._frame.queryCommandEnabled("paste")) {
			return DISABLED ;
		} else {
			return E._frame.queryCommandState( "paste" ) ? ON : OFF ;
		}
	}
	catch (e) {
		return OFF ;
	}
};

// Source mode class
var SourceCommand = function()
{
	this.Name = "SourceMode";
};

old_body_tag = null;
SourceCommand.prototype.getMode = function()
{
};

SourceCommand.prototype.execute = function()
{
	removeSafariStyles();
	var e = E._frame;
	clearUrls();

	E.commands.getCommand("Spellcheck").off();
	E.commands.getCommand("Paragraph").hideChar();
	
	ToolbarSets.SwitchToolbarSet(toolbarmode);

	var fr = document.getElementById(E.InstanceName+"_frame");
	if (E.showborders==ON) {
		E.commands.getCommand("Showborders").reset(true);
	}

	document.getElementById("ePath").style.display="none";

	if (fr.style.display=="none") {
		var Ifr = document.getElementById(E.InstanceName+"_preview");
		Ifr.style.display="none";
		fr.style.display="block";
		try {
			aed.designMode="on";
		} catch(e){}
	}

	if (E.mode=="edit") {
		E.saveBodyAttribute();
		var body_style="<style>body{font-family:monospace;font-size:11px;color:#000000;background-color:#FFFFFF;margin-top:10px;margin-left:10px;text-align: left;}</style>";

		var content = E._frame.documentElement.innerHTML;
		if (docType==1){ // DE_DOC_TYPE_HTML_PAGE
			var c =  content;
			if (browser.isFireFox1_5){
				add_title="";
				if (c.indexOf("<title>")==-1 && E._frame.title) {
					add_title = "<title>"+E._frame.title+"</title>";
				}
				var newhtml = c.match(HeadContents);
				c = newhtml[1]+newhtml[2].replace(/\n+/g,"\n")+add_title+newhtml[3];
			}
			c = E.HTMLTags[1] + c + E.HTMLTags[3];
			if (useXHTML==1) {
				iHTML = getXHTML(c);
			} else {
				iHTML = c;
			}
		} else {
			var c = E.HTMLTags[1] + content + E.HTMLTags[3];
			E.part = c.match(BodyContents);
			if (useXHTML==1) {
				iHTML = getXHTML(e.body.innerHTML);
			} else {
				iHTML = e.body.innerHTML;
			}
		}
		re = /&amp;/g;
		iHTML = iHTML.replace(re,'&');
		iHTML = iHTML.replace(/&/g,'&amp;');
		iHTML = deEngine.restore(iHTML);
		
		// switch to source view
		iHTML = removeBlock(iHTML);

		iHTML = removeBase(iHTML);
		iHTML = img2embed(iHTML);
		iHTML = convert_param_tag_to_xhtml(iHTML);
		iHTML = unescape_href(iHTML);
		iHTML = iHTML.replace(/</g,"&lt;");
		iHTML = iHTML.replace(/>/g,"&gt;");
		iHTML = iHTML.replace(/&lt;br&gt;/gi,"&lt;br/&gt;");
		iHTML = iHTML.replace(/\n/g,"<br/>");
		iHTML = iHTML.replace(/\r/g,"");
		iHTML = _de_replace_bookmark(iHTML);
		iHTML = iHTML.replace(/\n/g,"");
		iHTML = iHTML.replace(/\x09/g,"");

		e.body.innerHTML = iHTML;
		var c=e.body.innerHTML;
		c = _de_parse_special_char(c);
		c = c.replace(/^(<br>)+/g,"");

		// addEditTag
		html =  addEditTag(colourCode(formatCode(c))); // body_style +
		e.body.innerHTML = html;
		
		e.body.style.fontFamily = "monospace";
		e.body.style.fontSize = "12px";
		e.body.style.lineHeight = 1;
		e.body.style.color = "#000000";
		e.body.style.text = '#000000';
		e.body.style.background = '#FFFFFF';
		e.body.style.marginTop = '10px';
		e.body.style.marginLeft = '10px';
		e.body.style.textAlign = 'left';
	}
	E.mode="source";
	E.lastmode="source";
	buffer["source"].devhistory.position = 0;
	ToolbarSets.SwitchToolbarSet("_source");
	E.Focus();
};

// Edit mode
var EditCommand = function()
{
	this.Name = "EditMode";
};

EditCommand.prototype.getMode = function()
{
};

EditCommand.prototype.execute = function()
{

	var e = E._frame;
	var fr = document.getElementById(E.InstanceName+"_frame");

	document.getElementById("ePath").style.display="block";

	if (fr.style.display=="none") {
		var Ifr = document.getElementById(E.InstanceName+"_preview");
		fr.style.display="block";
		try {
			aed.designMode="on";
		} catch(e){}
		Ifr.style.display="none";
	}

	var headTag = /<head\s*>/i;

	if (E.mode=="source") {
		E.restoreBodyAttribute();

		var html = e.body.innerHTML;

		if (browser.isFireFox1_5) {
			html = html.replace(/<br\/?>/gi,"\n");
		} else {
			html = html.replace(/<br\/?>/gi,"\n");
		}
		html = html.replace(/<[^>]+>/g,"");
		html = html.replace(/&lt;/g,"<");
		html = html.replace(/&gt;/g,">");
	
		var temp = html.match(/(<a[^>]+\/>)/g);
		for (var i in temp){
			html = html.replace(temp[i], temp[i].replace("/>","></a>"));
		}

		var html_check = html.search(/<html\s*>/i);
		var head_check = html.search(headTag);
		var body_check = html.search(/<body\s*>/i);

		if(html.search(/<head\s*>/i)==-1 || html.search(/<html\s*>/i)==-1 || html.search(/<body\s*>/i)==-1){
			html = "<html><head></head><body>"+html+"</body></html>";
		}

		var addbase="";
		if (docType==1){ // DE_DOC_TYPE_HTML_PAGE
			html = html.toString().replace(headTag,'<head>'+addbase+'<link href="'+E.skinPath+'borders.css" type="text/css" rel="stylesheet">');
		} else{
			html = addbase + E.part[1]+removeStyle(html)+E.part[3];
		}
		var rr = new RegExp("&nbsp;","gi");
		html = html.replace(rr," ");
		html = html.replace(/&amp;/g,"&");
		html = deEngine.preserve(html);
		html = addBase(html);
		html = addBlock(html);
		E.changeHTML(embed2img(removeEditTag(html)));
		correctUrls();
	}
    
	E.mode="edit";	E.lastmode="edit";
	if (E.showborders==ON){
		E.commands.getCommand("Showborders").set(false);
	} else {
		E.commands.getCommand("Showborders").reset(false);
	}
	E.commands.getCommand("Paragraph").showChar();
	ToolbarSets.SwitchToolbarSet(toolbarmode);
	E.doStyles();
	if (E.toolbaritems.GetItem('Styles')){
		E.toolbaritems.GetItem('Styles').Redraw();
	}
	checkImgLoaded();
	E.Focus();
};

function removeStyle(code)
{
	styleTag = /(BODY\{font-family:monospace;font-size:11px;color:#000000;background:#FFFFFF;margin-top:10px;margin-left:10px;text-align: left;\})/gi;
	code = code.replace(styleTag,"");
	return code;
};

// Preview mode class
var PreviewCommand = function()
{
	this.Name = "PreviewMode";
};

PreviewCommand.prototype.getMode = function()
{
};

PreviewCommand.prototype.execute = function()
{
	ToolbarSets.SwitchToolbarSet(toolbarmode);

	var aed = E._frame;
	document.getElementById("ePath").style.display="none";
	var e = document.getElementById(E.InstanceName+"_frame");
	if (E.showborders==ON) {
		E.commands.getCommand("Showborders").reset();
	}
	E.commands.getCommand("Paragraph").hideChar();

	var Ifr = document.getElementById(E.InstanceName+"_preview");
	e.style.display="none";
	Ifr.style.display="block";

	if (E.mode=="edit"){
		E.saveBodyAttribute();
	}

	var addbase = "";
	if (E.mode=="source"){
		var html = aed.body.ownerDocument.createRange();
		html.selectNodeContents(aed.body);
		var c = removeStyle(html.toString());
		if (myBaseHref && E.useBase) {
			addbase += '<base href="'+myBaseHref+'" />';
		}	
		c = addbase + c ;
		if (docType!=1){
			var bodyhtml = removeStyle(c);
			c = E.part[1] + bodyhtml + E.part[3];
		}
		c = img2embed22(c);
	} else {
		var c = "<html>" + E._frame.documentElement.innerHTML+"</html>";
		c = img2embed22(img2embed2(c));
		c = removeBlock(c);
	}

	c = c.replace('<link href="'+E.skinPath+'borders.css" type="text/css" rel="stylesheet">','');
	E.lastmode="preview";
	E.changeHTML(c, Ifr.contentDocument,"preview");
	checkImgLoaded(Ifr.contentDocument);
	ToolbarSets.SwitchToolbarSet("_preview");
	// disable showborders style
	if(Ifr.contentDocument.getElementById(E.InstanceName+"bs"))Ifr.contentDocument.getElementById(E.InstanceName+"bs").disabled = true;
};


function clearCode(code)
{
	code = code.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, "<$1$3");
	code = code.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, "<$1$3");
	code = code.replace(/<\\?\??xml[^>]>/gi, "");
	code = code.replace(/<\/?\w+:[^>]*>/gi, "");
	code = code.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi,"");
	code = code.replace(/<span([^>])*>(&nbsp;)*\s*<\/span>/gi,"");
	code = code.replace(/<b([^>])*>(&nbsp;)*\s*<\/b>/gi,"");	
	code = code.replace(/[”“]/gi,'"');
	code = code.replace(/[‘’]/gi,"'");
	code = code.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	code = code.replace( /\s*mso-[^:]+:[^;"]+;?/gi, "" ) ;
	code = code.replace(/<\\?\?xml[^>]*>/gi, "") ;
	code =  code.replace( /\s*style="\s*"/gi, '' ) ;
	code = code.replace( /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;' ) ;
	code = code.replace( /<SPAN\s*[^>]*><\/SPAN>/gi, '' ) ;

	code = code.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
	code = code.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
	code = code.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;	
	return code;
}

// Clear Code command
var ClearCodeCommand = function()
{
	this.Name = 'ClearCode';
};

ClearCodeCommand.prototype.execute = function()
{
	if (confirm("Are you sure you want to clean your HTML code?")) {
		code = E._frame.body.innerHTML;
		code = clearCode(code);
		E._frame.body.innerHTML = code;
		E._window.focus();
	}
};

ClearCodeCommand.prototype.getMode = function(){
	if (E.isbegin && E.isend) {
		return DISABLED;
	}
	return OFF;
};


// Fullscreen class
var FullscreenCommand = function()
{
	this.Name = 'Fullscreen' ;
	e = parent.document.getElementById(E.InstanceName+"main");
	this.oldw = e.style.width;
	this.oldh = e.style.height;
	this.style = null;
	this.scrollXPos = 0;
	this.scrollXPos = 0;
};

FullscreenCommand.prototype.changemode = function(str2, par, val) {
	var str = str2;
	idx=str.indexOf(par+"=",1);
	idx2=str.indexOf("&",idx+1);
	if ((idx>=0)&&(idx2==-1)){
		idx2=str.length;
	}
	if (idx!=-1){
		str = str.substring(0,idx+par.length+1) + val + str.substring(idx2,str.length);
	} else {
		if (str.indexOf("?")!=-1){
			str = str + "&" + par + "=" + val;
		} else {
			str = str + "?"+par + "=" + val;
		}
	}
	return str;
};

function Resize_DE_Editor(){
	e = parent.document.getElementById(E.InstanceName+"main");
	w = parent.innerWidth;
	h = parent.innerHeight;
	e.style.width = w+"px";
	e.style.height = h+"px";
	document.getElementById("de_body").style.height=h+"px";
}

FullscreenCommand.prototype.execute = function(){

	e = parent.document.getElementById(E.InstanceName+"main");
	e1 = document.getElementById(E.InstanceName+"main1");

	if (E.fullscreen==OFF) {
		parent.addEventListener( 'resize', Resize_DE_Editor, true ) ;
		
		if (parent.document.compatMode=='CSS1Compat'){
			sL = parent.document.documentElement.scrollLeft;
			sT = parent.document.documentElement.scrollTop;
		} else {
			sL = parent.document.body.scrollLeft;
			sT = parent.document.body.scrollTop;
		}
		this.scrollXPos = sL;
		this.scrollYPos = sT;
		w = parent.innerWidth;
		h = parent.innerHeight 
		e1.style.height = "100%";
		e.style.position = 'absolute';
		e.style.left = 0;
		e.style.top = 0;
		e.style.width = w+"px";
		e.style.height = h+"px";

//		parent.scrollTo(0,0);
		document.getElementById("de_body").style.height=h+"px";
		document.getElementById(E.InstanceName+"_frame").style.height = "100%";
		E.neww = w;
		E.newh = h;
		E.fullscreen=ON;
		
		// hide sidebar
		var p = parent.document.documentElement;
		var bs = parent.document.body.style;
		this.style = SaveStyle(parent.document.body);
		bs.overflow = "hidden";
		parent.scrollTo(0,0);
		bs.width="0px";
		bs.height="0px";
		E.href = this.changemode(E.href,"fullscreen","on");
	} else {
		parent.removeEventListener( "resize", Resize_DE_Editor, true ) ;
		e1.style.height = "100%";
		e.style.position = '';
		e.style.left = 0;
		e.style.top = 0;
		e.style.width = E.oldw;
		e.style.height = E.oldh;
		document.getElementById("de_body").style.height=(E.oldh-5)+"px";
		E.neww = E.oldw;
		E.newh = E.oldh;
		E.fullscreen=OFF;
		RestoreStyle(parent.document.body,this.style);
		E.href = this.changemode(E.href,"fullscreen","off");
		parent.scrollTo(this.scrollXPos,this.scrollYPos);
	}

	try{
		E._frame.designMode = "On";
	} catch(e){}
	E.Focus();
};

FullscreenCommand.prototype.getMode = function()
{
	if (E.fullscreen==ON) {
		return ON;
	} else {
		return OFF;
	}
};

SaveStyle = function(o)
{
	var oSavedStyles = new Object() ;

	var expDate = new Date;
	expDate.setTime (expDate.getTime() + (24*60*60*1000));
	
	if ( o.className.length > 0 )
	{
		oSavedStyles.Class = o.className ;
		o.className = '' ;
	}
	SetCookie("savedClass",oSavedStyles.Class,expDate);

	var sInlineStyle = o.getAttribute( 'style' ) ;

	if ( sInlineStyle && sInlineStyle.length > 0 )
	{
		oSavedStyles.Inline = sInlineStyle ;
		o.setAttribute( 'style', '', 0 ) ;
	}
	SetCookie("savedStyle",oSavedStyles.InLine,expDate);

	return oSavedStyles ;
}

RestoreStyle = function( o, savedStyles )
{
	o.className = GetCookie("savedClass") || '' ;
	if ( GetCookie("savedStyle") )
		o.setAttribute( 'style', GetCookie("savedStyle"), 0 ) ;
	else
		o.removeAttribute( 'style', 0 ) ;
}


// InsertTextBox class
var InsertTextBox = function()
{
	this.Name = 'Inserttextboxe';
};

InsertTextBox.prototype.execute = function()
{
	E._inserthtml("<table id=de_textBox style='position:absolute;'><tr><td>Text box</td></tr></table>");
	textBox = E._frame.getElementById("de_textBox");
	textBox.removeAttribute("id");
	E._window.focus();
};

InsertTextBox.prototype.getMode = function()
{
	return OFF;
};

// Show borders
var ShowBordersCommand = function()
{
	this.Name = 'Showborders' ;
};

// function for set style
var el = new Object;
el.id 		= [];
el.className= [];

function setClassForInput()
{
	var elements = E._frame.getElementsByTagName("INPUT");
	for (var i = 0; i < elements.length; i++) {
		if (elements.item(i).type.toUpperCase()!="HIDDEN") {
			continue;
		}
		el.id[el.id.length] = elements.item(i);
		el.className[el.className.length] = elements.item(i).getAttribute("className");
		elements.item(i).className = "de_style_input";
	}
}

function setClassForAnchor()
{
	var elements = E._frame.getElementsByTagName("A");
	for (var i = 0; i < elements.length; i++) {
		if (!elements.item(i).name) {
			continue;
		}
		el.id[el.id.length] = elements.item(i);
		el.className[el.className.length] = elements.item(i).getAttribute("className");
		elements.item(i).className = "de_style_anchor";
	}
}


function resetClassForAll()
{
	for (var i = 0; i < el.id.length; i++) {
		el.id[i].className = el.className[i];
		if (!el.className[i]) {
			el.id[i].removeAttribute("class");
		}
	}
	el.id.length=0;
	el.className.length=0;
}

ShowBordersCommand.prototype.switchCSS = function(on)
{
	try{
	E._frame.getElementById(E.InstanceName+"bs").disabled = on;
	} catch(e) {}
};

ShowBordersCommand.prototype.set = function()
{
	try{
		var sheets = E._frame.styleSheets;
		if (el.id.length>0) {
			resetClassForAll();
		}
		setClassForInput();
		setClassForAnchor();
		this.switchCSS(false);
	} catch(e) {}
};

ShowBordersCommand.prototype.reset = function()
{
	try{
		var sheets = E._frame.styleSheets;
		this.switchCSS(true);
		resetClassForAll();
	} catch(e) {}
};

ShowBordersCommand.prototype.execute = function(ignore)
{
	if (E.showborders==OFF){
		if (ignore!==true) {
			E.showborders=ON;
		}
		this.set();
	} else {
		this.reset();
		if (ignore!==true) {
			E.showborders=OFF;
		}
	}
};

ShowBordersCommand.prototype.getMode = function()
{
	return E.showborders;
};

// paste from MS Word2
var PasteFromMSWord = function()
{
	this.Name = 'pastefrommsword' ;
	this.mode = OFF;
};

PasteFromMSWord.prototype.execute = function(is_key)
{
	//if pressed Ctrl+V
	if (is_key){
		buffer[E.mode].saveHistory();
		var pos = buffer['edit'].devhistory.position-1;
		this.code = buffer['edit'].devhistory.data[pos];
		this.clearHtmlCode();
		if (this.code) buffer['edit'].devhistory.offset[pos].innerHTML = this.code;
	}else{
		try{
			frame.execCommand("Paste", false, null );
		} catch (ee){
			if (confirm(security_error_allow)) {
				window.ShortCutKeys.pop();
			}
		}	
	}
};

PasteFromMSWord.prototype.clearHtmlCode = function()
{
	var to_replace = ["<o:p>", "</o:p>", ' style=""', ' class=""', ' class="MsoNormal"', ' lang="EN-US"'];
	if (this.code){
	for (var i in to_replace){
		var expr = new RegExp(to_replace[i], "gi");
		this.code = this.code.replace(expr, "");
	}
	}
}



PasteFromMSWord.prototype.getMode = function()
{
	// normal behavior
	try
	{
		if (!E._frame.queryCommandEnabled( "paste" ) ) {
			return DISABLED;
		} else {
			return E._frame.queryCommandState( "paste" ) ? ON : OFF;
		}
	}
	catch (e)
	{
		return OFF ;
	}
};
// ***** end of [paste from MS Word] ******


// Undo command
var Undo = function()
{
	this.Name = 'undo' ;
};

Undo.prototype.execute = function()
{
	buffer[E.mode].goHistory(-1);
	E._window.focus();
};

Undo.prototype.getMode = function()
{
	if ((buffer[E.mode].devhistory.data.length <= 0) || (buffer[E.mode].devhistory.position <= 0)) {
		return DISABLED;
	} else {
		return OFF;
	}
};

// Redo command
var Redo = function()
{
	this.Name = 'undo' ;
};

Redo.prototype.execute = function()
{
	buffer[E.mode].goHistory(1);
	E._window.focus();
};

Redo.prototype.getMode = function()
{
	if (buffer[E.mode].devhistory.position >= buffer[E.mode].devhistory.data.length-1 ) {
		return DISABLED;
	} else {
		return OFF;
	}
};

// ToggleAbsolute command
var TogglePosition = function()
{
	this.Name = 'toggleposition';
};

TogglePosition.prototype.execute = function()
{
	var sel = E.GetSelectedElement();
	if (!sel) {
		sel = E.parentNode("TABLE");
	}
	if (!sel) {
		return;
	}
	if (sel.style && sel.style.position=="absolute") {
		sel.style.position="";
	} else {
		sel.style.position="absolute";
	}
};

TogglePosition.prototype.getMode = function(){
	var sel = E.GetSelectedElement();
	if (!sel) {
		sel = E.parentNode("TABLE");
	}
	if (!sel) {
		return DISABLED;
	}
	if (sel.style && sel.style.position=="absolute") {
		return ON;
	} else {
		return OFF;
	}
};


// Name: Undo / Redo function
// Info: undo/redo fonctions for Gecko.

var URBuffer = function()
{
	var devhistory = new Object;
	devhistory.data = [];
	devhistory.position = 0;
	devhistory.offset = new Array();
	devhistory.max = _de_max_history_item;
	this.devhistory = devhistory;
};

URBuffer.prototype.createBookmark = function(node, node2, pos)
{return;
	this.devhistory.index[pos] = new Array();
	var count=0;
	while (node && node!==E._frame.body) {
		x = node;
		node = node.parentNode;
		if (node && node.childNodes != null) {
			for (var i=0; i < node.childNodes.length; i++) {
				if (x == node.childNodes.item(i)) {
					this.devhistory.index[pos][count] = i;
					count++;
					break;
				}
			}
		}
	}
	//if (node2==node)return;
	node = node2;
	this.devhistory.index2[pos] = new Array();
	count=0;
	while(node && node!==E._frame.body){
		x = node;
		node = node.parentNode;
		if (node && node.childNodes != null) {
			for (var i=0; i < node.childNodes.length; i++) {
				if (x == node.childNodes.item(i)) {
					this.devhistory.index2[pos][count] = i;
					count++;
					break;
				}
			}
		}
	}
};

URBuffer.prototype.moveToBookmark = function()
{return;

	var selection = E._window.getSelection();
	selection.removeAllRanges();
	var range = aed.createRange();

	var pos = this.devhistory.position;
	var node = E._frame.body;
	for (var i=this.devhistory.index[pos].length-1;i>=0;i--) {
		node = node.childNodes.item(this.devhistory.index[pos][i]);
	}
	range.setStart(node,this.devhistory.offset[pos]);

	if (typeof(this.devhistory.index2[pos])=="object"){
		var node2 = E._frame.body;
		for (var i=this.devhistory.index2[pos].length-1;i>=0;i--) {
			node2 = node2.childNodes.item(this.devhistory.index2[pos][i]);
		}
		range.setEnd(node2,this.devhistory.offset2[pos]);
	} else {
		range.collapse(true);
	}
	selection.addRange(range);
};

URBuffer.prototype.saveHistory = function(kk)
{
	aed = E._frame;
	var recpos;

//	try{
		oSel = E._window.getSelection();
		range = oSel.getRangeAt(0);
		p = range.commonAncestorContainer.parentNode;
		if (p && p.tagName && p.tagName.toLowerCase()=="li" && kk && kk==13)p=p.parentNode;
		if (p && p.tagName && p.tagName.toLowerCase()=="html"){
			p = E._frame.body;
		}
		
		// check if there is some changes
		if (p.innerHTML==this.devhistory.data[this.devhistory.length-1]){
			return;
		}
		if (this.devhistory.data.length >= this.devhistory.max) {
			if (this.devhistory.position==0) {
				this.devhistory.data.length = 0;
				this.devhistory.bookmark.length = 0;
			} else {
				this.devhistory.data.shift();
				this.devhistory.offset.shift();
				this.devhistory.position--;
			}
		}

		recpos = this.devhistory.position;
				
		if (p.tagName.toLowerCase() == "body"){
			this.devhistory.offset[recpos] = p;
			this.devhistory.data[recpos]  = p.innerHTML;
		}else{
			this.devhistory.offset[recpos] = p.parentNode;
			this.devhistory.data[recpos]  = p.parentNode.innerHTML;
		}
		this.devhistory.data.length = this.devhistory.position+1;
		
		this.devhistory.position++;

//	} catch (e) {}
};

URBuffer.prototype.goHistory = function(value)
{
	try{
	if (value == -1) {
		this.devhistory.position--;
	} else {
		this.devhistory.position++;
	}
		
	if (this.devhistory.position < 0)	{
		this.devhistory.position = 0;
	}

	if (this.devhistory.position == this.devhistory.data.length-1 && value==-1)	{
		this.devhistory.position++;
		this.saveHistory();
		this.devhistory.position -= 2;
	}

	rp = this.devhistory.position;
	p = this.devhistory.offset[rp];
	p.innerHTML=this.devhistory.data[rp];

	this.setHistoryCursor();
	
	if (E.showborders==ON) {
		E.commands.getCommand("Showborders").set(true);
	} else {
		E.commands.getCommand("Showborders").reset(true);
	}
	} catch (x){}
};

URBuffer.prototype.setHistoryCursor = function() {
return;
	aed = E._frame;

//	this.moveToBookmark();
	E._window.focus();
};

var buffer = new Array();
buffer["edit"] = new URBuffer();
buffer["source"] = new URBuffer();

// Name: Editor class
// Info: Contain all editors methonds for Gecko browsers.

var Editor = function( instanceName, width, height, skinName)
{
	window.activeEditor	= this;

	// Properties
	this.InstanceName	= instanceName ;
	this.Value			= '' ;
	this.Width			= width;
	this.Height			= height;
	this.skinName		= skinName ;

	// auxiliary properties
	this._frame			= false;
	this.mode			= "edit";
	this.lastmode		= "edit";
	this.showborders	= OFF;
	this.customLink		= CustomLink;
	this.tempWin		= null;
	this.tempEl;
	this.arr			= null;
	this.skinPath		= skinPath;
	this.snippetCSS		= snippetCSS;
	this._html			= null;
	this._preview_html	= null;
	this.XPCOM			= true;
	this.selectedtag	= null;
	this.editable		= true;
	this.href			= window.location.href;
	this.tempnode		= null;
	this.initHTML		= null;
	this.unlock			= false;
	this.use_old_base	= false;
	this.useBase		= false;
	this.isbegin		= false;
	this.isend			= false;
	this.disableTabs	= false;



	if (this.getParameter("fullscreen")=="on"){
		this.fullscreen		= ON ;
	} else {
		this.fullscreen		= OFF ;
	}
	this.oldw=0;
	this.oldh=0;



	if (toolbarmode) {
		for (var i=0;i<DevEditToolbars.length;i++){
			if (DevEditToolbars[i]==toolbarmode) {
				this.toolbarpos = i;
				return;
			}
		}
	}
	toolbarmode = DevEditToolbars[0];
	this.toolbarpos = 0;
};

Editor.prototype.getHTMLContent = function()
{
	return _de_getContent();
};

Editor.prototype.getTextContent = function()
{
	return _de_getTextContent();
};

Editor.prototype.setParameter = function(par, val)
{
	var str = this.href;
	idx=str.indexOf(par+"=",1);
	idx2=str.indexOf("&",idx+1);
	if((idx>=0)&&(idx2==-1)) {
		idx2=str.length;
	}
	if (idx!=-1){
		this.href = str.substring(0,idx+par.length+1) + val + str.substring(idx2,str.length);
	} else {
		if (str.indexOf("?")!=-1){
			this.href = str + "&" + par + "=" + val;
		} else {
			this.href = str + "?"+par + "=" + val;
		}
	}
};

Editor.prototype.getParameter = function(par)
{
	var str = this.href;
	idx=str.indexOf(par+"=",1);
	idx2=str.indexOf("&",idx+1);
	if ((idx>=0)&&(idx2==-1)) {
		idx2=str.length;
	}
	if (idx!=-1){
		return str.substring(idx+par.length+1,idx2);
	} else {
		return "0";
	}	
};

Editor.prototype.attachStyleSheet = function(name)
{
	this.addStyleSheet(this._frame,name);
};

// add StyleSheet (name) to document( d )
Editor.prototype.addStyleSheet = function(d,name)
{
	var e=d.createElement('LINK');
	e.rel='stylesheet';
	e.type='text/css';
	e.href=name;
};

Editor.prototype.checkLoad = function()
{//return;
	if (hideitems["EditMode"]==1 && hideitems["SourceMode"]==1 && hideitems["PreviewMode"]==1) {
		this.disableTabs=true;
	}
	this.commands = new Commands();
	this.toolbaritems = new ToolbarItems();

	ToolbarSets.AddItem(toolbarmode,'eToolbar');
	ToolbarSets.AddItem("_source",'eToolbar');
	ToolbarSets.AddItem("path",'ePath');
	ToolbarSets.AddItem("_preview",'eToolbar');
	if (!this.disableTabs)ToolbarSets.AddItem("footer",'eFooter');

	this.sheet = new Sheet();
	if (hideitems["EditMode"]==0) {
		this.sheet.AddItem("EditMode", "Edit mode", "status_edit", CHOOSE);
	}
	if (hideitems["SourceMode"]==0) {
		this.sheet.AddItem("SourceMode", "Source mode", "status_source", OFF);
	}
	if (hideitems["PreviewMode"]==0) {
		this.sheet.AddItem("PreviewMode", "Preview mode", "status_preview", OFF);
	}
	this.setSize();
};

Editor.prototype.setSize = function()
{

	var fr = document.getElementById(E.InstanceName+"_frame");
	fr.height="100%";
	var pDiv = parent.document.getElementById(E.InstanceName+"main");
	this.realHeight = pDiv.offsetHeight;
	var tDiv = document.getElementById(E.InstanceName+"main1");
	if (pDiv.offsetWidth<tDiv.offsetWidth) {
		pDiv.style.width = (tDiv.offsetWidth+20)+"px";
	}
	if (pDiv.offsetHeight<tDiv.offsetHeight) {
		pDiv.style.height = (tDiv.offsetHeight)+"px";
	}
	if (getCookieVal("de_mode").toLowerCase()=="de_mode=simple" && parseInt(pDiv.style.height) <= 250){
		fr.style.height = (parseInt(fr.offsetHeight)-25)+"px";
	}

	document.getElementById("de_body").style.height=(pDiv.offsetHeight-5)+"px";

	if (this.getParameter("oldw")=="0") {
		this.oldw = pDiv.offsetWidth;
		this.oldh = pDiv.offsetHeight;
		this.oldh = pDiv.offsetHeight;

		this.setParameter("oldw",this.oldw);
		this.setParameter("oldh",this.oldh);
	} else {
		this.oldw = this.getParameter("oldw")*1.0;
		this.oldh = this.getParameter("oldh")*1.0;
	}

	this.neww = this.oldw;
	this.newh = this.oldh;
};

Editor.prototype.execCommand = function(name)
{
	if (this.commands.getCommand(name)) {
		this.commands.getCommand(name).execute();
		ToolbarSets.Redraw();
	}
};

Editor.prototype.switchModeTo = function(mode)
{
	if (!mode) return false;
	if (typeof(mode)!== "string") return false;
	if (mode.toLowerCase()==this.lastmode)return false;	
	switch (mode.toLowerCase()){
		case "edit":
			this.execCommand("EditMode");
			this.sheet.Select("EditMode");
			break;
		case "source":
			this.execCommand("SourceMode");
			this.sheet.Select("SourceMode");
			break;
		case "preview":
			this.execCommand("PreviewMode");
			this.sheet.Select("PreviewMode");
	}
	return true;
};

Editor.prototype.loadComplete = function()
{
	this.setInitialValue();
};


Editor.prototype.setInitialValue = function()
{

	findCustomTags();// ??

	// set default color
	ToolbarSets.SwitchToolbarSet (toolbarmode);
	PopupSet.CreatePopup("spellmenu");
	PopupSet.CreatePopup("sourcetag");	

	if (E.toolbaritems&&E.toolbaritems.GetItem('Fontcolor')) {
		E.toolbaritems.GetItem('Fontcolor').SetButtonColor("#000000");
	}
	if (E.toolbaritems&&this.toolbaritems.GetItem('Highlight')) {
		this.toolbaritems.GetItem('Highlight').SetButtonColor("yellow");
	}

	if (hideitems["guidelinesOnByDefault"]==1 && !(E.lastmode=="source" && E.showborders==OFF)) {
		this.commands.getCommand('Showborders').execute();
	}
	if (hideitems["guidelinesOnByDefault"]==0) {
		this.commands.getCommand('Showborders').switchCSS(true);
	}

	E.doStyles();
	this.sheet.Redraw();
	ToolbarSets.Redraw();
	E.checkEditArea();

	checkImgLoaded();

	if (hideitems["EditMode"]==1){
		this.switchModeTo("source");
	}
	
	if (is_setCursor==1) {
		this.Focus();
	} else {
		this.updateValue();
	}
	if (eventListener){
		for (var i = 0; i < eventListener.length; i++){
			if (eventListener[i][0].toLowerCase()=="onload"){
				eval("parent."+eventListener[i][1]+"()");
			}	
		}
	}
	loading_in_progress = false;
	setTimeout("_try_edit()",500);
};

function _try_edit(){
 try{	
 	E._frame.designMode = "On";
 } catch (e) {}	

 correctSkype();
 correctUrls();
}

Editor.prototype.checkEditArea = function()
{
	check = false;
	findAllEditable(this._frame.body);
	E.isbegin = check;
	E.isend = check;
};

Editor.prototype.writeContentWithCSS = function(data)
{
};

Editor.prototype.saveBodyAttribute = function()
{
	try{
	this.bodyattr = new Array();
	this.bodystyle= this._frame.body.style.cssText;
          
	for (var i=0;i<this._frame.body.attributes.length;i++){
		if (this._frame.body.attributes[i].nodeName.substr(0,1)!=="-") {
			this.bodyattr[i] = this._frame.createAttribute(this._frame.body.attributes[i].nodeName);
			this.bodyattr[i].nodeValue = this._frame.body.attributes[i].nodeValue.replace(/(-moz-[^;]+;)/gi,"");
		}	
	}
	} catch(e){}
};

Editor.prototype.restoreBodyAttribute = function()
{
	var b = this._frame.body.attributes;
	/*if (this.bodystyle==""){
		this._frame.body.removeAttribute("style");
	} else {
		this._frame.body.style.cssText = this.bodystyle;
	}*/	
	for (var i=0;i<b.length;i++){
		this._frame.body.removeAttributeNode(b[i]);
	}
	this._frame.body.removeAttribute("style");
	/*for (var i=0;i<this.bodyattr.length;i++) {
		this._frame.body.setAttributeNode(this.bodyattr[i]);
	}*/
};

Editor.prototype.writeC = function(html)
{
	this.writeContent(embed2img(addWrap(html)));
	E.updateValue("no");	
};

Editor.prototype.writeHTMLContent = function(html)
{
	html = html.replace(/<!doctype[^>]+>/gi,'');
	if (this.mode=="source"){
		html = html.replace(/</g,"&lt;");
		html = html.replace(/>/g,"&gt;");
	}
	this.w(html);
	E.updateValue("no");
	correctSkype();
};

Editor.prototype.w = function(data)
{
	if (parent.document.getElementById(name+"_html2").value!="" && !data) {
		html = parent.document.getElementById(name+"_html2").value;
		html = html.replace(/&amp;/g,'&');
		if (html.toLowerCase().indexOf("<html")>=0) {
			var add_to_head = '<style id="'+this.InstanceName+'bs">'+border_style+'<\/style>';//'<link href="'+this.skinPath+'borders.css" type="text/css" rel="stylesheet" />';
			if (this.snippetCSS) {
				add_to_head += '<link href="'+this.snippetCSS+'" type="text/css" rel="stylesheet" />';
			}
			newhtml = html.match(HeadContents);
			if (newhtml) {
				html = newhtml[1]+add_to_head+newhtml[2]+newhtml[3];
			} else {
				html = h;
			}
		}
	} else {
		var h = data ? data : parent.document.getElementById(name+"_input").value;
		if (h=="") {
			h="<body></body>";
		}
		var html="";
		if (h.toLowerCase().indexOf("<html")>=0){
			var add_to_head = '<style id="'+this.InstanceName+'bs">'+border_style+'<\/style>';//'<link href="'+this.skinPath+'borders.css" type="text/css" rel="stylesheet" />';
			if (this.snippetCSS) {
				add_to_head += '<link href="'+this.snippetCSS+'" type="text/css" rel="stylesheet" />';
			}
			newhtml = h.match(HeadContents);
			if (newhtml) {
				html = newhtml[1]+add_to_head+newhtml[2]+newhtml[3];
			} else {
				html = h;
			}
		} else {
			html = "<html><head>";
			html += '<style id="'+this.InstanceName+'bs">'+border_style+'<\/style>';//'<link href="'+this.skinPath+'borders.css" type="text/css" rel="stylesheet" />';
			this.use_old_base = true;
			if (this.snippetCSS) {
				html += '<link href="'+this.snippetCSS+'" type="text/css" rel="stylesheet" />';
			}
			html+="</head>" + h + "</html>";
		}
	}
	// set initial HTML code for restricted mode
	var h = data?data:parent.document.getElementById(name+"_input").value;
	if (h.toLowerCase().indexOf("<html")>=0) {
		if (!this.initHTML) {
			this.initHTML = h;
		}
	} else {
		if (!this.initHTML) {
			this.initHTML = "<html><head></head>"+h+"</html>";
		}
	}

	this.HTMLTags = html.match(HtmlContents);
	if (!this.HTMLTags) {
		this.HTMLTags = new Array();
		this.HTMLTags[0]=html;
		this.HTMLTags[1]="";
		this.HTMLTags[2]="";
		this.HTMLTags[3]="";

		var x = html.match(HtmlContents1);
		if (x) {
			this.HTMLTags[1]=x[1];
		}
		var y = html.match(HtmlContents2);
		if (y) {
			this.HTMLTags[3]=y[1];
		}
	}


	if ( html.toLowerCase().indexOf("<base")>=0){
		myBaseHref="base tag";
	}
	
	try{
		this._frame.designMode = "on";
		this._frame.open();
		html = this.checkBODY(html);
		this._frame.write(embed2img(addWrap(html)));
		this._frame.close();
	} catch(e){}
};

Editor.prototype.writeContent = function(html)
{
	var o = this._frame;
	o.open();
	o.write(html);
	o.close();
	return;
};

Editor.prototype.changeHTML = function(html, frameobj, pr)
{
	var aed = this._frame;
	var o;
	if (frameobj){
		o=frameobj;
	} else {
		o=aed;
	}
	if (pr){
		o.open();
		o.write(html);
		o.close();
		return;
	}
	o.getElementsByTagName("BODY")[0] = old_body_tag;
	var old_head_text = o.getElementsByTagName("HEAD")[0].innerHTML;
	var h = html.match(HeadContents);
	if (h && h[2]!=old_head_text) {
		try{
			o.getElementsByTagName("HEAD")[0].innerHTML = h[2];
		} catch(e){}
	}

	html = trim_space_from_style(html);

	var m = html.match(BodyContents);
	if (m){
		try{
			if (pr) {
				o.body.innerHTML = addFullURI(m[2]);
			} else {
				o.body.innerHTML = m[2];
			}
			// change BODY attr
			E.restoreBodyAttribute() ;

			html.replace(/<body[^\>]*>/ig,function(s1){
				s1.replace(/((\S+)\=\"*([^\"]+)\"*)/gi,function(g1,g,g2,g3){
//					alert(g1);
					g3 = g3.replace(/\>/,"");
					g3 = g3.replace(/\"/i,"");
					g3 = g3.replace(/"/i,"");
					switch (g2){
						case "style":
							o.body.style.cssText = g3;
							//alert(g3)
							break;

						default:
							o.body.setAttribute( g2, g3, 0 ) ;
							//alert(g2+" "+g3)
					}		
				});
			});
		} catch(e){}
	}
};

function setEvent ()
{
	E.setEvent();
}

Editor.prototype.setEvent = function()
{
	try {
		this._frame.addEventListener( 'keydown', this.Redraw, true) ;
		this._frame.addEventListener( 'keypress', this.StopDefault , false) ;
		this._frame.addEventListener( 'keyup', this.CheckUp , false) ;
		this._frame.addEventListener( 'contextmenu', this.ContextMenu , true) ;
		this._frame.addEventListener( 'dragdrop', this.CheckEditable, true ) ;
		this._frame.addEventListener( 'draggesture', this.DragStart, true ) ;
		this._frame.addEventListener( 'DOMAttrModified', this.DOMSubtreeModified, true ) ;
		this._frame.addEventListener( 'drop', this.CheckEditable, true ) ;
		this._frame.addEventListener( 'mouseup', this.Redraw, true ) ;
		this._frame.addEventListener( 'mousedown', this.MouseDown, true ) ;
		this._frame.addEventListener( 'blur', this.updateValue, false ) ;
		document.addEventListener( 'blur', this.updateValue, false ) ;
	} catch(e){}

	element = parent.document.getElementById(E.InstanceName+"main");
	var e = element.parentNode ;
	while ( e ) {
		if (e.nodeName.toLowerCase() == "form") {
			break ;
		}
		e = e.parentNode ;
	}
	if (e){
		e.addEventListener( 'submit', this.updateValue, true ) ;
	}
	// Disable the standard table editing features of Firefox.
	try {
		this._frame.execCommand( 'enableInlineTableEditing', false, false ) ;
	} catch (e){}

	if (is_setCursor==1){
		E.Focus();
	}
};

		
mouseisdown=false;

var lostedImg = null;
Editor.prototype.DragStart = function(e)
{
	lostedImg = E._frame.getElementsByTagName("img");
};


Editor.prototype.setdown = function()
{
	mouseisdown=true;
	return true;
};

Editor.prototype.setup = function(evt)
{
	mouseisdown=false;
	evt = (evt)?evt:(window.event)?window.event:"";

	PopupSet.Redraw();
	ToolbarSets.Redraw(evt);

	return true;
};

Editor.prototype.updateValue = function()
{
	if (E){
		E.commands.getCommand('Save').execute("no");
	}	
};

// create Editor object
Editor.prototype.Create = function()
{ 
	// instanceName should not be empty
	if (!this.InstanceName || this.InstanceName.length == 0) {
		this.throwError( 1, 'You must specify a instance name.' );
		return ;
	}

	// check browser compatible
	if (!this.isCompatibleBrowser()) {
		this.throwError( 2, 'Browser is not compatible.' );
		return ;
	}

	// instert editor into page
	var htmlstr = "";
	htmlstr+= '<div id="'+this.InstanceName+'main1" style="height:100%;width:100%">';
	htmlstr+= '<table width="100%" height="100%" class="de_container" border="0" cellspacing="0" cellpadding="0" >';
	htmlstr+= '<tr><td>';
	htmlstr+= '<div id="eToolbar"></div>';
	htmlstr+= '</td></tr>';
	htmlstr+= '<tr><td width="100%" height="100%" >';
		htmlstr+= '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">';
		htmlstr+= '<tr><td valign=top height="100%" id="leftPanel">';
		htmlstr+= '<img src="images/1x1.gif" width="1px" height="5px">&nbsp;</td>';
		htmlstr+= '<td class="de_editcontainer_in" width="100%" height="100%">';
		htmlstr+= '<iframe onblur="updateValue();" width="100%" height="1px" class="de_editcontainer" id="' + this.InstanceName + '_frame'+'"'+' onLoad="setEvent()" frameborder="no"></iframe>';
		htmlstr+= '<iframe id="' + this.InstanceName + '_preview'+'" width="100%" height="100%" scrolling="yes"  frameborder="0" class="de_editcontainer" style="display:none;"></iframe>';
		htmlstr+= '</td><td width="1px">';
		htmlstr+= '<img src="images/1x1.gif" width="1px">&nbsp;&nbsp;';
		htmlstr+= '</td></tr>';
		htmlstr+= '</table>';
	htmlstr+= '</td></tr>';
	htmlstr+= '<tr><td><img src="images/1x1.gif" height=5px></td></tr>';
	htmlstr+= '<tr '+(hideTagBar?'style="display:none;"':'')+'><td class="de_TB_Toolbar" class="pathtext">';
		htmlstr+= '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
		htmlstr+= '<tr><td>';
		htmlstr+= '<span id="ePath"></span>';
		htmlstr+= '</td>';
		htmlstr+= '<td>';
		htmlstr+= '<span style="float:right" class="de_pathcontainer" id="eRemoveTag"></span>';
		htmlstr+= '</td></tr>';
		htmlstr+= '</table>';
	htmlstr+= '</td></tr>';

	if (!(hideitems["EditMode"]==1 && hideitems["SourceMode"]==1 && hideitems["PreviewMode"]==1)){
		htmlstr+= '<tr><td class="de_TB_Toolbar">';
		htmlstr+= '<table border="0" cellspacing="0" cellpadding="0">';
		htmlstr+= '<tr><td>';
		htmlstr+= '<div id="footersheet"></div>';
		htmlstr+= '</td>';
		htmlstr+= '<td width="100%" valign=top>';
			htmlstr+= '<table cellspacing="0" cellpadding="0" border="0" width="100%">';
			htmlstr+= '<tr><td width="100%">';
			htmlstr+= '<div class="de_sheetline1" width="100%" height="1px"></div>';
			htmlstr+= '</td></tr>';
			htmlstr+= '<tr><td width="100%">';
			htmlstr+= '<div class="de_sheetline2" width="100%" height="1px"></div>';
			htmlstr+= '</td></tr>';
			htmlstr+= '<tr><td align="right">';
			htmlstr+= '<div id="eFooter"></div>';
			htmlstr+= '</td></tr>';
			htmlstr+= '</table>';
		htmlstr+= '</td></tr></table>';
		htmlstr+= '</td></tr>';
		htmlstr+= '</table>';
	htmlstr+= '</td></tr>';
	}
	htmlstr+= '</table>';
	htmlstr+= '</div>';

	document.write(htmlstr);
	aID = this.InstanceName + '_frame';
	window.aID = aID;
	this._frame=document.getElementById(aID).contentDocument;
	this._window=document.getElementById(aID).contentWindow;
	this._preview = document.getElementById(this.InstanceName + '_preview').contentDocument;
	window.fr = this._frame;
	aed = this._frame;

	if (parent.document.getElementById(name+"_html2").value!="") {
		html = parent.document.getElementById(name+"_html2").value;
		html = html.replace(/&amp;/g,'&');
		if (html.toLowerCase().indexOf("<html")>=0) {
			var add_to_head = '<style id="'+this.InstanceName+'bs">'+border_style+'<\/style>';//'<link href="'+this.skinPath+'borders.css" type="text/css" rel="stylesheet" />';
			if (this.snippetCSS) {
				add_to_head += '<link href="'+this.snippetCSS+'" type="text/css" rel="stylesheet" />';
			}
			newhtml = html.match(HeadContents);
			if (newhtml) {
				html = newhtml[1]+add_to_head+newhtml[2]+newhtml[3];
			} else {
				html = h;
			}
		}

	} else {
		var h = parent.document.getElementById(name+"_input").value;
		if (h=="") {
			h="<body></body>";
		}
		var html="";
		if (h.toLowerCase().indexOf("<html")>=0){
			var add_to_head = '<style id="'+this.InstanceName+'bs">'+border_style+'<\/style>';
			if (this.snippetCSS) {
				add_to_head += '<link href="'+this.snippetCSS+'" type="text/css" rel="stylesheet" />';
			}
			newhtml = h.match(HeadContents);
			if (newhtml) {
				html = newhtml[1]+add_to_head+newhtml[2]+newhtml[3];
			} else {
				html = h;
			}
		} else {
			html = "<html><head>";
			html += '<style id="'+this.InstanceName+'bs">'+border_style+'<\/style>';
			this.use_old_base = true;
			if (this.snippetCSS) {
				html += '<link href="'+this.snippetCSS+'" type="text/css" rel="stylesheet" />';
			}
			html+="</head>" + h + "</html>";
		}
	}

	if ( html.toLowerCase().indexOf("<base")>=0){
		myBaseHref="base tag";
	}

	// set initial HTML code for restricted mode
	var h = parent.document.getElementById(name+"_input").value;
	if (h.toLowerCase().indexOf("<html")>=0){
		if (!this.initHTML) {
			this.initHTML = h;
		}
	} else {
		if (!this.initHTML) {
			this.initHTML = "<html><head></head>"+h+"</html>";
		}
	}


	//this.HTMLTags = html.match(HtmlContents);
	this.HTMLTags=null;
	var pos = html.indexOf("<html");
	if (pos==-1) {
		pos=html.indexOf("<HTML");
	}
	if (pos>=0){
		var pos1 = html.indexOf(">",pos+1);
		var pos2 = html.indexOf("</html",pos1+1);
		if (pos2==-1) {
			pos2 = html.indexOf("</HTML>",pos1+1);
		}
		if (pos2==-1) {
			pos2 = html.length;
		}
		this.HTMLTags = new Array();
		this.HTMLTags[0] = html;
		this.HTMLTags[1] = html.substring(0,pos1+1);
		this.HTMLTags[2] = html.substring(pos1+1,pos2);
		this.HTMLTags[3] = html.substring(pos2,html.length);
	}

	if (!this.HTMLTags){
		this.HTMLTags = new Array();
		this.HTMLTags[0]=html;
		this.HTMLTags[1]="";
		this.HTMLTags[2]="";
		this.HTMLTags[3]="";

		var x = html.match(HtmlContents1);
		if (x) {
			this.HTMLTags[1]=x[1];
		}
		var y = html.match(HtmlContents2);
		if (y) {
			this.HTMLTags[3]=y[1];
		}
	}

	try{
		// 2007-08-03
		// commenting this out has fixed the iframes on Firefox
		//setTimeout("enable()",10)
		this._frame.open();
		html = this.checkBODY(html);
		this._frame.write(deEngine.preserve(embed2img(addWrap(html))));
		this._frame.close();
	} catch(e) {}
	correctUrls();
	this.checkLoad();
};

function enable(){
	E._frame.designMode = "on";
}

Editor.prototype.checkBODY = function(s)
{
	return s.replace(/<body><\/body>/gi,"<body></body>");
};

Editor.prototype.lockPage = function()
{
	E.checkEditArea();
	E.unlock = false;
};

Editor.prototype.unlockPage = function()
{
	E.unlock = true;
	E.isbegin = false;
	E.isend = false;
};

Editor.prototype.Editable = function(e,e1)
{
	var range = null;
	var fR = null;
	var clW=0,clH=0,sL=0,sT=0;

	if (this._frame.compatMode=='CSS1Compat'){
		clW = this._frame.documentElement.clientWidth;
		clH = this._frame.documentElement.clientHeight;
		sL = this._frame.documentElement.scrollLeft;
		sT = this._frame.documentElement.scrollTop;
	} else {
		clW = this._frame.body.clientWidth;
		clH = this._frame.body.clientHeight;
		sL = this._frame.body.scrollLeft;
		sT = this._frame.body.scrollTop;
	}

	if (e && ((e.pageX > (clW+sL) )|| (e.pageY > (clH+sT) ) )){
		return true;
	}

	if (e && (e.type=="mousedown"|| e.type=="mouseup") && e.target && e.target.tagName && e.target.tagName.toUpperCase()=="HTML" && E.mode=="edit"){
		return;
	}

	try{
		oContainer = E.getSelectedElement();
		if (!oContainer) {
			if (e1) {
				oContainer = e1.target;
			} else {
				oSel = E._window.getSelection();
				range = oSel.getRangeAt(0);
				var oContainer = range.startContainer;
				var p = range.commonAncestorContainer;
				if (!range.collapsed && range.startContainer == range.endContainer && range.startOffset - range.endOffset <= 1 && range.startContainer.hasChildNodes()){
					p = range.startContainer.childNodes[range.startOffset];
					oContainer = p;
				}
				fR = p;
				oContainer = p;
				while (p.nodeType == 3 ) {
					p = p.parentNode;
					oContainer = p;
				}
			}
		}

		var isEditable = E.unlock ||E.walkDOM(oContainer);
		if (insideWrap) {
			oContainer=wrap;
		}

		try{
			if (oContainer && oContainer.id && oContainer.id.substr(0,7)=="de_wrap"){
				// start & backspace - range.startOffset == 0) && (e.which==8)
				//end & del - rest of if statement
				compareNode = E._frame.createRange();
				compareNode.selectNodeContents(oContainer);
				compareNode.collapse(false);
				bogus = false;

				// (range.endOffset == fR.length)
				var fc = false;
				if (oContainer.firstChild){
					if (oContainer.firstChild){
						if (range.startContainer.nodeType==1 && range.startOffset!==0){
							compare = range.startContainer.childNodes.item(range.startOffset);
						} else {
							compare = range.startContainer;
						}	
						fc=oContainer.firstChild==compare;
						if (!fc) {
							x = oContainer.firstChild;
							while (x && x!==compare){
								x=x.firstChild;
							}	
							if (!x){
								x = oContainer.firstChild.nextSibling;
								while (x && x!==compare){
									x=x.firstChild;
								}	
								
							}
							fc=x==compare;
						}	
						if (!fc && oContainer.firstChild.nodeValue=="")fc=oContainer.firstChild.nextSibling==range.startContainer;
					}
				}


is_first_empty_text = 0;
is_first_br = 0;

			try{
				var ce = false;
				if (oContainer.lastChild){
					ce = oContainer.lastChild==range.endContainer;
					var last = oContainer.lastChild;

					if (!ce){
						// check if last is empty #text node
						t = last;
						while ((t.nodeType==1 && t.tagName && t.tagName.toLowerCase()=="br" ) ||
							  (t.nodeType==3 && t.data.replace(/\n/gi,"").length == 0)){
							if (t.previousSibling){
								t = t.previousSibling;
								if(t)last=t;
							} else {
								break;
							}		
						}
						
						while (last && last!==range.endContainer){
							last=last.lastChild;
						}

						s1 = oContainer.firstChild;
						while (s1.nodeType==3 && s1.data.replace(/\n/gi,"").length == 0){
							s1 = s1.nextSibling;
							is_first_empty_text++;
						}

						// count BR tag
						sx = oContainer.firstChild;
						while (sx.nodeType==1 && sx.tagName.toLowerCase()=="br"){
							sx = sx.nextSibling;
							is_first_br++;
						}
						
						s2 = oContainer.lastChild;
						while (s2.nodeType==3 && s2.data.replace(/\n/gi,"").length == 0){
							s2 = s2.previousSibling;
						}
						if ( range.startContainer == range.endContainer && (s1==s2)){
							last =range.startContainer;
							ce = true;
							bogus = true;
						}
						if (!last)ce=false;
					}	

					if (last){
						if (range.endContainer == oContainer && range.endOffset==0)ce=true;
						if (!ce)ce = range.endOffset == last.nodeValue.length;							
						if (!ce) ce = (range.endOffset == last.nodeValue.length-1 && last.nodeValue.charCodeAt(last.nodeValue.length-1)==10 );
						if (!ce && last.nodeValue=="")	ce = range.endOffset == last.previousSibling.nodeValue.length;
					} else {
						if(range.endOffset){
							if (range.endOffset==range.endContainer.childNodes.length-1 && range.endContainer.childNodes.item(range.endOffset).tagName.toLowerCase()=="br"){
								ce = true;
							}
						} else {
							var s = oContainer.innerHTML.replace(/<[^>]+>/g,"");
							s = s.replace(/\n/g,"");
							if (range.endOffset == s.length){
								ce = true;
							}
						}
					}	
				}
				} catch (err){}

//trace(oContainer.firstChild.data.length+" fc="+fc+" "+range.startContainer.nodeType+" "+ range.startOffset+" "+is_first_br)				
				if ((((range.startOffset==0 || (range.startContainer.nodeType==3 && range.startOffset==1 && ((oContainer.firstChild.data.length==0)||(oContainer.firstChild.tagName && oContainer.firstChild.tagName.toLowerCase()=="br")))||(range.startContainer.nodeType==1 && range.startOffset==is_first_empty_text)) && fc) && ( e.which==8 || e.which==37 || e.which==38 || e.which==40)) || 
				  ( ce && (e.type && e.type=="keydown" && (e.which==46 || e.which==39 || e.which==40)))) {
					isEditable=false;
				}
			}
		} catch(x){}

		if (e) {
			if (E.walkDOM && isEditable) {
				E.editable = true;
				return true;
			} else {
				e.stopPropagation();
				e.preventDefault();
				E.editable = false;
				return false;
			}

		} else {
			if (E.walkDOM && isEditable) {
				return true;
			} else {
				return false;
			}
		}
	} catch(e){}
};

Editor.prototype.MouseDown = function(evt)
{
	e = evt;
	if (e.target && e.target.tagName && e.target.tagName.toLowerCase() =="div" && e.target.innerHTML==""){
		e.target.innerHTML="&nbsp;";
		
		var sel = E._window.getSelection();
		var range = E._frame.createRange();
		range.selectNode(e.target.firstChild);
		sel.removeAllRanges();
		sel.addRange(range);

	};
	
	// if click on image
	if (e.target && e.target.tagName.toLowerCase()=="img" && e.target.id){
		if (e.target.id.indexOf("de_add")>=0){
			addblock(e.target, e);
			return false;
		} else if (e.target.id.indexOf("de_del")>=0){
			delblock(e.target, e);
			return false;
		}	
	}
	return true;
};

Editor.prototype.ContextMenu = function(evt)
{
	if (hideitems["ContextMenu"]){
		evt.stopPropagation();
		evt.preventDefault();
	} else {
	if (!evt.ctrlKey){
		Selection.set();

		E.commands.getCommand("Contextmenu").execute(null,evt.clientX,evt.clientY);
		var sel = E._window.getSelection();

		var node = null;
		var node2 = null;
		for (var i=0;i<10;i++){
			node = E._frame.getElementById("de_wrap_div"+(i+1));
			node2 = sel.anchorNode;
			if (!node) {
				break;
			}
			if (node && sel.containsNode(node,true)) {
				break;
			}
			if (node2 && node2.id && node2.id.indexOf("de_wrap_id")>=0) {
				node=node2;
				break;
			}
		}
		if (sel.toString().length>0 && node && !sel.isCollapsed && (sel.containsNode(node,false)||node2==node)){
			sel.getRangeAt(0).selectNodeContents(node);
			sel.collapseToEnd();
		}
		evt.stopPropagation();
		evt.preventDefault();
	}
	}
};

// source engine var's
context_str="";
tag_typing = false;

function fixedImg(){
	try{
	var newImg = E._frame.getElementsByTagName("img");
	for (var i = 0; i < lostedImg.length;i++){
		newImg[i].src = lostedImg[i].src;
	}
	} catch(e){}
	lostedImg = null;
}


Editor.prototype.DOMSubtreeModified = function(e)
{
	if (lostedImg)fixedImg();
}

_start_typing_node=null;
_start_typing_offset=null;

ht_begin = null
ht_end = null

// redraw
Editor.prototype.Redraw = function(e)
{
	removeSafariStyles();
	E.editable = true;
	var cShow = false;
	cancel_event = false;
	if (!e) {
		return true;
	}
	if (!E.Editable(e)) {
		x = E.Editable(e)
		PopupSet.Redraw();
		ToolbarSets.Redraw(e);

		return false;
	}

	Selection.set();
	wc = E.commands;

	// check spell words
	var se = E.GetSelectedElement();
	if (!se&&E.GetSelection()=="") {
		se = E.firstParentNode();
	}
	if (se && se.id && se.id.substring(0,9) =="_de_spell"){
		buffer[E.mode].saveHistory();
		// select word
		if (e.clientX && e.clientY){
		var sel = E._window.getSelection();
		range = E._frame.createRange();
		range.selectNode(se);
		//sel.removeAllRanges();
		sel.addRange(range);

		var dg = se.id.match(/(\d+)/g);
		PopupSet.Items["spellmenu"].ReplaceItems(dg[0]*1.0);
		E.commands.getCommand("Spellmenu").execute(null,e.clientX,e.clientY);
		PopupSet.Redraw("spellmenu");
		e.stopPropagation();
		e.preventDefault();
		}
		return;
	}
	// end check spell
	cancel_event=false;

	var f = false;
	var shortcut = false;
	if (e.ctrlKey){
		var key = String.fromCharCode(e.which).toUpperCase();
		if (key=="X" || key=="V"){
			setTimeout("restoreUrls();",150);
			buffer[E.mode].saveHistory();
			if (is_forcePasteWord) {
	   			setTimeout('E.commands.getCommand("Pastefrommsword").execute(true);',100);
			}
		}

		for(var i=0; i < ShortCutKeys.length; i++){
			var k = ShortCutKeys[i][0];
			if (k.toUpperCase().indexOf("SHIFT")>=0 && e.shiftKey && key==k.substr(k.indexOf("+")+1,1))f=true;
				else if (key == k)f=true;
			if (f) {
				if (E.commands.getCommand(ShortCutKeys[i][1]).getMode()!==DISABLED){
					E.commands.getCommand(ShortCutKeys[i][1]).execute();
				}	
				f = false;				
			}
		}
		PopupSet.Redraw();
		ToolbarSets.Redraw(e);
		cShow = true;
	}

	if(!e.ctrlKey && e.which==1) {
		PopupSet.Redraw();
		ToolbarSets.Redraw(e);
		cShow = true;
	}

	if (shortcut || cancel_event) {
		e.stopPropagation();
		e.preventDefault();
	}

	if (cShow){		
		setTimeout("E.commands.getCommand('Paragraph').showChar()",20);
	}

	if ((e.which && (e.which>32 && e.which<256) && !e.altKey && !e.ctrlKey && !sKey[e.which]) && 
		(buffer[E.mode].devhistory.position==0 || E._window.getSelection().getRangeAt(0).startContainer!==this.lastContainer || ( E._window.getSelection().getRangeAt(0).startOffset!==this.lastOffset && E._window.getSelection().getRangeAt(0).startOffset!==this.lastOffset+1))){

		if (E._window.getSelection().getRangeAt(0).startContainer!==this.lastContainer){
			try{
				this.lastContainer = this.lastContainer.childNodes[this.lastOffset];
			} catch(y){}
			
		}	

		if (E._window.getSelection().getRangeAt(0).startContainer!==this.lastContainer)	{
			buffer[E.mode].saveHistory();
			PopupSet.Redraw();
			ToolbarSets.Redraw(e);		
		}

		this.lastContainer = E._window.getSelection().getRangeAt(0).startContainer;
		this.lastOffset = E._window.getSelection().getRangeAt(0).startOffset;

		
	} else 
	if (!e.ctrlKey && e.which != 90 && e.which != 89) {
		if (e.which == 32 || e.which == 13 || e.which == 46)
		{
			buffer[E.mode].saveHistory(e.which);
		}	
	}

	return true;

};

Editor.prototype.CheckEditable = function(e)
{
	var t = E.Editable(e);
	return t;
};

Editor.prototype.StopDefault = function(e)
{
	E.Editable(e);

	if (e.ctrlKey){
		var key = String.fromCharCode(e.which).toUpperCase();
		for(var i=0; i < ShortCutKeys.length; i++){
			if (key == ShortCutKeys[i][0]) {
				e.stopPropagation();
				e.preventDefault();
			}
		}
	}
};

Editor.prototype.CheckUp = function(e)
{
 try{
	e = (e) ? e : (window.event) ? window.event : "";

	E.Editable(e);

	// redraw menus for keys:
	if (!e.ctrlKey && (e.which >= 37 && e.which <= 40) && !cancel_event) {
		PopupSet.Redraw();
		ToolbarSets.Redraw(e);
	}

	if (e.shiftKey && (e.which==35 || e.which==36)) {
		PopupSet.Redraw();
		ToolbarSets.Redraw(e);
	}

	if (!e.ctrlKey && e.which != 90 && e.which != 89) {
		if (e.which == 32 || e.which == 13 || e.which == 46)
		{
			PopupSet.Redraw();
			ToolbarSets.Redraw(e);
		}
	}
	
	if (E.mode=="source"){
		E.updateValue();
	}
	return true;
} catch(x){
  return false;
}	
};

Editor.prototype.Focus = function()
{
	try{
		E._window.focus();
	} catch ( e ) {}
};

// this method check browser compatible
Editor.prototype.isCompatibleBrowser = function()
{
	if ( browser.NS && navigator.productSub >= 20020512 ) { //20030210
		return true ;
	} else {
		return false ;
	}
};

// show errors
Editor.prototype.throwError = function( errorNumber, errorDescription )
{
	this.ErrorNumber		= errorNumber ;
	this.ErrorDescription	= errorDescription ;

	document.write('<div style="COLOR: #ff0000">' ) ;
	document.write('[ Editor Error ' + this.ErrorNumber + ': ' + this.ErrorDescription + ' ]' ) ;
	document.write('</div>' ) ;
};

Editor.prototype.clearAll = function()
{
	this._frame.body.innerHTML = '&nbsp;';
};

Editor.prototype.clearContent = function()
{
	this._frame.body.innerHTML = '&nbsp;';
};

Editor.prototype._insertBefore = function(text)
{
	buffer[this.mode].saveHistory();
	
	var aew = E._window;
	var aed = E._frame;
	var sel = aew.getSelection();
	_end_node = sel.getRangeAt(0).startContainer
	_end_offset = sel.getRangeAt(0).startOffset;

	text = embed2img(addWrap(text,1));

	var range = aed.createRange();

	
	range.setStart(_start_typing_node, _start_typing_offset);
	range.setEnd(_end_node, _end_offset);
	sel.removeAllRanges();
	sel.addRange(range);
	
	addText = aew.getSelection().toString();
	addText = addText.replace(/([\/\n\f\r])/gi,"");
	addText = addText.replace(/</gi,"&lt;");
	addText = addText.replace(/>/gi,"&gt;");
	
	text1 = addText+"&gt;";
	text1 = colourCode(text1);
	insertNodeAtSelection(document.getElementById(window.aID),text1);
	
	text = colourCode(text);
	insertNodeAtSelection(document.getElementById(window.aID),text,true);

	// set cursor to the end of first FONT tag
	sc = aew.getSelection().getRangeAt(0).startContainer;
	sc_off = aew.getSelection().getRangeAt(0).startOffset;
	aew.getSelection().removeAllRanges();
	var range2 = aed.createRange();
	range2.selectNodeContents(sc.childNodes[sc_off-1]);
	range2.collapse(false);
	aew.getSelection().addRange(range2);
	// ---
	
	PopupSet.Redraw();
	ToolbarSets.Redraw();
};

Editor.prototype._inserthtml = function(text, isFromStyle)
{
	buffer[this.mode].saveHistory();
	
	text = embed2img(addWrap(text,1),true);
	insertNodeAtSelection(document.getElementById(window.aID),text);

	var aew = E._window;
	var aed = E._frame;

	var node = aed.getElementById("_de_temp_element");
	if (node){
		var sel = aew.getSelection();
		var range = aed.createRange();
		range.selectNode(node);
		sel.removeAllRanges();
		sel.addRange(range);
		if (!isFromStyle){
			node.removeAttribute("id");
		}
	}

	PopupSet.Redraw();
	ToolbarSets.Redraw();
};

Editor.prototype._shift_inserthtml = function(text, shift)
{
	text = embed2img(addWrap(text,1));
	buffer[this.mode].saveHistory();
	insertNodeAtSelection(document.getElementById(window.aID),text,false,shift);

	var aew = E._window;
	var aed = E._frame;

	var node = aed.getElementById("_de_temp_element");
	if (node){
		var sel = aew.getSelection();
		var range = aed.createRange();
		range.selectNode(node);
		sel.removeAllRanges();
		sel.addRange(range);
		node.removeAttribute("id");
	}
	PopupSet.Redraw();
	ToolbarSets.Redraw();
};

Editor.prototype.insertHTML = function(text)
{
	if (this.mode=="source"){
		text = text.replace(/</g,"&lt;");
		text = text.replace(/>/g,"&gt;");
	}	
	this._inserthtml(text);
	E.commands.getCommand('Save').execute("no");
};
Editor.prototype.isBrowserNS = function (){
	return browser.NS;
}
Editor.prototype.parentNode = function( nodeTagName )
{
	return this.parentNodeNS(nodeTagName);
};

Editor.prototype.GetType = function()
{
	return this.GetTypeNS();
};

Editor.prototype.getSelectedElement = function()
{
	return this.GetSelectedElementNS();
};

Editor.prototype.GetSelectedElement = function()
{
	return this.GetSelectedElementNS();
};

// Get the selection type (like document.select.type in IE).
Editor.prototype.GetTypeNS = function()
{
		this._Type = 'Text' ;
		var oSel = document.getElementById(window.aID).contentWindow.getSelection();
		if ( oSel && oSel.rangeCount == 1 ) {
			var oRange = oSel.getRangeAt(0) ;
			if ( oRange.startContainer == oRange.endContainer && (oRange.endOffset - oRange.startOffset) == 1 ) {
				this._Type = 'Control' ;
			}
		}
	return this._Type ;
};


// Retrieves the selected element (if any), just in the case that a single
// element (object like and image or a table) is selected.
Editor.prototype.GetSelectedElementNS = function()
{
	if ( this.GetTypeNS() == 'Control' ) {
		var oSel = document.getElementById(window.aID).contentWindow.getSelection() ;
		return oSel.anchorNode.childNodes[ oSel.anchorOffset ] ;
	}
};

// The "nodeTagName" parameter must be Upper Case.
Editor.prototype.parentNodeNS = function( nodeTagName )
{
	var oNode;

	var oContainer = this.GetSelectedElementNS() ;
	if ( ! oContainer ) {
		try {
			oContainer = this._window.getSelection().getRangeAt(0).startContainer ;
		}
		catch(e){}
	}

	while ( oContainer ) {
		if ( oContainer.tagName == nodeTagName ) {
			return oContainer ;
		}
		oContainer = oContainer.parentNode ;
	}
	return null ;
};

Editor.prototype.firstParentNode = function()
{
	var oNode ;

	var oContainer = this.GetSelectedElementNS() ;
	if ( ! oContainer ) {
		try {
			oContainer = this._window.getSelection().getRangeAt(0).startContainer ;
		}
		catch(e){}
	}
	if (oContainer && oContainer.nodeType==3) {
		oContainer = oContainer.parentNode ;
	}

	return oContainer;
};

Editor.prototype.selectNode = function(node)
{
	var sel = this._window.getSelection();
	var range = this._frame.createRange();
	range.selectNode(node);
	sel.removeAllRanges();
	sel.addRange(range);
}

function insertNodeAtSelection (win, html, before,shift)
{
	var sel = win.contentWindow.getSelection();
	if (shift){
		sel.getRangeAt(0).setStart(sel.anchorNode,sel.anchorNode.length-shift);
	}	

	// new code
	if (sel.anchorNode && sel.anchorNode.tagName && sel.anchorNode.tagName.toLowerCase()=="html"){
		sel.getRangeAt(0).selectNodeContents(E._frame.body);
		sel.collapseToStart();
	}
	//  end

	// Deletes the actual selection contents.
	for ( var i = 0 ; i < sel.rangeCount ; i++ ) {
		sel.getRangeAt(i).deleteContents() ;
	}

	var range = sel.getRangeAt(0) ;
	var f = range.createContextualFragment(html) ;
	sel.removeAllRanges();
	var last = f.lastChild;
	range.insertNode(f);

	if (last) {
		range.setEndAfter(last);
		//last.scrollIntoView();
	}

	// Set the cursor after the inserted fragment.
	if (before){
		range.collapse(true);
	} else {
		range.collapse(false);
	}

	sel = win.contentWindow.getSelection();

	sel.addRange(range);

	if (before){
		sel.collapseToStart();
	} else {
		sel.collapseToEnd();
	}	
}


Editor.prototype.GetSelection = function()
{
	return this.GetSelectionNS();
};

Editor.prototype.getSelectedText = function()
{
	return this.GetSelectionNS();
};

Editor.prototype.GetSelectionNS = function()
{
	return this._window.getSelection();
};

Editor.prototype.replaceNodeByText = function(obj)
{
	var txt = this._frame.createTextNode(obj.textContent);
	obj.parentNode.replaceChild(txt,obj);
};

Editor.prototype.doStyles = function()
{
	try {
		if (this._frame) {
			this.Styles			= new Array();
			this.cssText		= new Array();

			var sheets = this._frame.styleSheets;
			if(sheets.length > 1) {
				// loop over each sheet
				for (var x = 0; x < sheets.length; x++) {
					if (sheets[x].href.indexOf(border_css_file)>=0) {
						continue;
					}
					// grab stylesheet rules
					var rules = sheets[x].cssRules;
					if (rules.length > 0) {
						// check each rule
						for(var y = 0; y < rules.length; y++) {
							 sT = rules[y].selectorText;
							 if (!sT || sT.indexOf(".de_")==0) {
								 continue;
							 }
							 if (sT.indexOf("*")==0) {
								 sT=sT.substr(2,sT.length);
							 }
							 if (sT.substr(0,1)==".") {
								sT=sT.substr(1);
								if (sT.indexOf(" ")>0) {
									sT = sT.substring(0,sT.indexOf(" "));
								}
								if (sT.toLowerCase().indexOf("wep_")==0)continue;
								style_twice = false;
								for (var z = 0; z < this.Styles.length; z++){
									if (sT == this.Styles[z]){
										this.cssText[z] = this.cssText[z]+ (this.cssText[z].lastIndexOf(";")==this.cssText[z].length ? "" : ";")+rules[y].style.cssText;
										style_twice = true;
										break;
									}
								}
								if (!style_twice){
									this.Styles[this.Styles.length] = sT;
									this.cssText[this.cssText.length] = rules[y].style.cssText;
								}	
							}
						}
					}
				}
			}
		}
	} catch(e) {}
};

Editor.prototype.isFlash = function(x)
{
	var cn;
	cn = x.getAttribute("class");
	if (cn=="de_flash_file") {
		return true;
	} else {
		return false;
	}
};

Editor.prototype.isMedia = function(x)
{
	var cn;
	cn = x.getAttribute("class");
	if (cn=="de_media_file") {
		return true;
	} else {
		return false;
	}
};

Editor.prototype.checkTags = function(tags)
{
	var tags = tags.split("|");
	var r;
	for (var i=0; i<tags.length;i++){
		switch (tags[i]){
			case "empty":
				if (this.GetSelection()=="") {
					r = OFF;
				} else {
					r = DISABLED;
				}
				break;
			case "text":
				if (this.GetType()=="Control") {
					r = DISABLED;
				} else {
					if (this.GetSelection()!="") {
						r = OFF;
					} else {
						r = DISABLED;
					}
				}
				break;
			case "flash":
				var x = E.GetSelectedElement();
				if (x && this.isFlash(x)) {
					return OFF;
				} else {
					return DISABLED;
				}
				break;
			case "media":
				var x = E.GetSelectedElement();
				if (x && this.isMedia(x)) {
					return OFF;
				} else {
					return DISABLED;
				}
				break;
			case "link":
				if (E.GetType()=="Control") {
					var  x = Selection.parentNode("A");
					if (!x) {
						return DISABLED;
					}
					if (x.href) {
						if(x.href.indexOf("mailto:")==-1) {
							return OFF;
						} else {
							return DISABLED;
						}
					}
				} else if (E.GetSelection()!="") {
					var x = E.GetSelectedElement();
					if (!x) {
						return OFF;
					}
					if (x.href&&x.href.indexOf("mailto:")==-1) {
						return OFF;
					}
				}
				break;

			default:
				var x = this.GetSelectedElement();
				if (!x) {
					x = Selection.parentNode(tags[i]);
				}
				if (!x) {
					return DISABLED;
				}
				if (x && x.getAttribute("class") && (x.getAttribute("class")=="de_flash_file" || x.getAttribute("class")=="de_media_file")) {
					return DISABLED;
				}
				if (x && x.tagName && tags[i].toUpperCase()==x.tagName.toUpperCase()) {
					r=OFF;
				} else {
					r = DISABLED;
				}
				break;
		}
		if (r==OFF) {
			return OFF;
		}
	}
	return DISABLED;
};

Editor.prototype.resetSize = function()
{
	e = parent.document.getElementById(E.InstanceName+"main");
	e.style.width = E.neww;
	e.style.height = E.newh;
};

var checkbegin	= false;
var insideWrap	= false;
var checkend	= false;
var check		= false;
var traverse_end = false;
var ret			= false;
var wrap		= null;

Editor.prototype.walkDOM = function(node)
{
	if (!node) {
		return false;
	}
	traverse_end = false;
	checkbegin	= false;
	checkend	= false;
	ret			= false;
	check		= false;
	insideWrap	= false;
	wrap = null;

	if (E.unlock) {
		return true;
	}
	if (!E.isbegin && !E.isend) {
		return true;
	}
	traverse(this._frame.body,node);
	if ( checkbegin && !checkend ) {
		return true;
	} else {
		return false;
	}
};

function traverse(node,selnode)
{
	if (ret) {
		return;
	}
	if (node && node.id && node.id.substr(0,7)=="de_wrap"){
		insideWrap=true;wrap=node;
	}
	if (node==selnode){
		ret=true;
		return;
	}
	if (node.nodeType == 8) {
		if (node.nodeValue.toLowerCase().indexOf("begineditable")>=0) {
			checkend = false;
			checkbegin = true;
		}
		if (node.nodeValue.toLowerCase().indexOf("endeditable")>=0) {
			checkend = true;
		}
		if (checkbegin && checkend) {
			check=true;
			checkend=false;
			checkbegin=false;
		}
	}
	if (node.childNodes != null) {
		for ( var i=0; i < node.childNodes.length; i++) {
			traverse(node.childNodes.item(i),selnode);
		}
	}
}

function findAllEditable(node)
{
	if (check==true) {
		return;
	}
	if (node.nodeType == 8) {
		if (node.nodeValue.toLowerCase().indexOf("begineditable")>=0) {
			checkbegin = true;
		}
		if (node.nodeValue.toLowerCase().indexOf("endeditable")>=0) {
			checkend = true;
		}
		if (checkbegin && checkend) {
			check=true;
			checkend=false;
			checkbegin=false;
		}
	}
	if (node.childNodes != null) {
		for ( var i=0; i < node.childNodes.length; i++) {
			findAllEditable(node.childNodes.item(i));
		}
	}
}

Editor.prototype.outerHTML = function(el)
{
	var _emptyTags = {
		"IMG":   true,
		"BR":    true,
		"INPUT": true,
		"META":  true,
		"LINK":  true,
		"PARAM": true,
		"EMBED": true,
		"HR":    true
	};

	var attrs = el.attributes;
	var str = "<" + el.tagName;
	for (var i = 0; i < attrs.length; i++){
		if (attrs[i].name.indexOf("_")==0) {
			continue;
		}
		str += " " + attrs[i].name + "=\"" + attrs[i].value + "\"";
	}

	if (_emptyTags[el.tagName]) {
		return str + ">";
	}

	return str + ">" + el.innerHTML + "</" + el.tagName + ">";
};

var Api = new Object() ;

Api.GetParent = function( element, parentTagName )
{
	var e = element.parentNode ;

	while ( e ) {
		if ( e.nodeName == parentTagName ) {
			return e ;
		}

		e = e.parentNode ;
	}
};

Editor.prototype.getTop = function(e)
{
	var nTopPos = e.offsetTop;
	var eParElement = e.offsetParent;
	while (eParElement != null) {
		nTopPos += eParElement.offsetTop;
		eParElement = eParElement.offsetParent;
	}
	return nTopPos;
};

function addFullURI(code)
{
	c1 = /( src=\"?(\S+)\"?)/gi;
	code = code.replace(c1,function(s1,s2,s3){
		if (s3 && s3[0]=="/")	{
			var o = s3.replace(/["]/gi,"");
			return " src="+serverurl + o;
		} else {
			return s2;
		}
	});

	return code;
}


var deEngine = new Replacer();
// preserve script tag
deEngine.addRule("(<script[^>]*?>[\\s\\S]*?</script>)");
// preserve PHP tag
deEngine.addRule("(<\\?[\\s\\S]*?\\?>)");

// trim all space from STYLE defenition
// browser removes style contents if more than 1 space include (eg. style="color:    red;")
function trim_space_from_style(code){
	r = /(style=["'][^"']*?["'])/gi;
	return code.replace(r,function(s1,s2){
			s2 = s2.replace(/(\s*);(\s*)/g,";");
			s2 = s2.replace(/(\s*):(\s*)/g,":");
			return s2;
	});
}

function convert_param_tag_to_xhtml(code) {
	if (useXHTML != 1) {
		// Make param tags <param .... ></param>
		r = /(<param(.*?)>)(?!<\/param>)/gi;
		code = code.replace(r, "$1</param>");
	}
	return code;
}

// unescape unicode char inside href
function unescape_href(code) { 
	// FF replace {,! to %xx inside href=""
	c1 = /(href="([^"]+)")/gi;
	code = code.replace(c1,function(s1,s2,s3){
		var r = /(\%\w+:\w+\%)/gi;
		if (!r.test(s2) && s2.indexOf("%")==-1){
			return unescape(s2);
		}	
		return s2;
	});
	return code;
}

function _de_replace_bookmark(code){
	r = /(&lt;span id="_de_bookmark"&gt;([\s\S]*)&lt;\/span&gt;)/gi;
	code =  code.replace(r,function(s1,s2){
			s2 = s2.replace(/^&lt;span id="_de_bookmark"&gt;/gi,'<span id="_de_bookmark">');
			s2 = s2.replace(/&lt;\/span&gt;$/gi,"</span>");
			return s2;
	});
	return code;
}
// Name: XHTML function

// Info: XHTML function.



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;

_xhtml_parser_aTags = a;



function getXHTML(content) {

	content = content.replace(/<br>/gi,"<br/>");

	content = content.replace(/(<img([^>]+)>)/gi,function(s1,s2){return s2.replace(/\/?>/gi,"/>");});

	content = content.replace(/(<input([^>]+)>)/gi,function(s1,s2){return s2.replace(/\/?>/gi,"/>");});

	content = content.replace(/(<param([^>]+)>)/gi,function(s1,s2){return s2.replace(/\/?>/gi,"/>");});

	content = content.replace(/(<embed([^>]+)>)/gi,function(s1,s2){return s2.replace(/\/?>/gi,"/>");});

	return (content);

}

function removeSafariStyles(){
	var content = E._frame.documentElement.innerHTML;
	if (!content.match(/class=\"Apple-style|class=\"webkit-/ig)) return;
	content = content.replace(/class=\"Apple-style[^"]+\"|class=\"webkit-[^"]+\"/ig, "");
	E.changeHTML(content);
}