
if(navigator.appName == "Microsoft Internet Explorer")
{
    isIE=true;
}
else
{
    isIE=false;
}
var userAgent = navigator.userAgent.toLowerCase();
var is_webtv = userAgent.indexOf('webtv') != -1;
var is_kon = userAgent.indexOf('konqueror') != -1;
var is_mac = userAgent.indexOf('mac') != -1;
var is_saf = userAgent.indexOf('applewebkit') != -1 || navigator.vendor == 'Apple Computer, Inc.';
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko' && !is_saf) && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ns = userAgent.indexOf('compatible') == -1 && userAgent.indexOf('mozilla') != -1 && !is_opera && !is_webtv && !is_saf;
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera && !is_saf && !is_webtv) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
var allowImg=true;
var Content=null;
var ContentId="";
var EditMethod=0;
var EditMode=0;
var initialized=false;
function SetContentId(id)
{
	ContentId=id;
	if(!$$(ContentId+"_iframe")){
		var iframe = document.createElement('iframe');			
		iframe.id = ContentId + '_iframe';
		iframe.style.display='none';
		$$(ContentId).parentNode.insertBefore(iframe,$$(ContentId).parentNode.firstChild);
	}
}
function SetContent(o)
{
	GetContent()=o;
}
function GetContent()
{
	if(EditMode==0)
		return $$(ContentId);
	else
		return $$(ContentId+"_iframe").contentWindow.document.body;
}
function GetEditObj()
{
	return GetContent();
}
function GetEditDoc()
{
	if(EditMode==0)
	{
		return document;
	}
	else{
		return $$(ContentId+"_iframe").contentWindow.document;
	}
}
function SettingButton(setting,oo){
	list=oo.parentNode.getElementsByTagName("input");
	for(i=0;i<list.length;i++)
		list[i].className='';
	oo.className="selected";
}
function SettingEditor(setting,oo){ 
	if((setting && EditMode==1)||(!setting && EditMode==0))
		return;
	SettingButton(setting,oo);
	var oldvalue=GetContentValue();
	if(setting){
	  CheckEditor(1);
	  SetContentValue(UbbEncode(oldvalue));
	}else{
	  CheckEditor(0);
	  SetContentValue(UbbDecode(oldvalue));
	}
} 
function CheckEditor(mode)
{
	EditMode=mode;
	if(EditMode==0){
		$$(ContentId).style.display='';
		$$(ContentId+"_iframe").style.display='none';
	}
	else{
		$$(ContentId).style.display='none';
		var	editdoc=$$(ContentId+"_iframe");
		editdoc.style.display='';
		if(!initialized) {
			editdoc = editdoc.contentWindow.document;
			editdoc.designMode = 'on';
			editdoc.open('text/html', 'replace');
			editdoc.write('');
			editdoc.close();
			editdoc.body.contentEditable = true;
			initialized = true;
			setEditorEvents();
		}		
	}
	setEditorStyle();
}
function checkMessage(){
	if(typeof(ValidateString)   =='function'){
		if(!$$("editor_status"))
			return;
		var thisform=$$(ContentId).form;
		var	args={Value:$$(ContentId).value,IsValid:false};
		ValidateString($$("editor_status"),args);
		
		$$("editor_status").innerHTML=$$("editor_status").innerHTML+"&nbsp;<span>总字数:"+$$(ContentId).value.length+"</span>";

		list=thisform.getElementsByTagName("input");
		if(!args.IsValid){
			for(var i=0;i<list.length;i++){
				if(list[i].type=='submit' || list[i].type=='image' || list[i].name=='submitButton')
					list[i].disabled="true";
			}
		}else{
			for(var i=0;i<list.length;i++){
				if(list[i].type=='submit' || list[i].type=='image' || list[i].name=='submitButton')
					list[i].disabled ="";
			}
		}
	}
}
function setEditorEvents() {
	if(EditMode==1) {
		editdoc=GetEditDoc();
		editwin=GetEditWin();
		if(is_moz || is_opera) {
			editdoc.addEventListener('mouseup', function(e) {setContext(); checkMessage();}, true);
			editdoc.addEventListener('keyup', function(e) {setContext();checkMessage();}, true);
			editwin.addEventListener('focus', function(e) {this.hasfocus = true;}, true);
			editwin.addEventListener('blur', function(e) {checkMessage();this.hasfocus = false;}, true);
			//editwin.addEventListener('keydown', function(e) {ctlent(e);}, true);
		} else {
			editdoc.onmouseup = function(e) {setContext();checkMessage();};
			editdoc.onkeyup = function(e) {setContext();checkMessage();};
			editdoc.onblur = function(e) {checkMessage();};
			/*if(editdoc.attachEvent) {
				editdoc.body.attachEvent("onkeydown", ctlent);
			}*/
		}
	}
	editwin.onfocus = function(e) {this.hasfocus = true;};
	editwin.onblur = function(e) {this.hasfocus = false;};
}
function setContext(cmd) {
	var contextcontrols = new Array('bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist');
	for(var i in contextcontrols) {
		editdoc=GetEditDoc();
		try {
			var state = editdoc.queryCommandState(contextcontrols[i]);
		} catch(e) {
			var state = false;
		}
	}
	$$(ContentId).value=Stringtrim(UbbDecode(GetContentValue()));	
}
 function Stringtrim(tt) {
        re = /^[ ]+|[ ]+$/g;
		tt=tt.replace(re, "");		
		if(tt=='\r\n' || tt=='\r'||tt=='\n')
			return '';
		else
			return tt;
}

