
// 主页：http://www.shuziren.com
// QQ:66237000(24小时隐身在线)

var defaultMode=null;
var codeMode = null; //判断编辑区代码模式
var GtextArea = null; //获取隐藏表单里的内容
var btnStyle = 1; //判断鼠标
var gBaseUrl = document.location.protocol + '//' + document.location.host ;

// 浏览器版本检测
var BrowserInfo = new Object() ;
if(navigator.appName == "Microsoft Internet Explorer"){
	BrowserInfo.MajorVer = navigator.appVersion.match(/MSIE (.)/)[1] ;
	BrowserInfo.MinorVer = navigator.appVersion.match(/MSIE .\.(.)/)[1] ;
	BrowserInfo.Is55More = BrowserInfo.MajorVer >= 6 || ( BrowserInfo.MajorVer >= 5 && BrowserInfo.MinorVer >= 5 ) ;
}else{
	BrowserInfo = false;
}

window.onresize = initWidths;

var yToolbars = new Array();  // 工具栏数组

// 当文档完全调入时，进行初始化
var bInitialized = false;

// 工具栏控制
function document.onreadystatechange(){
	//onreadystatechange当对象状态变更时触发。
	if (document.readyState!="complete") return;
		//readyState获取表明对象当前状态的值。interactive交互式的;complete全部的;
	if (bInitialized) return;
	bInitialized = true;

	initHistory();
	initWidths();

	GtextArea = parent.document.getElementsByName(textAreaID)[0];
	if (!config.License){
		shuziren_editor_License.innerHTML = "";
	}
	// IE5.5以下版本只能使用纯文本模式
	if (!BrowserInfo.Is55More){
		config.initMode = "TEXT";
	}

	if (ContentFlag.value=="0") { 
		ContentEdit.value = GtextArea.value;
		ContentLoad.value = GtextArea.value;
		editMode.value = config.initMode;
		ContentFlag.value = "1";
	}

	setMode(editMode.value);
	setTextArea() ;
	shuziren_editor.focus();
}
///////////////////////////////////////
function AttachSubmit() { 
	ContentEdit.value = getHTML();
	GtextArea.value = ContentEdit.value;

	var oForm = GtextArea.form ;
	if (!oForm) return ;

	//表单限制值设定，限制值是102399，考虑到中文设为一半
	var FormLimit = 50000 ;

	//取当前表单的值 
	var TempVar = new String ;
	TempVar = GtextArea.value ;
	if (defaultMode=="TEXT"){
		TempVar = HTMLEncode(TempVar);
		GtextArea.value = TempVar;
	}

	// 未提交成功再次处理时，先赋空值
	for (var i=1;i<parent.document.getElementsByName(textAreaID).length;i++) {
		parent.document.getElementsByName(textAreaID)[i].value = "";
	}

	//如果表单值超过限制，拆成多个对象
	if (TempVar.length > FormLimit) { 
		GtextArea.value = TempVar.substr(0, FormLimit) ;
		TempVar = TempVar.substr(FormLimit) ;

		while (TempVar.length > 0) { 
			var objTEXTAREA = GtextArea.document.createElement("TEXTAREA"); //为指定标签创建一个元素实例。
			objTEXTAREA.name = textAreaID;
			objTEXTAREA.style.display = "none" ;
			objTEXTAREA.value = TempVar.substr(0, FormLimit) ;
			oForm.appendChild(objTEXTAREA) ;

			TempVar = TempVar.substr(FormLimit) ;
		} 
	} 
} 

// 附加Reset事件
function AttachReset() {
	//if (!codeMode) setMode('EDIT');
	if(codeMode){
		shuziren_editor.document.body.innerHTML = ContentLoad.value;
	}else{
		shuziren_editor.document.body.innerText = ContentLoad.value;
	}
}

// 设置所属表单的提交或reset事件
function setTextArea() {
	if (! GtextArea) return ;
	var gForm = GtextArea.form ;
	if (!gForm) return ;
	// 附加submit事件
	gForm.attachEvent("onsubmit", AttachSubmit) ;
	//attachEvent 将指定函数绑定到事件，以便每当该事件在对象上触发时都调用该函数。
	if (! gForm.submitEditor) gForm.submitEditor = new Array() ;
	gForm.submitEditor[gForm.submitEditor.length] = AttachSubmit ;
	if (! gForm.originalSubmit) {
		gForm.originalSubmit = gForm.submit ;
		gForm.submit = function() {
			if (this.submitEditor) {
				for (var i = 0 ; i < this.submitEditor.length ; i++) {
					this.submitEditor[i]() ;
				}
			}
			this.originalSubmit() ;
		}
	}
	// 附加reset事件
	gForm.attachEvent("onreset", AttachReset) ;
	if (! gForm.resetEditor) gForm.resetEditor = new Array() ;
	gForm.resetEditor[gForm.resetEditor.length] = AttachReset ;
	if (! gForm.originalReset) {
		gForm.originalReset = gForm.reset ;
		gForm.reset = function() {
			if (this.resetEditor) {
				for (var i = 0 ; i < this.resetEditor.length ; i++) {
					this.resetEditor[i]() ;
				}
			}
			this.originalReset() ;
		}
	}
}

///////////////////////////////////
function YCancelEvent() {
	event.returnValue=false;
	event.cancelBubble=true;
	return false;
}
//////////////////////////////////////////////////////
function BtnMouseOver() {
	if (event.srcElement.tagName != "IMG") return false;
	var image = event.srcElement;
	var element = image.parentElement;
	
	// Change button look based on current state of image.
	if (image.className == "Ico") element.className = "BtnMouseOverUp";
	else if (image.className == "IcoDown") element.className = "BtnMouseOverDown";

	event.cancelBubble = true;
}