function setEditorStyle() {
	var textobj=$$(ContentId);
	if(EditMode==1) {
		var	editbox=$$(ContentId+"_iframe");
		var	editwin=editbox.contentWindow;	
	    var	editdoc=editwin.document;
		if(is_moz || is_opera) {
			for(var i=0;i<document.styleSheets.length;i++)
			{
				if(document.styleSheets[i].href=="/ubbeasy/i5D_editor.css")
					editdoc.createStyleSheet().cssText = document.styleSheets[i].cssText
			}
			try{
				for(var ss = 0; ss < document.styleSheets.length; ss++) {
					if(document.styleSheets[ss].cssRules.length <= 0) {
						continue;
					}
					for(var i = 0; i < document.styleSheets[ss].cssRules.length; i++) {
						if(in_array(document.styleSheets[ss].cssRules[i].selectorText, ['.iframe_editor', '.t_table', '.t_table td'])) {
							var newss = editdoc.createElement('style');
							newss.type = 'text/css';
							newss.innerHTML = document.styleSheets[ss].cssRules[i].cssText + ' p { margin: 0px; }';
							editdoc.documentElement.childNodes[0].appendChild(newss);
							editdoc.body.style.fontSize = document.styleSheets[ss].cssRules[i].style.fontSize;
							editdoc.body.style.fontFamily = document.styleSheets[ss].cssRules[i].style.fontFamily;
						}
					}
				}
			}catch(e){}
			//editbox.style.border = '0px';
			editdoc.body.className = 'iframe_editor';
		} else if(is_ie) {
			for(var i=0;i<document.styleSheets.length;i++)
			{
				if(document.styleSheets[i].href=="/ubbeasy/i5D_editor.css")
					editdoc.createStyleSheet().cssText = document.styleSheets[i].cssText
			}
			editdoc.body.style.border = '0px';
			try
			{
				editdoc.body.addBehavior('#default#userData');
			}
			catch(e){}
		}
		editdoc.body.className='iframe_editor';
		editbox.style.width = textobj.style.width;
		editbox.style.height = textobj.style.height;
	} else {
		var iframe = textobj.parentNode.getElementsByTagName('iframe')[0];
		if(iframe) {
			textobj.style.width = iframe.style.width;
			textobj.style.height = iframe.style.height;
		}
	}
}
function Contentfocus()
{
	if(EditMode==1)
		obj=GetEditWin();
	else
		obj=GetContent();
	if(!obj.hasfocus) {
		obj.focus();
	}
}
function SetContentValue(value)
{
	if(EditMode==0)
		GetContent().value=value;
	else
		GetContent().innerHTML=value;
}
function GetContentValue()
{
	if(EditMode==0)
		return GetContent().value;
	else
		return GetContent().innerHTML;
}
function GetEditWin()
{
	if(EditMode==0)
		return window;
	else
		return $$(ContentId+"_iframe").contentWindow;
}
function GetEditDoc()
{
	if(EditMode==0)
		return document;
	else
		return $$(ContentId+"_iframe").contentWindow.document;
}
function Methodchange(o){
	EditMethod=o
}
function showfileframe(type)
{
        var demo=$$("FP");
        demo.innerHTML="";        
}
var Tcolor=null;
function H(T,I){
	if(I==0){
		Tcolor=null;
		S(false,I)
		return;
	}
	Tcolor=setTimeout("S(false,'"+I+"')",T)
}
function S(B,I){
	if(Tcolor!=null)
		clearTimeout(Tcolor);
	if(B)
		$$(I).style.display="";
	else 
		$$(I).style.display="none";
}
/*------------------ UBB BUTTON CLICK ----------------*/
function about(){
	alert("easyUBB编辑器\n作者:FEIHAN\n版权所有:5D.cn 2006\n浏览器: "+window.navigator.appName+"\n其他信息: "+window.navigator.appVersion);
}
function isSelectText(){
    if(getSel()) 
		return true;
	else
		return false;
}

function AddText(txt) {
	if(EditMode==0){
		var obj = GetContent();
		selection = obj.selection;
		Contentfocus();
		if(!isUndefined(obj.selectionStart)) {
			var opn = obj.selectionStart + 0;
			tvalue=GetContentValue();
			tvalue=tvalue.substr(0, obj.selectionStart) + txt + tvalue.substr(obj.selectionEnd);
			SetContentValue(tvalue); 
		} else if(selection && selection.createRange) {
			var sel = selection.createRange();
			sel.text = txt;
		} else {		
			SetContentValue(GetContentValue()+txt);
		}
	}
	else{
		insertText(txt);
	}
	Contentfocus();
}
function R(txt1,txt2,P){
		var obj = GetContent();
		selection = GetEditDoc().selection;
		Contentfocus();
		//var start=0;
		if(document.all)
		{
			var sel = selection.createRange();
			AddTxt=txt1+"\r\n";
			list=sel.text.split("\r\n");
			if(list.length==0)
				list=sel.text.split("<br />");
			for(i=0;i<list.length;i++)
			{
				AddTxt+=P+list[i]+"\r\n";
			}
			AddTxt+=txt2;
			sel.text = AddTxt;
		}
		else{
			if(!isUndefined(obj.selectionStart)) {
				var opn = obj.selectionStart + 0;
				AddTxt=txt1+"\r\n";
				tvalue=GetContentValue();
				list=tvalue.substr(obj.selectionStart,obj.selectionEnd-obj.selectionStart).split("\r\n");
				if(list.length==0)
					list=tvalue.substr(obj.selectionStart,obj.selectionEnd-obj.selectionStart).split("<br />");
				for(i=0;i<list.length;i++)
				{
					AddTxt+=P+list[i]+"\r\n";
				}
				AddTxt+=txt2;
				tvalue= tvalue.substr(0, obj.selectionStart) + AddTxt + tvalue.substr(obj.selectionEnd);
				SetContentValue(tvalue); 
				//obj.selectionStart=opn;
				//obj.selectionEnd=opn;
			}
		}
	Contentfocus();
}
function ReplaceText(txt1,txt2)
{
	var obj = GetContent();
	selection = GetEditDoc().selection;
	Contentfocus();
	if(document.all){
		var sel = selection.createRange();
		insertText(txt1 + sel.text + txt2)
	}
	else{
		sel=getSel();
		if(sel){
			//sel=sel.replace('<[\s\S]*?>',"")
			insertText(txt1+sel+txt2);
		}
	}
	Contentfocus();
}
function showPrompt(dialogtxt, defaultval) {
	return trim(prompt(dialogtxt, defaultval) + '');
}
function churl(op){
	Contentfocus();
	if(EditMode==1){
			if(is_moz || is_opera) {
				var url = showPrompt("请输入链接的地址:", 'http://');
				if((url = verifyPrompt(url)) !== false) {
					if(getSel()) {
						applyFormat('unlink');
						applyFormat('createlink', is_ie, (isUndefined(url) ? true : url));
					} else {
						applyFormat('removeformat');
						insertText('<a href="' + url + '">' + url + '</a>');
					}
				}
			} else {
				applyFormat('createlink', is_ie, (isUndefined(url) ? true : url));
			}
			return ;
	}
	if (isSelectText()) 
	{
		ReplaceText("[url=请输入连接地址]","[/url]")		
    }
    else
    {  
		if(op==1)
		{
				AddTxt="[url=请输入连接地址]连接[/url]";
				AddText(AddTxt);
		}
		else
		{
			var txt1=window.prompt("请输入链接的标题","");
			var txt2=window.prompt("请输入链接的URL地址","http://");
			if(txt2!=null)
			{
				if(txt1=="")
				{
						AddTxt="[url]"+txt2 +"[/url]";
						AddText(AddTxt);				
				}
				else
				{
						AddTxt="[url=" + txt2 + "]"+txt1 + "[/url]";
						AddText(AddTxt);
				}
			}
		}
    }
}
function AddUBB(what,value)
{
	Contentfocus();
	if(EditMode==1){
		InsertHtmlTag(what,value);
		return ;
	}
	if (isSelectText()) 
	{
		ReplaceText("["+what+"]"+value,"[/"+what+"]");
    }
    else
    {
        AddTxt="["+what+"]"+value;
        AddText(AddTxt+"[/"+what+"]");
   }
}
function ubbFormat(what,about,op) 
{	
    Contentfocus();
	if(EditMode==1){
		InsertHtmlTag(what);
		return ;
	}
	if (isSelectText()){
		ReplaceText("["+what+"]","[/"+what+"]")
    }
    else
    {
		if(op==1)
		{
			AddTxt="["+what+"]";
			AddText(AddTxt+"[/"+what+"]");  
		}
		else
		{
			if(about.length!=0)
				txt=window.prompt("请输入"+about+"内容","");  
			else 
				txt="";
			if (txt!=null) {           
					AddTxt="["+what+"]"+txt;
					AddText(AddTxt+"[/"+what+"]");
			}
		}
    } 
}
function verifyPrompt(str) {
	if(in_array(str, ['http://', 'null', 'undefined', 'false', '']) || str == null || str == false) {
		return false;
	} else {
		return str;
	}
}
function InsertHtmlTag(what,arg){
	var cmd="";
	switch(what.toLowerCase()){
		case "google":
			if(is_moz || is_opera) {
				var url = 'http://www.google.com/search?q=';
				if((url = verifyPrompt(url)) !== false) {
					if(getSel()) {
						applyFormat('unlink');
						applyFormat('createlink', is_ie, (isUndefined(url) ? true : url));
					} else {
						applyFormat('removeformat');
						ReplaceText('<a href="http://www.google.com/search?q=" TARGET=_blank >','</a>');
					}
				}
			} else {
				applyFormat('createlink', false, "http://www.google.com/search?q=");
			}
			break;
		case "email":
			var email = showPrompt("请输入此链接的邮箱地址:", '');
			email = verifyPrompt(email);
			if(email === false) {
				applyFormat('unlink');
			} else {
				var selection = getSel();
				if(selection == '') {
					applyFormat('removeformat');
				}
				insertText('<a href="mailto:' + email + '">' + email + '</a>', (selection ? true : false));
			}
			break;
		case "b":
			cmd="bold";
			applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
			break;
		case "img":
			var selection = getSel();
			if(selection == '') {
					applyFormat('removeformat');
			}
			if(!allowImg)
				insertText('<A href="'+arg+'" target=_BLANK><IMG alt=点击查看大图 src="http://art.5d.cn/Images/ISPIC.JPG" border=0>[点击查看大图]</A>', (selection ? true : false));
			else
				insertText('<img src="'+arg+'" />', (selection ? true : false));
			break;
		case "i":
			cmd="italic";
			applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
			break;
		case "u":
			cmd="underline";
			applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
			break;
		case "left":
			cmd="justifyleft";
			applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
			break;
		case "center":
			cmd="justifycenter";
			applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
			break;
		case "right":
			cmd="justifyright";
			applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
			break;
		case "insertorderedlist":
		case "insertunorderedlist":
			cmd=what;
			if(is_moz && in_array(cmd, ['insertorderedlist', 'insertunorderedlist']) && getSel() == '') {
				applyFormat('removeformat');
			}
			try {
				var ret = applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
			} catch(e) {
				var ret = false;
			}
			break;
		case "quote":
			var selection = getSel();
			if(selection == '') {
					applyFormat('removeformat');
			}
			insertText('<blockquote>引用:<hr>'+selection+'<hr></blockquote>', (selection ? true : false));
			break;

	}
	Contentfocus();
}