// 鼠标离开
function BtnMouseOut() {
	if (event.srcElement.tagName != "IMG") {
		event.cancelBubble = true;
		return false;
	}

	var image = event.srcElement;
	var element = image.parentElement;
	yRaisedElement = null;
	element.className = "Btn";
	image.className = "Ico";
	event.cancelBubble = true;
}

// 鼠标按下
function BtnMouseDown() {
	if(btnStyle==1){
		btnStyle=2;
		}
	else{
		btnStyle=1;
		}
	if (event.srcElement.tagName != "IMG") {
		event.cancelBubble = true;
		event.returnValue=false;
		return false;
	}

	var image = event.srcElement;
	var element = image.parentElement;

	element.className = "BtnMouseOverDown";
	image.className = "IcoDown";

	event.cancelBubble = true;
	event.returnValue=false;
	return false;
}

// 鼠标放上
function BtnMouseUp() {
	if (event.srcElement.tagName != "IMG") {
		event.cancelBubble = true;
		return false;
	}

	var image = event.srcElement;
	var element = image.parentElement;

　　try{
　　	 if (element.YUSERONCLICK) eval(element.YUSERONCLICK + 'onclick(event)');
　　}
　　catch(e){
　　	 if (element.YUSERONCLICK) eval(element.YUSERONCLICK + 'anonymous()');
　　}

	element.className = "BtnMouseOverUp";
	image.className = "Ico";

	event.cancelBubble = true;
	return false;
}

function initWidths(){
	var i, curr;
	for (i=0; i<document.body.all.length;i++){
		curr=document.body.all[i];
		if (curr.className == "yToolbar"){
			InitTB(curr);
			yToolbars[yToolbars.length] = curr;
		}
	}
}


// 初始化一个工具栏上的按钮
function InitBtn(btn) {
	btn.onmouseover = BtnMouseOver;
	btn.onmouseout = BtnMouseOut;
	btn.onmousedown = BtnMouseDown;
	btn.onmouseup = BtnMouseUp;
	btn.ondragstart = YCancelEvent;
	btn.onselectstart = YCancelEvent;
	btn.onselect = YCancelEvent;
	try{btn.YUSERONCLICK = btn.onclick;}catch(e){}
	btn.onclick = YCancelEvent;
	btn.YINITIALIZED = true;
	return true;
}
///////////////////////////////////////////////////
// 格式化编辑器中的内容
function format(what,opt) {
	if (!passEditMode()) return;
	shuziren_editor.focus();
	if (!history.saved){saveHistory();}
	if (opt=="RemoveFormat") {
		what=opt;
		opt=null;
	}

	if(opt==null) {
		shuziren_editor.document.execCommand(what);
	}else{
		shuziren_editor.document.execCommand(what,"",opt);
	}

	var a_Font = shuziren_editor.document.body.getElementsByTagName("FONT");
	for (var i=0; i<a_Font.length; i++){
		var o_Font = a_Font[i];
		if (o_Font.getAttribute("face") != ""){
			delInFont(o_Font, what);
			setInFont(o_Font, what, opt);
			o_Font.removeAttribute("face");
		}
		if (o_Font.getAttribute("size") != ""){
			delInFont(o_Font, what);
			setInFont(o_Font, what, opt);
			o_Font.removeAttribute("size");
		}
	}

	saveHistory();
	shuziren_editor.focus();
}


function setStyleValue(obj, what, v){
	try{
		switch(what){
		case "fontname":
			obj.style.fontFamily = v;
			break;
		case "fontsize":
			obj.style.fontSize = v;
			var lineh;
			lineh = Math.abs(v) + 10;
			obj.style.lineHeight = lineh + "px";
			break;
		default:
			break;
		}
	}catch(e){}
}

function delInFont(obj, what){
	setStyleValue(obj, what, "");
	var o_Children = obj.children;
	for (var j=0; j<o_Children.length; j++){
		delInFont(o_Children[j], what);

		if ((o_Children[j].tagName=="FONT") || (o_Children[j].tagName=="SPAN")){
			if ((o_Children[j].style.cssText=="")||(o_Children[j].innerHTML=="")){
				o_Children[j].outerHTML = o_Children[j].innerHTML;
			}
		}
	}
}

function setInFont(obj, what, v){
	setStyleValue(obj, what, v);
	var o_Children = obj.children;
	for (var j=0; j<o_Children.length; j++){
		if (o_Children[j].innerHTML!=""){
			setInFont(o_Children[j], what, v);
		}
	}
}