function ubbInsert(what,about,op) 
{
	Contentfocus();
	if(EditMode==1){
		InsertHtmlTag(what);
		return ;
	}
	if (isSelectText()) 
	{
		ReplaceText("["+what+"]","[/"+what+"]")
    }
    else
    {
		if(op==1)
		{
			AddTxt="["+what+"]";
			AddText(AddTxt+"[/"+what+"]");
		}
		else{
				txt=window.prompt("请输入"+about+"内容","");     
				if (txt!=null) {           
						AddTxt="["+what+"]"+txt;
						AddText(AddTxt+"[/"+what+"]");
				}   
			}
    } 
}
function L(tt,op) {
	Contentfocus();
	if(EditMode==1)
	{
		if(tt==""){
			InsertHtmlTag("insertunorderedlist");
			//R("<UL TYPE=SQUARE>","</OL>")
		}else{
			InsertHtmlTag("insertorderedlist");
			//R("<OL TYPE=1>","</UL>")
		}
		return ;
	}
	if (isSelectText()) 
	{
		R("[list"+tt+"]","[/list]","[*]")
    }
    else
    {   if(op==1)
		{
			AddTxt="[list"+tt+"][*][/list]";
			AddText(AddTxt);
		}
		else
		{
			txt=window.prompt("请输入内容",""); 
			if (txt!=null)
			{             
				AddTxt="[list"+tt+"][*]"+txt+"[/list]";
				AddText(AddTxt);
			}
		}
    }
}
function chsize(size,op) {
	Contentfocus();
	if (isSelectText()) 
	{
		if(EditMode==0)	{
			ReplaceText("[size=" + size + "]","[/size]")
		}else{
			ReplaceText("<span style=\"font-size:"+size+"px\">","</span>")
		}		
    }
    else
    {   if(op==1)
		{
			AddTxt="[size="+size+"]";
			AddText(AddTxt+"[/size]");
		}
		else
		{
			txt=window.prompt("请输入内容",""); 
			if (txt!=null)
			{             
				if(EditMode==0){
					AddTxt="[size="+size+"]"+txt+"[/size]";
				}else{
					AddTxt="<span style=\"font-size:"+size+"px\">"+txt+"</span>";
				}
				AddText(AddTxt);
			}
		}
    }
}
function chfont(font,op) {
	Contentfocus();
	if (isSelectText()) 
	{
		if(EditMode==0)	{
			ReplaceText( "[font=" + font +"]","[/font]")
		}
    }
    else
    {    
		if(op==1)
		{ 
			AddTxt="[font=" + font + "]";
			AddText(AddTxt+"[/font]");
		}
		else
		{
			txt=window.prompt("请输入内容","");
			if (txt!=null)
			{             
				AddTxt="[font=" + font + "]"+txt;
				AddText(AddTxt+"[/font]");
			}  						
		}
    }  
}

function chcolor(color,op) {
	Contentfocus();
	if (isSelectText()) 
	{
		if(EditMode==0)	
			ReplaceText("[color=" + color +"]","[/color]")
		else
			ReplaceText("<font color=" + color +">","</font>")			
    }else{  
		if(op==1){
			AddTxt="[color=" + color + "]";
			AddText(AddTxt+"[/color]");
		}
		else{
			txt=window.prompt("请输入内容","");
			if(txt!=null)
			{
				if(EditMode==0){
					AddTxt="[color=" + color + "]"+txt+"[/color]";
				}else{
					AddTxt="<font color=" + color +">"+txt+"</font>";
				}
				AddText(AddTxt);
			}
		}
    }
}

function chFace(what)
{
	Contentfocus();
	if(EditMode==1){
		insertText(htmlFace(what));
		return;
	}
	if(isSelectText()){
		insertText(what);
	}else{
		AddText(what);
	}
}

function AddDownLoad(value)
{
	Contentfocus();
	if(EditMode==1){
		ReplaceText("<a href='"+value+"' target='_blank'>下载说明","</a>")
		return ;
	}	
	if (isSelectText()){
		ReplaceText("[download="+value+"]下载说明","[/download]")

    }
   	else
	{
		AddTxt="[download="+value+"]下载说明";
		AddText(AddTxt+"[/download]");
    }
}
function chDownLoad(op) 
{
	Contentfocus();
	if (isSelectText()) {
		ReplaceText("[download=这里输入连接地址]","[/download]")
    }else{ 
		if(op==1){
			AddTxt="[download=文件的地址]下载说明";
			AddText(AddTxt+"[/download]");
		}
		else{
			var txt1=window.prompt("请输入下载说明","");
			var txt2=window.prompt("请输入下载地址地址","http://");
			if(txt2!=null){
				if(txt1==""){
					AddTxt="[download]"+txt2;
					AddText(AddTxt+"[/download]");			
				}
				else{
					AddTxt="[download=" + txt2 + "]"+txt1;
					AddText(AddTxt+"[/download]");
				}
			}
		}
    }
}
/*------------------ UBB BUTTON CLICK ----------------*/
/*    Shared Function         */
function $$(element) {
  return document.getElementById(element);
}
function in_array(needle, haystack) {
	if(typeof needle == 'string') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}