// 检测当前是否允许编辑
function passEditMode() {
	if (defaultMode=="EDIT") return true;
	alert("编辑器需要转换为设计模式后才能使用编辑功能！");
	shuziren_editor.focus();
	return false;
}
//取得编辑器中内容
function getHTML() {
	var html;
	if((defaultMode=="EDIT")||(defaultMode=="VIEW")){
		html = shuziren_editor.document.body.innerHTML;
	}else{
		html = shuziren_editor.document.body.innerText;
	}
	if (defaultMode!="TEXT"){
		var re = new RegExp(gBaseUrl.replace(/\//,"\/"),"gi");
		html = html.replace(re, "");
		if ((html.toLowerCase()=="<p>&nbsp;</p>")||(html.toLowerCase()=="<p></p>")){
			html = "";
		}
	}
	return html;
}
// 在尾部追加内容
function appendHTML(html) {
	if (isModeView()) return false;
	if(defaultMode=="EDIT"){
		shuziren_editor.document.body.innerHTML += html;
	}else{
		shuziren_editor.document.body.innerText += html;
	}
}
// 检测当前是否在预览模式
function isModeView(){
	if (defaultMode=="VIEW"){
		alert("预览时不允许设置编辑区内容。");
		return true;
	}
	return false;
}



function PopulateTB(y) {
	var i, elements, element;
	elements = y.children;
	// children 获取作为对象直接后代的 DHTML 对象的集合。
	for (i=0; i<elements.length; i++) {
		element = elements[i];
		if (element.tagName == "SCRIPT" || element.tagName == "!") continue;
		switch (element.className) {
		case "Btn":
			if (element.YINITIALIZED == null) {
				if (! InitBtn(element)) {
					alert("Problem initializing:" + element.id);
					return false;
				}
			}
			
			element.style.posLeft = y.TBWidth;
			y.TBWidth += element.offsetWidth + 1;
			//offsetWidth 获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的宽度。
			break;
		case "slt_1":
			element.style.posLeft = y.TBWidth;
			y.TBWidth += element.offsetWidth + 2;
			break;
		case "slt_2":
			element.style.posLeft = y.TBWidth + 2;
			y.TBWidth += 5;
			break;
			
		case "slt_3":
			element.style.posLeft = 2;
			y.TBWidth += element.offsetWidth + 7;
			break;
			
		default:
			alert("Invalid class: " + element.className + " on Element: " + element.id + " <" + element.tagName + ">");
			return false;
		}
	}

	y.TBWidth += 1;
	return true;
}


/////////////////////////////////////////////
function InitTB(y) {
	// Set initial size of toolbar to that of the handle
	y.TBWidth = 0;
		
	// Populate the toolbar with its contents
	if (! PopulateTB(y)) return false;
	
	// Set the toolbar width and put in the handle
	y.style.posWidth = y.TBWidth;
	
	return true;
}
///////////////////////////////////////////
// 替换特殊字符
function HTMLEncode(text){
	text = text.replace(/&/g, "&amp;") ;
	text = text.replace(/"/g, "&quot;") ;
	text = text.replace(/</g, "&lt;") ;
	text = text.replace(/>/g, "&gt;") ;
	text = text.replace(/'/g, "&#146;") ;
	text = text.replace(/\ /g,"&nbsp;");
	text = text.replace(/\n/g,"<br>");
	text = text.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;");
	return text;
}

function editorHeight(size){
	var temp = "此功能需要(Microsoft Internet Explorer) MSIE 5.5版本以上的支持！";
	//if(navigator.appName == "Microsoft Internet Explorer"){
	//temp = temp + "\n您当前版本为 " + navigator.appVersion;
	//}
	if (!BrowserInfo.Is55More){
		alert(temp);
		return false;
	}
	for (var i=0; i<parent.frames.length; i++){
		if (parent.frames[i].document==self.document){
			var obj=parent.frames[i].frameElement;
			var height = parseInt(obj.offsetHeight);
			if (height+size>=300){
				obj.height=height+size;
			}
			break;
		}
	}
}
// 设置编辑器的内容
function setHTML(html) {
	if (isModeView()) return false;
	ContentEdit.value = html;
	if(defaultMode=="EDIT"){
		shuziren_editor.document.body.innerHTML = html;//html;
	}else{
		shuziren_editor.document.body.innerText = html;
	}
}
function GetClipboardHTML() {
	var oDiv = document.getElementById("shuziren_editorTempText");
	oDiv.innerHTML = "" ;
	
	var oTextRange = document.body.createTextRange() ;
	oTextRange.moveToElementText(oDiv) ;
	oTextRange.execCommand("Paste") ;
	
	var sData = oDiv.innerHTML ;
	oDiv.innerHTML = "" ;
	
	return sData ;
}

function onPaste() {
	if (defaultMode=="VIEW") return false;
	if (!history.saved){saveHistory();}
	if (defaultMode=="EDIT"){
		if (config.AutoDetectPasteFromWord && BrowserInfo.Is55More) {
			var sHTML = GetClipboardHTML() ;
			var re = /<\w[^>]* class="?MsoNormal"?/gi ;
			if ( re.test(sHTML)){
				if ( confirm( "你要粘贴的内容好象是从Word中拷出来的，是否要先清除Word格式再粘贴？" ) ){
					cleanAndPaste( sHTML ) ;
					saveHistory();
					return false ;
				}
			}
		}else{
			return true ;
		}
	}else{
		shuziren_editor.document.selection.createRange().pasteHTML(HTMLEncode( clipboardData.getData("Text"))) ;
		saveHistory();
		return false;
	}
	
}

function onKeyDown(event){
	var n_KeyCode = event.keyCode;
	var s_Key = String.fromCharCode(n_KeyCode).toUpperCase();
	

	// F2
	if (n_KeyCode==113){
		showBorders();
		return false;
	}
	if (event.ctrlKey){
		// Ctrl+Enter
		if (n_KeyCode==10){
			doSubmit();
			return false;
		}
		// Ctrl++
		if (s_Key=="+"){
			sizeChange(300);
			return false;
		}
		// Ctrl+-
		if (s_Key=="-"){
			sizeChange(-300);
			return false;
		}
		// Ctrl+1
		if (s_Key=="1"){
			setMode("CODE");
			return false;
		}
		// Ctrl+2
		if (s_Key=="2"){
			setMode("EDIT");
			return false;
		}
		// Ctrl+3
		if (s_Key=="3"){
			setMode("TEXT");
			return false;
		}
		// Ctrl+4
		if (s_Key=="4"){
			setMode("VIEW");
			return false;
		}
	}


	switch(defaultMode){
	case "VIEW":
		return true;
		break;
	case "EDIT":
		if (event.ctrlKey){
			// Ctrl+D
			if (s_Key == "D"){
				PasteWord();
				return false;
			}
			// Ctrl+R
			if (s_Key == "R"){
				findReplace();
				return false;
			}
			// Ctrl+Z
			if (s_Key == "Z"){
				goHistory(-1);
				return false;
			}
			// Ctrl+Y
			if (s_Key == "Y"){
				goHistory(1);
				return false;
			}
		}
		break;
	default:
		if (n_KeyCode==13){
			if (!history.saved){saveHistory();}
			history.saved = false;
			var sel = shuziren_editor.document.selection.createRange();
			sel.pasteHTML("<BR>");
			event.cancelBubble = true;
			event.returnValue = false;
			sel.select();
			sel.moveEnd("character", 1);
			sel.moveStart("character", 1);
			sel.collapse(false);
			return false;
		}
		if (event.ctrlKey){
			// Ctrl+B,I,U
			if ((s_Key == "B")||(s_Key == "I")||(s_Key == "U")){
				return false;
			}
			// Ctrl+Z
			if (s_Key == "Z"){
				goHistory(-1);
				return false;
			}
			// Ctrl+Y
			if (s_Key == "Y"){
				goHistory(1);
				return false;
			}
		}
		break;
	}


	if ((n_KeyCode==13)||(n_KeyCode==8)||(n_KeyCode==46)){			//Enter,Backspace,Del
		if (!history.saved){saveHistory();}
		history.saved = false;
	}else if ((n_KeyCode>=33)&&(n_KeyCode<=40)){					//PageUp,PageDown,End,Home,Left,Up,Right,Down
		if (!history.saved){saveHistory();}
	}else if (!event.ctrlKey && s_Key!="A" && s_Key!="F"){			//Ctrl+A,F
		history.saved = false;
	}

	return true;
}

var oResizing = new Object;

function onMouseDown(){
	oResizing.El = null;
	if (shuziren_editor.document.selection.type == "Control") {
		var oControlRange = shuziren_editor.document.selection.createRange();
		oResizing.El = oControlRange(0);
		oResizing.W = oResizing.El.style.width;
		oResizing.H = oResizing.El.style.height;
	}

	if (!history.saved){saveHistory();}
}

function onMouseUp(){
	if (oResizing.El){
		if ((oResizing.El.style.width!=oResizing.W)||(oResizing.El.style.height!=oResizing.H)){
			saveHistory();
		}
	}
}


function doDragEnd(){
	if (!history.saved){saveHistory();}
	var oSelection = shuziren_editor.document.selection.createRange();
	var sRangeType = shuziren_editor.document.selection.type;
	if (sRangeType == "Control") {
		var oControl = oSelection.item(0);
		if (oControl.tagName == "IMG"){
			oControl.src = FullPath2SetPath(oControl.src);
		}
	}
	if (sRangeType == "Text") {
		var els = shuziren_editor.document.body.getElementsByTagName("IMG");
		var oRngTemp = shuziren_editor.document.body.createTextRange();
		for(var i=0;i<els.length;i++){
			oRngTemp.moveToElementText(els(i));
			if (oSelection.inRange(oRngTemp)){
				els(i).src = FullPath2SetPath(els(i).src)
			}
		}
	}

	saveHistory();
	return true;
}

function FullPath2SetPath(url){
	if (url.indexOf("://")<0){return url;}
	var s_SitePath = getSitePath();
	if (url.indexOf(s_SitePath) < 0){return url;}

	return url.substr(s_SitePath.length);
}

function getSitePath(){
	var sSitePath = document.location.protocol + "//" + document.location.host;
	if (sSitePath.substr(sSitePath.length-3) == ":80"){
		sSitePath = sSitePath.substring(0,sSitePath.length-3);
	}
	return sSitePath;
}


// 缩放操作
var defaultZoomSize = 100;
var setZoomSize = new Array(10, 25, 50, 75, 100, 150, 200, 500);
function setZoom(size) {
	shuziren_editor.document.body.runtimeStyle.zoom = size + "%";
	//runtimeStyle 对象设置并获取对象的格式和样式，并且在过程中覆盖已有的格式和样式。
	//runtimeStyle.zoom设置或获取对象的放大比例。
	defaultZoomSize = size;
}
//编辑器类型  代码，设计，文本，预览

function setHTML(html, b_NotSaveHistory) {
	ContentEdit.value = html;
	switch (defaultMode){
	case "CODE":
		shuziren_editor.document.designMode="On";
		shuziren_editor.document.open();
		shuziren_editor.document.write(config.cssHeader);
		shuziren_editor.document.body.innerText=html;
		shuziren_editor.document.body.contentEditable="true";
		shuziren_editor.document.close();
		codeMode=false;
		break;
	case "EDIT":
		shuziren_editor.document.designMode="On";
		shuziren_editor.document.open();
		shuziren_editor.document.write(config.cssHeader+html);
		shuziren_editor.document.body.contentEditable="true";
		shuziren_editor.document.execCommand("2D-Position",true,true);
		shuziren_editor.document.execCommand("MultipleSelection", true, true);
		shuziren_editor.document.execCommand("LiveResize", true, true);
		shuziren_editor.document.close();
		setZoom(defaultZoomSize);
		codeMode=true;
		break;
	case "TEXT":
		shuziren_editor.document.designMode="On";
		shuziren_editor.document.open();
		shuziren_editor.document.write(config.cssHeader);
		shuziren_editor.document.body.innerText=html;
		shuziren_editor.document.body.contentEditable="true";
		shuziren_editor.document.close();
		codeMode=false;
		break;
	case "VIEW":
		shuziren_editor.document.designMode="off";
		shuziren_editor.document.open();
		shuziren_editor.document.write(config.cssHeader+html);
		shuziren_editor.document.body.contentEditable="false";
		shuziren_editor.document.close();
		codeMode=false;
		break;
	}

	shuziren_editor.document.body.onpaste = onPaste ;
	shuziren_editor.document.body.ondragend = new Function("return doDragEnd();");
	shuziren_editor.document.onkeydown = new Function("return onKeyDown(shuziren_editor.event);");
	shuziren_editor.document.oncontextmenu=new Function("return showContextMenu(shuziren_editor.event);");
	shuziren_editor.document.onmousedown = new Function("return onMouseDown();");
	shuziren_editor.document.onmouseup = new Function("return onMouseUp();");

	if ((borderShown != "0")&&codeMode) {
		borderShown = "0";
		showBorders();
	}

	if (!b_NotSaveHistory){
		saveHistory();
	}
}

function setMode(newMode){
	if (newMode!=defaultMode){
		if (!BrowserInfo.Is55More){
			if ((newMode=="CODE") || (newMode=="EDIT") || (newMode=="VIEW")){
				alert("HTML编辑模式需要IE5.5版本以上的支持！");
				return false;
			}
		}

		if (newMode=="TEXT"){
			if (defaultMode==editMode.value){
				if (!confirm("提醒，切换到文本模式将丢失您现在所有的HTML标记，您确定么？")){
					return false;
				}
			}
		}
	var gBody = ""; //编辑器内容		
	switch(defaultMode){
		case "CODE":
			if (newMode=="TEXT"){
				shuziren_editorTempText.innerHTML = shuziren_editor.document.body.innerText;
				gBody = shuziren_editorTempText.innerText;
			}else{
				gBody = shuziren_editor.document.body.innerText;
			}
			break;
			
		case "TEXT":
			gBody = shuziren_editor.document.body.innerText;
			gBody = HTMLEncode(gBody);
			break;
			
		case "EDIT":
			//gBody = shuziren_editor.document.body.innerText;
			//gBody = HTMLEncode(gBody);
			//break;
		case "VIEW":
			if (newMode=="TEXT"){
				gBody = shuziren_editor.document.body.innerText;
			}else{
				gBody = shuziren_editor.document.body.innerHTML;
			}
			break;
			
		default:
			gBody = ContentEdit.value;
			break;
		}
		//尝试按钮按下的显示风格
		try{
			document.all["shuziren_editor_CODE"].className = "BtnOff";
			document.all["shuziren_editor_EDIT"].className = "BtnOff";
			document.all["shuziren_editor_TEXT"].className = "BtnOff";
			document.all["shuziren_editor_VIEW"].className = "BtnOff";
			document.all["shuziren_editor_"+newMode].className = "BtnOn";
			}
		catch(e){
			}
		// 换内容
			//shuziren_editor.document.body.innerHTML = "1312321";
		defaultMode = newMode; //将新编辑类型设置为当前默认编辑类型
		editMode.value = newMode;
		setHTML(gBody);
		disableChildren(shuziren_editor_Toolbar);

	}
	shuziren_editor.focus();
}
function onKeyPress(event){
	if ((defaultMode=="EDIT")||(defaultMode=="VIEW")){
		return true;
	}
	if (event.keyCode==13){ //判断回车键
		var sel = shuziren_editor.document.selection.createRange();
		sel.pasteHTML("<BR>");
		event.cancelBubble = true;
		event.returnValue = false;
		sel.select();
		sel.moveEnd("character", 1);
		sel.moveStart("character", 1);
		sel.collapse(false);
		return false;
	}
}
// 使工具栏无效
function disableChildren(obj){
	if (obj){
		obj.disabled=(!codeMode);
		for (var i=0; i<obj.children.length; i++){
			disableChildren(obj.children[i]);
		}
	}
}
////////////////////////////////
// 显示无模式对话框
function ShowDialog(url, width, height, optValidate) {
	if (optValidate) {
		if (!passEditMode()) return;
	}
	shuziren_editor.focus();
	if (!history.saved){saveHistory();}
	window.showModelessDialog(url, window, "dialogWidth:" + width + "px;dialogHeight:" + height + "px;help:no;scroll:no;status:no");
	//showModalDialog创建一个显示指定 HTML 文档的模式对话框。
	saveHistory();
	shuziren_editor.focus();
}

// 全屏编辑
function Maximize() {
	if (!passEditMode()) return;
	saveHistory();
	window.open("dialog/fullscreen.htm?style="+config.StyleName, 'FullScreen'+textAreaID, 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,fullscreen=yes');
}
// 创建或修改超级链接
function createLink(){
	if (!passEditMode()) return;
	if (shuziren_editor.document.selection.type == "Control") {
		var oControlRange = shuziren_editor.document.selection.createRange();
		//selection.createRange 从当前文本选中区中创建 TextRange 对象，或从控件选中区中创建 controlRange 集合。
		if (oControlRange(0).tagName.toUpperCase() != "IMG") {
			alert("链接只能是图片或文本");
			return;
		}
	}
	
	ShowDialog("dialog/hyperlink.htm", 350, 180, true);
}
// 图片热点链接
function mapEdit(){
	if (!passEditMode()) return;
	saveHistory();
	var b = false;
	if (shuziren_editor.document.selection.type == "Control") {
		var oControlRange = shuziren_editor.document.selection.createRange();
		if (oControlRange(0).tagName.toUpperCase() == "IMG") {
			b = true;
		}
	}
	if (!b){
		alert("热点链接只能作用于图片");
		return;
	}

	window.open("dialog/map.htm", 'mapEdit'+textAreaID, 'toolbar=no,location=no,directories=no,status=not,menubar=no,scrollbars=no,resizable=yes,width=450,height=300');
}

/////////////////////////////////////////////////////
function insert(what) {
	if (!passEditMode()) return;
	shuziren_editor.focus();
	saveHistory();
	var sel = shuziren_editor.document.selection.createRange();

	switch(what){
	case "excel":		// 插入EXCEL表格
		insertHTML("<object classid='clsid:0002E510-0000-0000-C000-000000000046' id='Spreadsheet1' codebase='file:\\Bob\software\office2000\msowc.cab' width='100%' height='250'><param name='HTMLURL' value><param name='HTMLData' value='&lt;html xmlns:x=&quot;urn:schemas-microsoft-com:office:excel&quot;xmlns=&quot;http://www.w3.org/TR/REC-html40&quot;&gt;&lt;head&gt;&lt;style type=&quot;text/css&quot;&gt;&lt;!--tr{mso-height-source:auto;}td{black-space:nowrap;}.wc4590F88{black-space:nowrap;font-family:宋体;mso-number-format:General;font-size:auto;font-weight:auto;font-style:auto;text-decoration:auto;mso-background-source:auto;mso-pattern:auto;mso-color-source:auto;text-align:general;vertical-align:bottom;border-top:none;border-left:none;border-right:none;border-bottom:none;mso-protection:locked;}--&gt;&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;!--[if gte mso 9]&gt;&lt;xml&gt;&lt;x:ExcelWorkbook&gt;&lt;x:ExcelWorksheets&gt;&lt;x:ExcelWorksheet&gt;&lt;x:OWCVersion&gt;9.0.0.2710&lt;/x:OWCVersion&gt;&lt;x:Label Style='border-top:solid .5pt silver;border-left:solid .5pt silver;border-right:solid .5pt silver;border-bottom:solid .5pt silver'&gt;&lt;x:Caption&gt;Microsoft Office Spreadsheet&lt;/x:Caption&gt; &lt;/x:Label&gt;&lt;x:Name&gt;Sheet1&lt;/x:Name&gt;&lt;x:WorksheetOptions&gt;&lt;x:Selected/&gt;&lt;x:Height&gt;7620&lt;/x:Height&gt;&lt;x:Width&gt;15240&lt;/x:Width&gt;&lt;x:TopRowVisible&gt;0&lt;/x:TopRowVisible&gt;&lt;x:LeftColumnVisible&gt;0&lt;/x:LeftColumnVisible&gt; &lt;x:ProtectContents&gt;False&lt;/x:ProtectContents&gt; &lt;x:DefaultRowHeight&gt;210&lt;/x:DefaultRowHeight&gt; &lt;x:StandardWidth&gt;2389&lt;/x:StandardWidth&gt; &lt;/x:WorksheetOptions&gt; &lt;/x:ExcelWorksheet&gt;&lt;/x:ExcelWorksheets&gt; &lt;x:MaxHeight&gt;80%&lt;/x:MaxHeight&gt;&lt;x:MaxWidth&gt;80%&lt;/x:MaxWidth&gt;&lt;/x:ExcelWorkbook&gt;&lt;/xml&gt;&lt;![endif]--&gt;&lt;table class=wc4590F88 x:str&gt;&lt;col width=&quot;56&quot;&gt;&lt;tr height=&quot;14&quot;&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;'> <param name='DataType' value='HTMLDATA'> <param name='AutoFit' value='0'><param name='DisplayColHeaders' value='-1'><param name='DisplayGridlines' value='-1'><param name='DisplayHorizontalScrollBar' value='-1'><param name='DisplayRowHeaders' value='-1'><param name='DisplayTitleBar' value='-1'><param name='DisplayToolbar' value='-1'><param name='DisplayVerticalScrollBar' value='-1'> <param name='EnableAutoCalculate' value='-1'> <param name='EnableEvents' value='-1'><param name='MoveAfterReturn' value='-1'><param name='MoveAfterReturnDirection' value='0'><param name='RightToLeft' value='0'><param name='ViewableRange' value='1:65536'></object>");
		break;
	case "nowdate":		// 插入当前系统日期
		var d = new Date();
		insertHTML(d.toLocaleDateString());
		break;
	case "nowtime":		// 插入当前系统时间
		var d = new Date();
		insertHTML(d.toLocaleTimeString());
		break;
	case "page":		// 插入分页符
		insertHTML("[NextPage]")
		break;
	case "br":			// 插入换行符
		insertHTML("<br>")
		break;
	case "code":		// 代码片段样式
		insertHTML('<table width="95%" style="border: 1px" border="1" align="Center" cellpadding="4" cellspacing="1"  borderColor="#e0e0e0" TABLE-LAYOUT: fixed><tr><td bgcolor="#f6f6f6" style="WORD-WRAP: break-word; height: 25;" valign="top"><font style="color: #b0b0b0;">代码内容</font><br>'+HTMLEncode(sel.text)+'</td></tr></table>');
		break;
	case "quote":		// 引用片段样式
		insertHTML('<table width="95%" style="border: 1px" border="1" align="Center" cellpadding="4" cellspacing="1"  borderColor="#e0e0e0" TABLE-LAYOUT: fixed"><tr><td bgcolor="#f6f6f6" style="WORD-WRAP: break-word; height: 25;" valign="top"><font style="color: #990000;font-weight:bold">引用内容</font><br>'+HTMLEncode(sel.text)+'</td></tr></table>');
		break;
	case "big":			// 字体变大
		insertHTML("<big>" + sel.text + "</big>");
		break;
	case "small":		// 字体变小
		insertHTML("<small>" + sel.text + "</small>");
		break;
	default:
		alert("错误参数调用！");
		break;
	}
	sel=null;
}

// 显示或隐藏指导方针
var borderShown = "no";
function showBorders() {
	if (!passEditMode()) return;
	
	var allForms = shuziren_editor.document.body.getElementsByTagName("FORM");
	var allInputs = shuziren_editor.document.body.getElementsByTagName("INPUT");
	var allTables = shuziren_editor.document.body.getElementsByTagName("TABLE");
	var allLinks = shuziren_editor.document.body.getElementsByTagName("A");

	// 表单
	for (a=0; a < allForms.length; a++) {
		if (borderShown == "no") {
			allForms[a].runtimeStyle.border = "1px dotted #FF0000";
		} else {
			allForms[a].runtimeStyle.cssText = ""
		}
	}

	// Input Hidden类
	for (b=0; b < allInputs.length; b++) {
		if (borderShown == "no") {
			if (allInputs[b].type.toUpperCase() == "HIDDEN") {
				allInputs[b].runtimeStyle.border = "1px dashed #000000";
				allInputs[b].runtimeStyle.width = "15px";
				allInputs[b].runtimeStyle.height = "15px";
				allInputs[b].runtimeStyle.backgroundColor = "#FDADAD";
				allInputs[b].runtimeStyle.color = "#FDADAD";
			}
		} else {
			if (allInputs[b].Type.toUpperCase() == "HIDDEN")
				allInputs[b].runtimeStyle.cssText = "";
		}
	}

	// 表格
	for (i=0; i < allTables.length; i++) {
			if (borderShown == "no") {
				allTables[i].runtimeStyle.border = "1px dotted #BFBFBF";
			} else {
				allTables[i].runtimeStyle.cssText = "";
			}

			allRows = allTables[i].rows
			for (y=0; y < allRows.length; y++) {
			 	allCellsInRow = allRows[y].cells;
					for (x=0; x < allCellsInRow.length; x++) {
						if (borderShown == "no") {
							allCellsInRow[x].runtimeStyle.border = "1px dotted #BFBFBF";
						} else {
							allCellsInRow[x].runtimeStyle.cssText = "";
						}
					}
			}
	}

	// 链接 A
	for (a=0; a < allLinks.length; a++) {
		if (borderShown == "no") {
			if (allLinks[a].href.toUpperCase() == "") {
				allLinks[a].runtimeStyle.border = "1px dashed #000000";
				allLinks[a].runtimeStyle.width = "20px";
				allLinks[a].runtimeStyle.height = "16px";
				allLinks[a].runtimeStyle.backgroundColor = "#FFFFCC";
				allLinks[a].runtimeStyle.color = "#FFFFCC";
			}
		} else {
			allLinks[a].runtimeStyle.cssText = "";
		}
	}

	if (borderShown == "no") {
		borderShown = "yes";
	} else {
		borderShown = "no";
	}

	scrollUp();
}
////////////////////////////////////////////
// 是否选中指定类型的控件
function isControlSelected(tag){
	if (shuziren_editor.document.selection.type == "Control") {
		var oControlRange = shuziren_editor.document.selection.createRange();
		if (oControlRange(0).tagName.toUpperCase() == tag) {
			return true;
		}	
	}
	return false;
}
function cleanAndPaste(html) {
	// Remove all SPAN tags
	html = html.replace(/<\/?SPAN[^>]*>/gi, "" );
	// Remove Class attributes
	html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	// Remove Style attributes
	html = html.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, "<$1$3") ;
	// Remove Lang attributes
	html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	// Remove XML elements and declarations
	html = html.replace(/<\\?\?xml[^>]*>/gi, "") ;
	// Remove Tags with XML namespace declarations: <o:p></o:p>
	html = html.replace(/<\/?\w+:[^>]*>/gi, "") ;
	// Replace the &nbsp;
	html = html.replace(/&nbsp;/, " " );
	// Transform <P> to <DIV>
	var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)","gi") ;	// Different because of a IE 5.0 error
	html = html.replace( re, "<div$2</div>" ) ;
	
	insertHTML(html) ;
}
// 取剪粘板中的HTML格式数据
function GetClipboardHTML() {
	var oDiv = document.getElementById("shuziren_editorTempText")
	oDiv.innerHTML = "" ;
	
	var oTextRange = document.body.createTextRange() ;
	oTextRange.moveToElementText(oDiv) ;
	oTextRange.execCommand("Paste") ;
	
	var sData = oDiv.innerHTML ;
	oDiv.innerHTML = "" ;
	
	return sData ;
}
// 从Word中粘贴，去除格式
function PasteWord(){
	if (!passEditMode()) return;
	shuziren_editor.focus();
	if (!history.saved){saveHistory();}
	if (BrowserInfo.Is55More)
		cleanAndPaste( GetClipboardHTML() ) ;
		//saveHistory();
	else if ( confirm( "此功能要求IE5.5版本以上，你当前的浏览器不支持，是否按常规粘贴进行？" ) )
		format("paste") ;
	shuziren_editor.focus();
}

// 粘贴纯文本
function PasteText(){
	if (!passEditMode()) return;
	shuziren_editor.focus();
	if (!history.saved){saveHistory();}
	var sText = HTMLEncode( clipboardData.getData("Text") ) ;
	insertHTML(sText);
	saveHistory();
	shuziren_editor.focus();
}
// 在当前文档位置插入.
function insertHTML(html) {
	if (isModeView()) return false;
	if (shuziren_editor.document.selection.type.toLowerCase() != "none"){
		shuziren_editor.document.selection.clear() ;
	}
	if (defaultMode!="EDIT"){
		html=HTMLEncode(html);
	}
	shuziren_editor.document.selection.createRange().pasteHTML(html) ; 
}

// 查找替换
function findReplace(){
	ShowDialog('dialog/findreplace.htm', 320, 165, true)
}
// 返回页面最上部
function scrollUp() {
	shuziren_editor.scrollBy(0,0);
}
// 上传文件成功返回原文件名和保存后的文件名，提供接口
function addUploadFile(saveFileName){
	if (gLinkSaveFileName){
		var oSaveFileName = parent.document.getElementsByName(gLinkSaveFileName)[0];
		if (oSaveFileName){
			if (oSaveFileName.value!=""){
				oSaveFileName.value = oSaveFileName.value + "|";
			}
			oSaveFileName.value = oSaveFileName.value + saveFileName;
			oSaveFileName.fireEvent("onchange");
			//.fireEvent触发对象的指定事件。
		}
	}
}

var history = new Object;
history.data = [];
history.position = 0;
history.bookmark = [];
history.saved = false;

function saveHistory() {
	history.saved = true;
	var html = getHTML();
	if (history.data[history.position] != html){
		var nBeginLen = history.data.length;
		var nPopLen = history.data.length - history.position;
		for (var i=1; i<nPopLen; i++){
			history.data.pop();
			history.bookmark.pop();
		}

		history.data[history.data.length] = html;

		if (shuziren_editor.document.selection.type != "Control"){
			try{
				history.bookmark[history.bookmark.length] = shuziren_editor.document.selection.createRange().getBookmark();
			}catch(e){
				history.bookmark[history.bookmark.length] = "";
			}
		} else {
			var oRng = shuziren_editor.document.selection.createRange();
			var el = oRng.item(0);
			history.bookmark[history.bookmark.length] = "[object]|" + el.tagName + "|" + getElementTagIndex(el);
		}

		if (nBeginLen!=0){
			history.position++;
		}
	}
}

function getElementTagIndex(el){
	var els = shuziren_editor.document.body.getElementsByTagName(el.tagName);
	for (var i=0; i<els.length; i++){
		if (els[i]==el){
			return i;
		}
	}
	return null;
}

function initHistory() {
	history.data.length = 0;
	history.bookmark.length = 0;
	history.position = 0;
	history.saved = false;
}

function goHistory(value) {
	if (!history.saved){saveHistory();}
	
	//shuziren_editor.focus();
	// undo
	if (value == -1){
		if (history.position > 0){
			history.position = history.position - 1;
			setHTML(history.data[history.position], true);
			setHistoryCursor();

		}
	// redo
	} else {
		if (history.position < history.data.length -1){
			history.position = history.position + 1;
			setHTML(history.data[history.position], true);
			setHistoryCursor();
		}
	}
	shuziren_editor.focus();
}

function setHistoryCursor() {
	var s_Bookmark = history.bookmark[history.position];
	if (s_Bookmark){
		//shuziren_editor_Toolbar.focus();
		//shuziren_editor_Layout.focus();
		if (s_Bookmark.substring(0,8) != "[object]"){
			r = shuziren_editor.document.body.createTextRange();
			if (r.moveToBookmark(history.bookmark[history.position])){
				//r.duplicate();
				//r.collapse(false);
				r.select();
			}
		}else{
			if (defaultMode=="EDIT"){
				r = shuziren_editor.document.body.createControlRange();
				var a = s_Bookmark.split("|");
				var els = shuziren_editor.document.body.getElementsByTagName(a[1]);
				var el = els[a[2]];
				r.addElement(el);
				r.select();
			}
		}
	}
}


// n_Type  -  0:en; 1:chs; 2:en+chs(1);3,en+chs(2)
function getCount(n_Type){
	var str=getText();
	str = str.replace(/\n/g,"");
	str = str.replace(/\r/g,"");

	var l=str.length;
	var n=0;
    for (var i=0;i<l;i++){
        if (str.charCodeAt(i)<0||str.charCodeAt(i)>255){
			if (n_Type!=0){
				n++;
				if (n_Type==3){
					n++;
				}
			}
		}else{
			if (n_Type!=1){
				n++;
			}
		}
    }
    return n;
}

function getText(){
	shuziren_editor_Temp_HTML.innerHTML = getHTML();
	var s = shuziren_editor_Temp_HTML.innerText;
	return s;
}