function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}
/*    Select Function     */
function getSel() {
	if(EditMode==1) {
		if(is_moz || is_opera) {
			selection = GetEditWin().getSelection();
			Contentfocus();//checkFocus();
			range = selection ? selection.getRangeAt(0) : editdoc.createRange();
			return readNodes(range.cloneContents(), false);
		} else {
			var range = GetEditDoc().selection.createRange();
			if(range.htmlText && range.text) {
				return range.htmlText;
			} else {
				var htmltext = '';
				for(var i = 0; i < range.length; i++) {
					htmltext += range.item(i).outerHTML;
				}
				return htmltext;
			}
		}
	} else {
		if(!isUndefined(GetContent().selectionStart)) {
			return GetContent().value.substr(GetContent().selectionStart, GetContent().selectionEnd - GetContent().selectionStart);
		} else if(document.selection && document.selection.createRange) {
			return document.selection.createRange().text;
		} else if(window.getSelection) {
			return window.getSelection() + '';
		} else {
			return false;
		}
	}
}
function insertNodeAtSelection(text) {
	Contentfocus();

	var sel = GetEditWin().getSelection();
	var range = sel ? sel.getRangeAt(0) : GetEditDoc().createRange();
	sel.removeAllRanges();
	range.deleteContents();

	var node = range.startContainer;
	var pos = range.startOffset;

	switch(node.nodeType) {
		case Node.ELEMENT_NODE:
			if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
				selNode = text.firstChild;
			} else {
				selNode = text;
			}
			node.insertBefore(text, node.childNodes[pos]);
			add_range(selNode);
			break;

		case Node.TEXT_NODE:
			if(text.nodeType == Node.TEXT_NODE) {
				var text_length = pos + text.length;
				node.insertData(pos, text.data);
				range = editdoc.createRange();
				range.setEnd(node, text_length);
				range.setStart(node, text_length);
				sel.addRange(range);
			} else {
				node = node.splitText(pos);
				var selNode;
				if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
					selNode = text.firstChild;
				} else {
					selNode = text;
				}
				node.parentNode.insertBefore(text, node);
				add_range(selNode);
			}
			break;
	}
}
function add_range(node) {
	Contentfocus();
	var sel = GetEditWin().getSelection();
	var range = GetEditDoc().createRange();
	range.selectNodeContents(node);
	sel.removeAllRanges();
	sel.addRange(range);
}
function applyFormat(cmd, dialog, argument) {
	if(EditMode==1) {
		GetEditDoc().execCommand(cmd, (isUndefined(dialog) ? false : dialog), (isUndefined(argument) ? true : argument));
		return false;
	}	
}
function strlen(str) {
	return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
function mb_strlen(str) {
	var len = 0;
	for(var i = 0; i < str.length; i++) {
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? 2 : 1;
	}
	return len;
}
function insertText(text, movestart, moveend, select) {
	if(EditMode==1) {
		if(is_moz || is_opera) {
			applyFormat('removeformat');
			var fragment = GetEditDoc().createDocumentFragment();
			var holder = GetEditDoc().createElement('span');
			holder.innerHTML = text;

			while(holder.firstChild) {
				fragment.appendChild(holder.firstChild);
			}
			insertNodeAtSelection(fragment);
		} else {
			Contentfocus();
			if(!isUndefined(GetEditDoc().selection) && GetEditDoc().selection.type != 'Text' && GetEditDoc().selection.type != 'None') {
				movestart = false;
				GetEditDoc().selection.clear();
			}

			var sel = GetEditDoc().selection.createRange();

			sel.pasteHTML(text);

			if(text.indexOf('\n') == -1) {
				if(!isUndefined(movestart)) {
					sel.moveStart('character', -strlen(text) + movestart);
					sel.moveEnd('character', -moveend);
				} else if(movestart != false) {
					sel.moveStart('character', -strlen(text));
				}
				if(!isUndefined(select) && select) {
					sel.select();
				}
			}
		}
	} else {
		Contentfocus();
		var	editdoc=GetContent();
		if(!isUndefined(editdoc.selectionStart)) {
			var opn = editdoc.selectionStart + 0;
			editdoc.value = editdoc.value.substr(0, editdoc.selectionStart) + text + editdoc.value.substr(editdoc.selectionEnd);
			if(!isUndefined(movestart)) {
				editdoc.selectionStart = opn + movestart;
				editdoc.selectionEnd = opn + strlen(text) - moveend;
			} else if(movestart !== false) {
				editdoc.selectionStart = opn;
				editdoc.selectionEnd = opn + strlen(text);
			}
		} else if(document.selection && document.selection.createRange) {
			
			var sel = document.selection.createRange();
			sel.text = text.replace(/\r?\n/g, '\r\n');

			if(!isUndefined(movestart)) {
				sel.moveStart('character', -strlen(text) +movestart);
				sel.moveEnd('character', -moveend);
			} else if(movestart !== false) {
				sel.moveStart('character', -strlen(text));
			}
			sel.select();
		} else {
			GetContent().value += text;
		}
	}
	Contentfocus();
}
function readNodes(root, toptag) {
	var html = "";
	var moz_check = /_moz/i;
	switch(root.nodeType) {
		case Node.ELEMENT_NODE:
		case Node.DOCUMENT_FRAGMENT_NODE:
			var closed;
			if(toptag) {
				closed = !root.hasChildNodes();
				html = '<' + root.tagName.toLowerCase();
				var attr = root.attributes;
				for(var i = 0; i < attr.length; ++i) {
					var a = attr.item(i);
					if(!a.specified || a.name.match(moz_check) || a.value.match(moz_check)) {
						continue;
					}
					html += " " + a.name.toLowerCase() + '="' + a.value + '"';
				}
				html += closed ? " />" : ">";
			}
			for(var i = root.firstChild; i; i = i.nextSibling) {
				html += readNodes(i, true);
			}
			if(toptag && !closed) {
				html += "</" + root.tagName.toLowerCase() + ">";
			}
			break;

		case Node.TEXT_NODE:
			html = htmlspecialchars(root.data);
			break;
	}
	return html;
}
function htmlspecialchars(str) {
	return preg_replace([(is_mac && is_ie ? '&' : '&(?!#[0-9]+;)'), '<', '>', '"'], ['&amp;', '&lt;', '&gt;', '&quot;'], str);
}