// 当前模式
var sCurrMode = null;
var bEditMode = null;
// 链接对象
var oLinkField = null;

// 表格相关全局变量
var selectedTD
var selectedTR
var selectedTBODY
var selectedTable


// 浏览器版本检测
var BrowserInfo = new Object() ;
BrowserInfo.MajorVer = navigator.appVersion.match(/MSIE (.)/)[1] ;
BrowserInfo.MinorVer = navigator.appVersion.match(/MSIE .\.(.)/)[1] ;
BrowserInfo.IsIE55OrMore = BrowserInfo.MajorVer >= 6 || ( BrowserInfo.MajorVer >= 5 && BrowserInfo.MinorVer >= 5 ) ;

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

// 当文档完全调入时，进行初始化
var bInitialized = false;
function document.onreadystatechange(){
	if (document.readyState!="complete") return;
	if (bInitialized) return;
	bInitialized = true;

	var i, s, 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;
		}
	}

	oLinkField = parent.document.getElementsByName(sLinkFieldName)[0];
	if (!config.License){
		try{
			HtmlEdit_License.innerHTML = "Wangren.Net";
		}
		catch(e){
		}
	}

	// IE5.5以下版本只能使用纯文本模式
	if (!BrowserInfo.IsIE55OrMore){
		config.InitMode = "TEXT";
	}

	if (ContentFlag.value=="0") {
		ContentEdit.value = oLinkField.value;
		ContentLoad.value = oLinkField.value;
		ModeEdit.value = config.InitMode;
		ContentFlag.value = "1";
	}

	setMode(ModeEdit.value);
	setLinkedField() ;
}

// 菜单常量
var sMenuHr="<tr><td align=center valign=middle height=2><TABLE border=0 cellpadding=0 cellspacing=0 width=128 height=2><tr><td height=1 class=HrShadow><\/td><\/tr><tr><td height=1 class=HrHighLight><\/td><\/tr><\/TABLE><\/td><\/tr>";
var sMenu1="<TABLE border=0 cellpadding=0 cellspacing=0 class=Menu width=150><tr><td width=18 valign=Top align=center style='background:url(../../Images/button/MenuLeft.gif)'><\/td><td width=132 class=RightBg><TABLE border=0 cellpadding=0 cellspacing=0>";
var sMenu2="<\/TABLE><\/td><\/tr><\/TABLE>";



// 初始化一个正常按纽
function InitBtn(btn) {
	btn.onmouseover = BtnMouseOver;
	btn.onmouseout = BtnMouseOut;
	btn.onmousedown = BtnMouseDown;
	btn.onmouseup = BtnMouseUp;
	btn.ondragstart = YCancelEvent;
	btn.onselectstart = YCancelEvent;
	btn.onselect = YCancelEvent;
	btn.YUSERONCLICK = btn.onclick;
	btn.onclick = YCancelEvent;
	btn.YINITIALIZED = true;
	return true;
}

// 初始化一个菜单栏上的按钮
function InitMenuBtn(btn) {
	btn.onmouseover = MenuBtnMouseOver;
	btn.onmouseout = MenuBtnMouseOut;
	btn.onmousedown = MenuBtnMouseDown;
	btn.onmouseup = MenuBtnMouseUp;
	btn.ondragstart = YCancelEvent;
	btn.onselectstart = YCancelEvent;
	btn.onselect = YCancelEvent;
	btn.YUSERONCLICK = btn.onclick;
	btn.onclick = YCancelEvent;
	btn.YINITIALIZED = true;
	return true;
}

//Initialize a toolbar.
function InitTB(y) {
	y.TBWidth = 0;
	if (! PopulateTB(y)) return false;
	y.style.posWidth = y.TBWidth;
	return true;
}

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;
	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 (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;
        if (navigator.appVersion.match(/8./i)=='8.'){
            if (element.YUSERONCLICK) eval(element.YUSERONCLICK + 'onclick(event)');
        }else{
         if(document.documentMode === 5) {
            if (element.YUSERONCLICK) eval(element.YUSERONCLICK + 'onclick(event)');
          }else{
            if (element.YUSERONCLICK) eval(element.YUSERONCLICK + 'anonymous()');
          }
        }
	element.className = "BtnMouseOverUp";
	image.className = "Ico";
	event.cancelBubble = true;
	return false;
}

//菜单按纽
function MenuBtnMouseOver() {
	if (event.srcElement.tagName != "IMG") return false;
	var image = event.srcElement;
	var element = image.parentElement;
	if (image.className == "MenuIco") element.className = "MenuBtnMouseOverUp";
	else if (image.className == "MenuIcoDown") element.className = "MenuBtnMouseOverDown";
	event.cancelBubble = true;
}
function MenuBtnMouseOut() {
	if (event.srcElement.tagName != "IMG") {
		event.cancelBubble = true;
		return false;
	}
	var image = event.srcElement;
	var element = image.parentElement;
	yRaisedElement = null;
	element.className = "MenuBtn";
	image.className = "MenuIco";
	event.cancelBubble = true;
}
function MenuBtnMouseDown() {
	if (event.srcElement.tagName != "IMG") {
		event.cancelBubble = true;
		event.returnValue=false;
		return false;
	}
	var image = event.srcElement;
	var element = image.parentElement;
	element.className = "MenuBtnMouseOverDown";
	image.className = "MenuIcoDown";
	event.cancelBubble = true;
	event.returnValue=false;
	return false;
}
function MenuBtnMouseUp() {
	if (event.srcElement.tagName != "IMG") {
		event.cancelBubble = true;
		return false;
	}
	var image = event.srcElement;
	var element = image.parentElement;
	if (element.YUSERONCLICK) eval(element.YUSERONCLICK + "anonymous()");
	element.className = "MenuBtnMouseOverUp";
	image.className = "MenuIco";
	event.cancelBubble = true;
	return false;
}



// Populate a toolbar with the elements within it
function PopulateTB(y) {
	var i, elements, element;

	// Iterate through all the top-level elements in the toolbar
	elements = y.children;
	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;
			break;

		case "MenuBtn":
			if (element.YINITIALIZED == null) {
				if (! InitMenuBtn(element)) {
					alert("Problem initializing:" + element.id);
					return false;
				}
			}
			element.style.posLeft = y.TBWidth;
			y.TBWidth += element.offsetWidth + 1;
			break;

		case "TBGen":
			element.style.posLeft = y.TBWidth;
			y.TBWidth += element.offsetWidth + 1;
			break;

		case "TBSep":
			element.style.posLeft = y.TBWidth + 2;
			y.TBWidth += 5;
			break;

		case "TBHandle":
			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;
}


// 设置所属表单的提交或reset事件
function setLinkedField() {
	if (! oLinkField) return ;
	var oForm = oLinkField.form ;
	if (!oForm) return ;
	// 附加submit事件
	oForm.attachEvent("onsubmit", AttachSubmit) ;
	if (! oForm.doneAutoRemote) oForm.doneAutoRemote = 0 ;

	if (! oForm.submitEditor) oForm.submitEditor = new Array() ;
	oForm.submitEditor[oForm.submitEditor.length] = AttachSubmit ;
	if (! oForm.originalSubmit) {
		oForm.originalSubmit = oForm.submit ;
		oForm.submit = function() {
			if (this.submitEditor) {
				for (var i = 0 ; i < this.submitEditor.length ; i++) {
					this.submitEditor[i]() ;
				}
			}
			this.originalSubmit() ;
		}
	}
	// 附加reset事件
	oForm.attachEvent("onreset", AttachReset) ;
	if (! oForm.resetEditor) oForm.resetEditor = new Array() ;
	oForm.resetEditor[oForm.resetEditor.length] = AttachReset ;
	if (! oForm.originalReset) {
		oForm.originalReset = oForm.reset ;
		oForm.reset = function() {
			if (this.resetEditor) {
				for (var i = 0 ; i < this.resetEditor.length ; i++) {
					this.resetEditor[i]() ;
				}
			}
			this.originalReset() ;
		}
	}
}

// 附加submit提交事件,大表单数据提交,保存HtmlEdit中的内容
var bDoneAutoRemote = false;
function AttachSubmit() {
	var oForm = oLinkField.form ;
	if (!oForm) return;
		var html = getHTML();
		ContentEdit.value = html;
		if (sCurrMode=="TEXT"){
			html = HTMLEncode(html);
		}
		splitTextField(oLinkField, html);
}

// 提交表单
function doSubmit(){
	var oForm = oLinkField.form ;
	if (!oForm) return ;
	oForm.submit();
}

// 附加Reset事件
function AttachReset() {
	if(bEditMode){
		HtmlEdit.document.body.innerHTML = ContentLoad.value;
	}else{
		HtmlEdit.document.body.innerText = ContentLoad.value;
	}
}

// 显示帮助
function onHelp(){
	ShowDialog('dialog/help.htm','400','300');
	return false;
}

// 粘贴时自动检测是否来源于Word格式
function onPaste() {
	if (sCurrMode=="VIEW") return false;

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

// 快捷键
function onKeyDown(event){
	var key = String.fromCharCode(event.keyCode).toUpperCase();

	// F2:显示或隐藏指导方针
	if (event.keyCode==113){
		showBorders();
		return false;
	}
	if (event.ctrlKey){
		// Ctrl+Enter:提交
		if (event.keyCode==10){
			doSubmit();
			return false;
		}
		// Ctrl++:增加编辑区
		if (key=="+"){
			sizeChange(300);
			return false;
		}
		// Ctrl+-:减小编辑区
		if (key=="-"){
			sizeChange(-300);
			return false;
		}
		// Ctrl+1:代码模式
		if (key=="1"){
			setMode("CODE");
			return false;
		}
		// Ctrl+2:设计模式
		if (key=="2"){
			setMode("EDIT");
			return false;
		}
		// Ctrl+3:纯文本
		if (key=="3"){
			setMode("TEXT");
			return false;
		}
		// Ctrl+4:预览
		if (key=="4"){
			setMode("VIEW");
			return false;
		}
	}

	switch(sCurrMode){
	case "VIEW":
		return true;
		break;
	case "EDIT":
		if (event.ctrlKey){
			// Ctrl+D:从Word粘贴
			if (key == "D"){
				PasteWord();
				return false;
			}
			// Ctrl+R:查找替换
			if (key == "R"){
				findReplace();
				return false;
			}
			// Ctrl+Z:Undo
			if (key == "Z"){
				goHistory(-1);
				return false;
			}
			// Ctrl+Y:Redo
			if (key == "Y"){
				goHistory(1);
				return false;
			}
		}
		if(!event.ctrlKey && event.keyCode != 90 && event.keyCode != 89) {
			if (event.keyCode == 32 || event.keyCode == 13){
				saveHistory()
			}
		}
		return true;
		break;
	default:
		if (event.keyCode==13){
			var sel = HtmlEdit.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 ((key == "B")||(key == "I")||(key == "U")){
				return false;
			}
		}

	}
}

// 取剪粘板中的HTML格式数据
function GetClipboardHTML() {
	var oDiv = document.getElementById("HtmlEdit_Temp_HTML")
	oDiv.innerHTML = "" ;

	var oTextRange = document.body.createTextRange() ;
	oTextRange.moveToElementText(oDiv) ;
	oTextRange.execCommand("Paste") ;

	var sData = oDiv.innerHTML ;
	oDiv.innerHTML = "" ;

	return sData ;
}

// 清除WORD冗余格式并粘贴
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 ) ;
}

// 在当前文档位置插入.
function insertHTML(html) {
	if (isModeView()) return false;
	if (HtmlEdit.document.selection.type.toLowerCase() != "none"){
		HtmlEdit.document.selection.clear() ;
	}
	if (sCurrMode!="EDIT"){
		html=HTMLEncode(html);
	}
	HtmlEdit.document.selection.createRange().pasteHTML(html) ;
}

// 设置编辑器的内容
function setHTML(html) {
	ContentEdit.value = html;
	switch (sCurrMode){
	case "CODE":
		HtmlEdit.document.designMode="On";
		HtmlEdit.document.open();
		HtmlEdit.document.write(config.StyleEditorHeader);
		HtmlEdit.document.body.innerText=html;
		HtmlEdit.document.body.contentEditable="true";
		HtmlEdit.document.close();
		bEditMode=false;
		break;
	case "EDIT":
		HtmlEdit.document.designMode="On";
		HtmlEdit.document.open();
		HtmlEdit.document.write(config.StyleEditorHeader+html);
		HtmlEdit.document.body.contentEditable="true";
		HtmlEdit.document.execCommand("2D-Position",true,true);
		HtmlEdit.document.execCommand("MultipleSelection", true, true);
		HtmlEdit.document.execCommand("LiveResize", true, true);
		HtmlEdit.document.close();
		doZoom(nCurrZoomSize);
		bEditMode=true;
		HtmlEdit.document.onselectionchange = function () { doToolbar();}
		break;
	case "TEXT":
		HtmlEdit.document.designMode="On";
		HtmlEdit.document.open();
		HtmlEdit.document.write(config.StyleEditorHeader);
		HtmlEdit.document.body.innerText=html;
		HtmlEdit.document.body.contentEditable="true";
		HtmlEdit.document.close();
		bEditMode=false;
		break;
	case "VIEW":
		HtmlEdit.document.designMode="off";
		HtmlEdit.document.open();
		HtmlEdit.document.write(config.StyleEditorHeader+html);
		HtmlEdit.document.body.contentEditable="false";
		HtmlEdit.document.close();
		bEditMode=false;
		break;
	}

	HtmlEdit.document.body.onpaste = onPaste ;
	HtmlEdit.document.body.onhelp = onHelp ;
	HtmlEdit.document.onkeydown = new Function("return onKeyDown(HtmlEdit.event);");
	HtmlEdit.document.oncontextmenu=new Function("return showContextMenu(HtmlEdit.event);");

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

	initHistory();
}

// 取编辑器的内容
function getHTML() {
	var html;
	if((sCurrMode=="EDIT")||(sCurrMode=="VIEW")){
		html = HtmlEdit.document.body.innerHTML;
	}else{
		html = HtmlEdit.document.body.innerText;
	}
	if (sCurrMode!="TEXT"){
		if ((html.toLowerCase()=="<p>&nbsp;</p>")||(html.toLowerCase()=="<p></p>")){
			html = "";
		}
	}
	return html;
}

// 在尾部追加内容
function appendHTML(html) {
	if (isModeView()) return false;
	if(sCurrMode=="EDIT"){
		HtmlEdit.document.body.innerHTML += html;
	}else{
		HtmlEdit.document.body.innerText += html;
	}
}

// 从Word中粘贴，去除格式
function PasteWord(){
	HtmlEdit.focus();
	if (BrowserInfo.IsIE55OrMore)
		cleanAndPaste( GetClipboardHTML() ) ;
	else if ( confirm( "此功能要求IE5.5版本以上，你当前的浏览器不支持，是否按常规粘贴进行？" ) )
		format("paste") ;
	HtmlEdit.focus();
}

// 粘贴纯文本
function PasteText(){
	HtmlEdit.focus();
	var sText = HTMLEncode( clipboardData.getData("Text") ) ;
	insertHTML(sText);
	HtmlEdit.focus();
}

// 检测当前是否允许编辑
function validateMode() {
	if (sCurrMode=="EDIT") return true;
	alert("需转换为编辑状态后才能使用编辑功能！");
	HtmlEdit.focus();
	return false;
}

// 检测当前是否在预览模式
function isModeView(){
	if (sCurrMode=="VIEW"){
		alert("预览时不允许设置编辑区内容。");
		return true;
	}
	return false;
}

// 格式化编辑器中的内容
function format(what,opt) {
	HtmlEdit.focus();
	if (opt=="RemoveFormat") {
		what=opt;
		opt=null;
	}
	if (opt==null) HtmlEdit.document.execCommand(what);
	else HtmlEdit.document.execCommand(what,"",opt);
	HtmlEdit.focus();
}

// 确保焦点在 HtmlEdit 内
function VerifyFocus() {
	if ( HtmlEdit )
		HtmlEdit.focus();
}

// 改变模式：代码、编辑、文本、预览
function setMode(NewMode){
	if (NewMode!=sCurrMode){

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

		if (NewMode=="TEXT"){
			if (sCurrMode==ModeEdit.value){
				if (!confirm("警告！切换到纯文本模式会丢失您所有的HTML格式，您确认切换吗？")){
					return false;
				}
			}
		}

		var sBody = "";
		switch(sCurrMode){
		case "CODE":
			if (NewMode=="TEXT"){
				HtmlEdit_Temp_HTML.innerHTML = HtmlEdit.document.body.innerText;
				sBody = HtmlEdit_Temp_HTML.innerText;
			}else{
				sBody = HtmlEdit.document.body.innerText;
			}
			break;
		case "TEXT":
			sBody = HtmlEdit.document.body.innerText;
			sBody = HTMLEncode(sBody);
			break;
		case "EDIT":
		case "VIEW":
			if (NewMode=="TEXT"){
				sBody = HtmlEdit.document.body.innerText;
			}else{
				sBody = HtmlEdit.document.body.innerHTML;
			}
			break;
		default:
			sBody = ContentEdit.value;
			break;
		}

		// 换图片
		try{
			document.all["HtmlEdit_CODE"].className = "StatusBarBtnOff";
			document.all["HtmlEdit_EDIT"].className = "StatusBarBtnOff";
			document.all["HtmlEdit_TEXT"].className = "StatusBarBtnOff";
			document.all["HtmlEdit_VIEW"].className = "StatusBarBtnOff";
			document.all["HtmlEdit_"+NewMode].className = "StatusBarBtnOn";
			}
		catch(e){
			}

		sCurrMode = NewMode;
		ModeEdit.value = NewMode;
		setHTML(sBody);
		disableChildren(HtmlEdit_toolbar);
	}
}

// 使工具栏无效
function disableChildren(obj){
    if(config.InitTool != "TEMPLATES" && config.InitTool != "LABEL"){
	  if (obj){
		obj.disabled=(!bEditMode);
		for (var i=0; i<obj.children.length; i++){
			disableChildren(obj.children[i]);
		}
	  }
	}
}

// 显示无模式对话框
function ShowDialog(url, width, height, optValidate) {
	if (optValidate) {
		if (!validateMode()) return;
	}
	HtmlEdit.focus();
	var arr = showModalDialog(url, window, "dialogWidth:" + width + "px;dialogHeight:" + height + "px;help:no;scroll:no;status:no");
	HtmlEdit.focus();
}

// 全屏编辑
function Maximize() {
	window.open("dialog/fullscreen.htm?sMode="+config.InitMode+"&Tool="+config.InitTool, 'FullScreen'+sLinkFieldName, 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,fullscreen=yes');
}

// 创建或修改超级链接
function createLink(){
	if (!validateMode()) return;

	if (HtmlEdit.document.selection.type == "Control") {
		var oControlRange = HtmlEdit.document.selection.createRange();
		if (oControlRange(0).tagName.toUpperCase() != "IMG") {
			alert("链接只能是图片或文本");
			return;
		}
	}

	ShowDialog("dialog/hyperlink.htm", 350, 170, 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 InsertLabel(what) {
	HtmlEdit.focus();
	insertHTML(what)
	HtmlEdit.focus();
}
// 插入引用对象
function insertquote(what) {
		appendHTML('<table width=95% border="0" align="Center" cellpadding="6" cellspacing="0" style="border: 1px Dotted #CCCCCC; TABLE-LAYOUT: fixed"><tr><td bgcolor=#F3F3F3 style="WORD-WRAP: break-word;padding:10px"><font style="color: #990000;font-weight:bold">以下是引用片段：</font><br>'+what+'</td></tr></table>');
}

// 插入特殊对象
function insert(what) {
	if (!validateMode()) return;
	HtmlEdit.focus();
	var sel = HtmlEdit.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 "pagenext":		// 插入手动分页符
		insertHTML("[NextPage]")
		break;
	case "nowdate":		// 插入当前系统日期
		var d = new Date();
		insertHTML(d.toLocaleDateString());
		break;
	case "nowtime":		// 插入当前系统时间
		var d = new Date();
		insertHTML(d.toLocaleTimeString());
		break;
	case "code":		// 代码片段样式
		insertHTML('<table width=95% border="0" align="Center" cellpadding="6" cellspacing="0" style="border: 1px Dotted #CCCCCC; TABLE-LAYOUT: fixed"><tr><td bgcolor=#FDFDDF style="WORD-WRAP: break-word"><font style="color: #990000;font-weight:bold">以下是代码片段：</font><br>'+HTMLEncode(sel.text)+'</td></tr></table>');
		break;
	case "quote":		// 引用片段样式
		insertHTML('<table width=95% border="0" align="Center" cellpadding="6" cellspacing="0" style="border: 1px Dotted #CCCCCC; TABLE-LAYOUT: fixed"><tr><td bgcolor=#F3F3F3 style="WORD-WRAP: break-word"><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 = config.ShowBorder;
function showBorders() {
	if (!validateMode()) return;

	var allForms = HtmlEdit.document.body.getElementsByTagName("FORM");
	var allInputs = HtmlEdit.document.body.getElementsByTagName("INPUT");
	var allTables = HtmlEdit.document.body.getElementsByTagName("TABLE");
	var allLinks = HtmlEdit.document.body.getElementsByTagName("A");

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

	// Input Hidden类
	for (b=0; b < allInputs.length; b++) {
		if (borderShown == "0") {
			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 == "0") {
				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 == "0") {
							allCellsInRow[x].runtimeStyle.border = "1px dotted #BFBFBF"
						} else {
							allCellsInRow[x].runtimeStyle.cssText = ""
						}
					}
			}
	}

	// 链接 A
	for (a=0; a < allLinks.length; a++) {
		if (borderShown == "0") {
			if (allLinks[a].href.toUpperCase() == "") {
				allLinks[a].runtimeStyle.borderBottom = "1px dashed #000000"
			}
		} else {
			allLinks[a].runtimeStyle.cssText = ""
		}
	}

	if (borderShown == "0") {
		borderShown = "1"
	} else {
		borderShown = "0"
	}

	scrollUp()
}

// 返回页面最上部
function scrollUp() {
	HtmlEdit.scrollBy(0,0);
}

// 缩放操作
var nCurrZoomSize = 100;
var aZoomSize = new Array(10, 25, 50, 75, 100, 150, 200, 500);
function doZoom(size) {
	HtmlEdit.document.body.runtimeStyle.zoom = size + "%";
	nCurrZoomSize = size;
}

// 查找替换
function findReplace(){
	ShowDialog('dialog/findreplace.htm', 320, 165)
}

// 相对(absolute)或绝对位置(static)
function absolutePosition(){
	var objReference	= null;
	var RangeType		= HtmlEdit.document.selection.type;
	if (RangeType != "Control") return;
	var selectedRange	= HtmlEdit.document.selection.createRange();
	for (var i=0; i<selectedRange.length; i++){
		objReference = selectedRange.item(i);
		if (objReference.style.position != 'absolute') {
			objReference.style.position='absolute';
		}else{
			objReference.style.position='static';
		}
	}
}

// 上移(forward)或下移(backward)一层
function zIndex(action){
	var objReference	= null;
	var RangeType		= HtmlEdit.document.selection.type;
	if (RangeType != "Control") return;
	var selectedRange	= HtmlEdit.document.selection.createRange();
	for (var i=0; i<selectedRange.length; i++){
		objReference = selectedRange.item(i);
		if (action=='forward'){
			objReference.style.zIndex  +=1;
		}else{
			objReference.style.zIndex  -=1;
		}
		objReference.style.position='absolute';
	}
}

// 是否选中指定类型的控件
function isControlSelected(tag){
	if (HtmlEdit.document.selection.type == "Control") {
		var oControlRange = HtmlEdit.document.selection.createRange();
		if (oControlRange(0).tagName.toUpperCase() == tag) {
			return true;
		}
	}
	return false;
}

// 改变编辑区高度
function sizeChange(size){
	if (!BrowserInfo.IsIE55OrMore){
		alert("此功能需要IE5.5版本以上的支持！");
		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 mapEdit(){
	if (!validateMode()) return;

	var b = false;
	if (HtmlEdit.document.selection.type == "Control") {
		var oControlRange = HtmlEdit.document.selection.createRange();
		if (oControlRange(0).tagName.toUpperCase() == "IMG") {
			b = true;
		}
	}
	if (!b){
		alert("热点链接只能作用于图片");
		return;
	}

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

// 大文件内容自动拆分
function splitTextField(objField, html) {
	var strFieldName = objField.name;
	var objForm = objField.form;
	var objDocument = objField.document;
	objField.value = html;

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

	// 再次处理时，先赋空值
	for (var i=1;i<objDocument.getElementsByName(strFieldName).length;i++) {
		objDocument.getElementsByName(strFieldName)[i].value = "";
	}

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

		while (html.length > 0) {
			var objTEXTAREA = objDocument.createElement("TEXTAREA") ;
			objTEXTAREA.name = strFieldName ;
			objTEXTAREA.style.display = "none" ;
			objTEXTAREA.value = html.substr(0, FormLimit) ;
			objForm.appendChild(objTEXTAREA) ;

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

// 修正Undo/Redo
var history = new Object;
history.data = [];
history.position = 0;
history.bookmark = [];

// 保存历史
function saveHistory() {
	if (bEditMode){
		if (history.data[history.position] != HtmlEdit.document.body.innerHTML){
			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] = HtmlEdit.document.body.innerHTML;

			if (HtmlEdit.document.selection.type != "Control"){
				history.bookmark[history.bookmark.length] = HtmlEdit.document.selection.createRange().getBookmark();
			} else {
				var oControl = HtmlEdit.document.selection.createRange();
				history.bookmark[history.bookmark.length] = oControl[0];
			}

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

// 初始历史
function initHistory() {
	history.data.length = 0;
	history.bookmark.length = 0;
	history.position = 0;
}

// 返回历史
function goHistory(value) {
	saveHistory();
	// undo
	if (value == -1){
		if (history.position > 0){
			HtmlEdit.document.body.innerHTML = history.data[--history.position];
			setHistoryCursor();
		}
	// redo
	} else {
		if (history.position < history.data.length -1){
			HtmlEdit.document.body.innerHTML = history.data[++history.position];
			setHistoryCursor();
		}
	}
}

// 设置当前书签
function setHistoryCursor() {
	if (history.bookmark[history.position]){
		r = HtmlEdit.document.body.createTextRange()
		if (history.bookmark[history.position] != "[object]"){
			if (r.moveToBookmark(history.bookmark[history.position])){
				r.collapse(false);
				r.select();
			}
		}
	}
}
// End Undo / Redo Fix

// 工具栏事件发生
function doToolbar(){
	if (bEditMode){
		saveHistory();
	}
}



//table.js

// 插入表格
function TableInsert(){
	if (!isTableSelected()){
		ShowDialog('dialog/table.htm', 350, 380, true);
	}
}

// 修改表格属性
function TableProp(){
	if (isTableSelected()||isCursorInTableCell()){
		ShowDialog('dialog/table.htm?action=modify', 350, 380, true);
	}
}

// 修改单元格属性
function TableCellProp(){
	if (isCursorInTableCell()){
		ShowDialog('dialog/tablecell.htm', 350, 280, true);
	}
}

// 拆分单元格
function TableCellSplit(){
	if (isCursorInTableCell()){
		ShowDialog('dialog/tablecellsplit.htm', 200, 150, true);
	}
}

// 修改表格行属性
function TableRowProp(){
	if (isCursorInTableCell()){
		ShowDialog('dialog/tablecell.htm?action=row', 350, 280, true);
	}
}

// 插入行（在上方）
function TableRowInsertAbove() {

	if (isCursorInTableCell()){
		var numCols = 0

		allCells = selectedTR.cells
		for (var i=0;i<allCells.length;i++) {
		 	numCols = numCols + allCells[i].getAttribute('colSpan')
		}

		var newTR = selectedTable.insertRow(selectedTR.rowIndex)

		for (i = 0; i < numCols; i++) {
		 	newTD = newTR.insertCell()
			newTD.innerHTML = "&nbsp;"

			if (borderShown == "yes") {
				newTD.runtimeStyle.border = "1px dotted #BFBFBF"
			}
		}
	}
}

// 插入行（在下方）
function TableRowInsertBelow() {

	if (isCursorInTableCell()){

		var numCols = 0

		allCells = selectedTR.cells
		for (var i=0;i<allCells.length;i++) {
		 	numCols = numCols + allCells[i].getAttribute('colSpan')
		}

		var newTR = selectedTable.insertRow(selectedTR.rowIndex+1)

		for (i = 0; i < numCols; i++) {
		 	newTD = newTR.insertCell()
			newTD.innerHTML = "&nbsp;"

			if (borderShown == "yes") {
				newTD.runtimeStyle.border = "1px dotted #BFBFBF"
			}
		}
	}
}

// 合并行（向下方）
function TableRowMerge() {
	if (isCursorInTableCell()) {

		var rowSpanTD = selectedTD.getAttribute('rowSpan')
		allRows = selectedTable.rows
		if (selectedTR.rowIndex +1 != allRows.length) {

			var allCellsInNextRow = allRows[selectedTR.rowIndex+selectedTD.rowSpan].cells
			var addRowSpan = allCellsInNextRow[selectedTD.cellIndex].getAttribute('rowSpan')
			var moveTo = selectedTD.rowSpan

			if (!addRowSpan) addRowSpan = 1;

			selectedTD.rowSpan = selectedTD.rowSpan + addRowSpan
			allRows[selectedTR.rowIndex + moveTo].deleteCell(selectedTD.cellIndex)
		}
	}

}

// 拆分行
function TableRowSplit(nRows){
	if (!isCursorInTableCell()) return;
	if (nRows<2) return;

	var addRows = nRows - 1;
	var addRowsNoSpan = addRows;

	var nsLeftColSpan = 0;
	for (var i=0; i<selectedTD.cellIndex; i++){
		nsLeftColSpan += selectedTR.cells[i].colSpan;
	}

	var allRows = selectedTable.rows;

	// rowspan>1时
	while (selectedTD.rowSpan > 1 && addRowsNoSpan > 0){
		var nextRow = allRows[selectedTR.rowIndex+selectedTD.rowSpan-1];
		selectedTD.rowSpan -= 1;

		var ncLeftColSpan = 0;
		var position = -1;
		for (var n=0; n<nextRow.cells.length; n++){
			ncLeftColSpan += nextRow.cells[n].getAttribute('colSpan');
			if (ncLeftColSpan>nsLeftColSpan){
				position = n;
				break;
			}
		}

		var newTD=nextRow.insertCell(position);
		newTD.innerHTML = "&nbsp;";

		if (borderShown == "yes") {
			newTD.runtimeStyle.border = "1px dotted #BFBFBF";
		}

		addRowsNoSpan -= 1;
	}

	// rowspan=1时
	for (var n=0; n<addRowsNoSpan; n++){
		var numCols = 0

		allCells = selectedTR.cells
		for (var i=0;i<allCells.length;i++) {
			numCols = numCols + allCells[i].getAttribute('colSpan')
		}

		var newTR = selectedTable.insertRow(selectedTR.rowIndex+1)

		// 上方行的rowspan达到这行
		for (var j=0; j<selectedTR.rowIndex; j++){
			for (var k=0; k<allRows[j].cells.length; k++){
				if ((allRows[j].cells[k].rowSpan>1)&&(allRows[j].cells[k].rowSpan>=selectedTR.rowIndex-allRows[j].rowIndex+1)){
					allRows[j].cells[k].rowSpan += 1;
				}
			}
		}
		// 当前行
		for (i = 0; i < allCells.length; i++) {
			if (i!=selectedTD.cellIndex){
				selectedTR.cells[i].rowSpan += 1;
			}else{
				newTD = newTR.insertCell();
				newTD.colSpan = selectedTD.colSpan;
				newTD.innerHTML = "&nbsp;";

				if (borderShown == "yes") {
					newTD.runtimeStyle.border = "1px dotted #BFBFBF";
				}
			}
		}
	}

}

// 删除行
function TableRowDelete() {
	if (isCursorInTableCell()) {
		selectedTable.deleteRow(selectedTR.rowIndex)
	}
}

// 插入列（在左侧）
function TableColInsertLeft() {
   	if (isCursorInTableCell()) {
		moveFromEnd = (selectedTR.cells.length-1) - (selectedTD.cellIndex)
		allRows = selectedTable.rows
		for (i=0;i<allRows.length;i++) {
			rowCount = allRows[i].cells.length - 1
			position = rowCount - moveFromEnd
			if (position < 0) {
				position = 0
			}
			newCell = allRows[i].insertCell(position)
			newCell.innerHTML = "&nbsp;"

			if (borderShown == "yes") {
				newCell.runtimeStyle.border = "1px dotted #BFBFBF"
			}
		}
   	}
}

// 插入列（在右侧）
function TableColInsertRight() {
   	if (isCursorInTableCell()) {
		moveFromEnd = (selectedTR.cells.length-1) - (selectedTD.cellIndex)
		allRows = selectedTable.rows
		for (i=0;i<allRows.length;i++) {
			rowCount = allRows[i].cells.length - 1
			position = rowCount - moveFromEnd
			if (position < 0) {
				position = 0
			}
			newCell = allRows[i].insertCell(position+1)
			newCell.innerHTML = "&nbsp;"

			if (borderShown == "yes") {
				newCell.runtimeStyle.border = "1px dotted #BFBFBF"
			}
		}
   	}
}

// 合并列
function TableColMerge() {
	if (isCursorInTableCell()) {

		var colSpanTD = selectedTD.getAttribute('colSpan')
		allCells = selectedTR.cells

		if (selectedTD.cellIndex + 1 != selectedTR.cells.length) {
			var addColspan = allCells[selectedTD.cellIndex+1].getAttribute('colSpan')
			selectedTD.colSpan = colSpanTD + addColspan
			selectedTR.deleteCell(selectedTD.cellIndex+1)
		}
	}
}

// 删除列
function TableColDelete() {
   	if (isCursorInTableCell()) {
		moveFromEnd = (selectedTR.cells.length-1) - (selectedTD.cellIndex)
		allRows = selectedTable.rows
		for (var i=0;i<allRows.length;i++) {
			endOfRow = allRows[i].cells.length - 1
			position = endOfRow - moveFromEnd
			if (position < 0) {
				position = 0
			}


			allCellsInRow = allRows[i].cells

			if (allCellsInRow[position].colSpan > 1) {
				allCellsInRow[position].colSpan = allCellsInRow[position].colSpan - 1
			} else {
				allRows[i].deleteCell(position)
			}

		}

	}

}

// 拆分列
function TableColSplit(nCols){
	if (!isCursorInTableCell()) return;
	if (nCols<2) return;

	var addCols = nCols - 1;
	var addColsNoSpan = addCols;
	var newCell;

	var nsLeftColSpan = 0;
	var nsLeftRowSpanMoreOne = 0;
	for (var i=0; i<selectedTD.cellIndex; i++){
		nsLeftColSpan += selectedTR.cells[i].colSpan;
		if (selectedTR.cells[i].rowSpan > 1){
			nsLeftRowSpanMoreOne += 1;
		}
	}

	var allRows = selectedTable.rows
	// colSpan>1时
	while (selectedTD.colSpan > 1 && addColsNoSpan > 0) {
		newCell = selectedTR.insertCell(selectedTD.cellIndex+1);
		newCell.innerHTML = "&nbsp;"
		if (borderShown == "yes") {
			newCell.runtimeStyle.border = "1px dotted #BFBFBF"
		}
		selectedTD.colSpan -= 1;
		addColsNoSpan -= 1;
	}
	// colSpan=1时
	for (i=0;i<allRows.length;i++) {
		var ncLeftColSpan = 0;
		var position = -1;
		for (var n=0; n<allRows[i].cells.length; n++){
			ncLeftColSpan += allRows[i].cells[n].getAttribute('colSpan');
			if (ncLeftColSpan+nsLeftRowSpanMoreOne>nsLeftColSpan){
				position = n;
				break;
			}
		}

		if (selectedTR.rowIndex!=i){
			if (position!=-1){
				allRows[i].cells[position+nsLeftRowSpanMoreOne].colSpan += addColsNoSpan;
			}
		}else{
			for (var n=0; n<addColsNoSpan; n++){
				newCell = allRows[i].insertCell(selectedTD.cellIndex+1)
				newCell.innerHTML = "&nbsp;"
				newCell.rowSpan = selectedTD.rowSpan;

				if (borderShown == "yes") {
					newCell.runtimeStyle.border = "1px dotted #BFBFBF"
				}
			}
		}
	}
}

// 是否选中表格
function isTableSelected() {
	if (HtmlEdit.document.selection.type == "Control") {
		var oControlRange = HtmlEdit.document.selection.createRange();
		if (oControlRange(0).tagName.toUpperCase() == "TABLE") {
			selectedTable = HtmlEdit.document.selection.createRange()(0);
			return true;
		}
	}
}

// 光标是否在表格中
function isCursorInTableCell() {
	if (HtmlEdit.document.selection.type != "Control") {
		var elem = HtmlEdit.document.selection.createRange().parentElement()
		while (elem.tagName.toUpperCase() != "TD" && elem.tagName.toUpperCase() != "TH"){
			elem = elem.parentElement
			if (elem == null)
                break
		}
		if (elem) {
			selectedTD = elem
			selectedTR = selectedTD.parentElement
			selectedTBODY =  selectedTR.parentElement
			selectedTable = selectedTBODY.parentElement
			return true
		}
	}
}


//menu.js

// 菜单
var oPopupMenu = null;
if (BrowserInfo.IsIE55OrMore){
	oPopupMenu = window.createPopup();
}

// 取菜单行
function getMenuRow(s_Disabled, s_Event, s_Image, s_Html) {
	var s_MenuRow = "";
	s_MenuRow = "<tr><td align=center valign=middle><TABLE border=0 cellpadding=0 cellspacing=0 width=132><tr "+s_Disabled+"><td valign=middle height=20 class=MouseOut onMouseOver=this.className='MouseOver'; onMouseOut=this.className='MouseOut';";
	if (s_Disabled==""){
		s_MenuRow += " onclick=\"parent."+s_Event+";parent.oPopupMenu.hide();\"";
	}
	s_MenuRow += ">"
	if (s_Image !=""){
		s_MenuRow += "&nbsp;<img border=0 src='../../Images/Button/"+s_Image+"' width=20 height=20 align=absmiddle "+s_Disabled+">&nbsp;";
	}else{
		s_MenuRow += "&nbsp;";
	}
	s_MenuRow += s_Html+"<\/td><\/tr><\/TABLE><\/td><\/tr>";
	return s_MenuRow;

}

// 取标准的format菜单行
function getFormatMenuRow(menu, html, image){
	var s_Disabled = "";
	if (!HtmlEdit.document.queryCommandEnabled(menu)){
		s_Disabled = "disabled";
	}
	var s_Event = "format('"+menu+"')";
	var s_Image = menu+".gif";
	if (image){
		s_Image = image;
	}
	return getMenuRow(s_Disabled, s_Event, s_Image, html)
}

// 取表格菜单行
function getTableMenuRow(what){
	var s_Menu = "";
	var s_Disabled = "disabled";
	switch(what){
	case "TableInsert":
		if (!isTableSelected()) s_Disabled="";
		s_Menu += getMenuRow(s_Disabled, "TableInsert()", "TableInsert.gif", "插入表格...")
		break;
	case "TableProp":
		if (isTableSelected()||isCursorInTableCell()) s_Disabled="";
		s_Menu += getMenuRow(s_Disabled, "TableProp()", "TableProp.gif", "表格属性...")
		break;
	case "TableCell":
		if (isCursorInTableCell()) s_Disabled="";
		s_Menu += getMenuRow(s_Disabled, "TableCellProp()", "TableCellProp.gif", "单元格属性...")
		s_Menu += getMenuRow(s_Disabled, "TableCellSplit()", "TableCellSplit.gif", "拆分单元格...")
		s_Menu += sMenuHr;
		s_Menu += getMenuRow(s_Disabled, "TableRowProp()", "TableRowProp.gif", "表格行属性...")
		s_Menu += getMenuRow(s_Disabled, "TableRowInsertAbove()", "TableRowInsertAbove.gif", "插入行（在上方）");
		s_Menu += getMenuRow(s_Disabled, "TableRowInsertBelow()", "TableRowInsertBelow.gif", "插入行（在下方）");
		s_Menu += getMenuRow(s_Disabled, "TableRowMerge()", "TableRowMerge.gif", "合并行（向下方）");
		s_Menu += getMenuRow(s_Disabled, "TableRowSplit(2)", "TableRowSplit.gif", "拆分行");
		s_Menu += getMenuRow(s_Disabled, "TableRowDelete()", "TableRowDelete.gif", "删除行");
		s_Menu += sMenuHr;
		s_Menu += getMenuRow(s_Disabled, "TableColInsertLeft()", "TableColInsertLeft.gif", "插入列（在左侧）");
		s_Menu += getMenuRow(s_Disabled, "TableColInsertRight()", "TableColInsertRight.gif", "插入列（在右侧）");
		s_Menu += getMenuRow(s_Disabled, "TableColMerge()", "TableColMerge.gif", "合并列（向右侧）");
		s_Menu += getMenuRow(s_Disabled, "TableColSplit(2)", "TableColSplit.gif", "拆分列");
		s_Menu += getMenuRow(s_Disabled, "TableColDelete()", "TableColDelete.gif", "删除列");
		break;
	}
	return s_Menu;
}

// 右键菜单
function showContextMenu(event){
	if (!bEditMode) return false;

	var width = 150;
	var height = 0;
	var lefter = event.clientX;
	var topper = event.clientY;

	var oPopDocument = oPopupMenu.document;
	var oPopBody = oPopupMenu.document.body;

	var sMenu="";

	sMenu += getFormatMenuRow("cut", "剪切");
	sMenu += getFormatMenuRow("copy", "复制");
	sMenu += getFormatMenuRow("paste", "常规粘贴");
	sMenu += getFormatMenuRow("delete", "删除");
	sMenu += getFormatMenuRow("selectall", "全选");
	sMenu += sMenuHr;
	height += 102;

	if (isCursorInTableCell()){
		sMenu += getTableMenuRow("TableProp");
		sMenu += getTableMenuRow("TableCell");
		sMenu += sMenuHr;
		height += 286;
	}

	if (isControlSelected("TABLE")){
		sMenu += getTableMenuRow("TableProp");
		sMenu += sMenuHr;
		height += 22;
	}

	if (isControlSelected("IMG")){
		sMenu += getMenuRow("", "zIndex('forward')", "forward.gif", "上移一层");
		sMenu += getMenuRow("", "zIndex('backward')", "backward.gif", "下移一层");
		sMenu += sMenuHr;
		height += 42;
	}

	sMenu += getMenuRow("", "findReplace()", "findreplace.gif", "查找替换...");
	height += 20;

	sMenu = sMenu1 + sMenu + sMenu2;

	oPopDocument.open();
	oPopDocument.write(config.StyleMenuHeader+sMenu);
	oPopDocument.close();

	height+=2;
	if(lefter+width > document.body.clientWidth) lefter=lefter-width;
	//if(topper+height > document.body.clientHeight) topper=topper-height;

	oPopupMenu.show(lefter, topper, width, height, HtmlEdit.document.body);
	return false;

}

// 工具栏菜单
function showToolMenu(menu,num){
	if (num==0){if (!bEditMode) return false;}
	var sMenu = ""
	var width = 150;
	var height = 0;

	var lefter = event.clientX;
	var leftoff = event.offsetX
	var topper = event.clientY;
	var topoff = event.offsetY;

	var oPopDocument = oPopupMenu.document;
	var oPopBody = oPopupMenu.document.body;

	switch(menu){
	case "font":		// 字体菜单
		sMenu += getFormatMenuRow("bold", "粗体", "bold.gif");
		sMenu += getFormatMenuRow("italic", "斜体", "italic.gif");
		sMenu += getFormatMenuRow("underline", "下划线", "underline.gif");
		sMenu += getFormatMenuRow("strikethrough", "中划线", "strikethrough.gif");
		sMenu += sMenuHr;
		sMenu += getFormatMenuRow("superscript", "上标", "superscript.gif");
		sMenu += getFormatMenuRow("subscript", "下标", "subscript.gif");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "ShowDialog('dialog/selcolor.htm?action=forecolor', 280, 250, true)", "forecolor.gif", "字体颜色");
		sMenu += getMenuRow("", "ShowDialog('dialog/selcolor.htm?action=backcolor', 280, 250, true)", "backcolor.gif", "字体背景色");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "insert('big')", "tobig.gif", "字体增大");
		sMenu += getMenuRow("", "insert('small')", "tosmall.gif", "字体减小");
		height = 206;
		break;
	case "paragraph":	// 段落菜单
		sMenu += getFormatMenuRow("JustifyLeft", "左对齐", "JustifyLeft.gif");
		sMenu += getFormatMenuRow("JustifyCenter", "居中对齐", "JustifyCenter.gif");
		sMenu += getFormatMenuRow("JustifyRight", "右对齐", "JustifyRight.gif");
		sMenu += getFormatMenuRow("JustifyFull", "两端对齐", "JustifyFull.gif");
		sMenu += sMenuHr;
		sMenu += getFormatMenuRow("insertorderedlist", "编号", "insertorderedlist.gif");
		sMenu += getFormatMenuRow("insertunorderedlist", "项目符号", "insertunorderedlist.gif");
		sMenu += getFormatMenuRow("indent", "增加缩进量", "indent.gif");
		sMenu += getFormatMenuRow("outdent", "减少缩进量", "outdent.gif");
		sMenu += sMenuHr;
		sMenu += getFormatMenuRow("insertparagraph", "插入段落", "insertparagraph.gif");
		sMenu += getMenuRow("", "InsertLabel('<br>')", "br.gif", "插入换行符");
		height = 204;
		break;
	case "edit":		// 编辑菜单
		var s_Disabled = "";
		if (history.data.length <= 1 || history.position <= 0) s_Disabled = "disabled";
		sMenu += getMenuRow(s_Disabled, "goHistory(-1)", "undo.gif", "撤消")
		if (history.position >= history.data.length-1 || history.data.length == 0) s_Disabled = "disabled";
		sMenu += getMenuRow(s_Disabled, "goHistory(1)", "redo.gif", "恢复")
		sMenu += sMenuHr;
		sMenu += getFormatMenuRow("Cut", "剪切", "cut.gif");
		sMenu += getFormatMenuRow("Copy", "复制", "copy.gif");
		sMenu += getFormatMenuRow("Paste", "常规粘贴", "paste.gif");
		sMenu += getMenuRow("", "PasteText()", "pastetext.gif", "纯文本粘贴");
		sMenu += getMenuRow("", "PasteWord()", "pasteword.gif", "从Word中粘贴");
		sMenu += sMenuHr;
		sMenu += getFormatMenuRow("delete", "删除", "delete.gif");
		sMenu += getFormatMenuRow("RemoveFormat", "删除文字格式", "removeformat.gif");
		sMenu += sMenuHr;
		sMenu += getFormatMenuRow("SelectAll", "全部选中", "selectall.gif");
		sMenu += getFormatMenuRow("Unselect", "取消选择", "unselect.gif");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "findReplace()", "findreplace.gif", "查找替换");
		height = 248;
		break;
	case "object":		// 对象效果菜单
		sMenu += getMenuRow("", "ShowDialog('dialog/selcolor.htm?action=bgcolor', 280, 250, true)", "bgcolor.gif", "对象背景颜色");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "absolutePosition()", "abspos.gif", "绝对或相对位置");
		sMenu += getMenuRow("", "zIndex('forward')", "forward.gif", "上移一层");
		sMenu += getMenuRow("", "zIndex('backward')", "backward.gif", "下移一层");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "showBorders()", "showborders.gif", "显示隐藏指导方针");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "insert('quote')", "quote.gif", "引用样式");
		sMenu += getMenuRow("", "insert('code')", "code.gif", "代码样式");
		height = 146;
		break;
	case "component":	// 组件菜单
		sMenu += getMenuRow("", "ShowDialog('dialog/fieldset.htm', 350, 170, true)", "fieldset.gif", "插入或修改栏目框");
		sMenu += getMenuRow("", "ShowDialog('dialog/iframe.htm', 350, 200, true)", "iframe.gif", "插入或修改网页帧");
		sMenu += getFormatMenuRow("InsertHorizontalRule", "插入水平尺", "inserthorizontalrule.gif");
		sMenu += getMenuRow("", "ShowDialog('dialog/marquee.htm', 395, 150, true)", "marquee.gif", "插入或修改字幕");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "ShowDialog('dialog/media.htm', 350, 140, true)", "media.gif", "插入播放媒体文件");
		sMenu += getMenuRow("", "ShowDialog('dialog/flash.htm', 350, 140, true)", "flash.gif", "插入Flash动画");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "createLink()", "createlink.gif", "插入或修改超链接");
		sMenu += getMenuRow("", "ShowDialog('dialog/anchor.htm', 270, 220, true)", "anchor.gif", "书签管理");
		sMenu += getMenuRow("", "mapEdit()", "map.gif", "图形热点链接");
		sMenu += getFormatMenuRow("UnLink", "取消超链接或标签", "unlink.gif");
		height = 204;
		break;
	case "tool":		// 工具菜单
		sMenu += getMenuRow("", "ShowDialog('dialog/symbol.htm', 350, 220,true)", "symbol.gif", "插入特殊字符");
		sMenu += getMenuRow("", "insert('excel')", "excel.gif", "插入Excel表格");
		sMenu += getMenuRow("", "ShowDialog('dialog/emot.htm', 300, 290,true)", "emot.gif", "插入表情图标");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "insert('pagenext')", "Page.gif", "插入手动分页符");
		sMenu += getMenuRow("", "LayOut()", "paiban.gif", "内容自动排版");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "insert('nowdate')", "date.gif", "插入当前日期");
		sMenu += getMenuRow("", "insert('nowtime')", "time.gif", "插入当前时间");
		height = 144;
		break;
	case "file":		// 文件视图菜单
		sMenu += getMenuRow("", "setMode('CODE')", "modecodebtn.gif", "代码状态");
		sMenu += getMenuRow("", "setMode('EDIT')", "modeeditbtn.gif", "编辑状态");
		sMenu += getMenuRow("", "setMode('TEXT')", "modetextbtn.gif", "文本状态");
		sMenu += getMenuRow("", "setMode('VIEW')", "modeviewbtn.gif", "预览状态");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "sizeChange(300)", "sizeplus.gif", "增高编辑区");
		sMenu += getMenuRow("", "sizeChange(-300)", "sizeminus.gif", "减小编辑区");
		sMenu += sMenuHr;
		sMenu += getMenuRow("", "format('Print')", "print.gif", "打印");
		height = 144;
		break;
	case "table":		// 表格菜单
		sMenu += getTableMenuRow("TableInsert");
		sMenu += getTableMenuRow("TableProp");
		sMenu += sMenuHr;
		sMenu += getTableMenuRow("TableCell");
		height = 306;
		break;
	case "form":		// 表单菜单
		sMenu += getFormatMenuRow("InsertInputText", "插入输入框", "FormText.gif");
		sMenu += getFormatMenuRow("InsertTextArea", "插入输入区", "FormTextArea.gif");
		sMenu += getFormatMenuRow("InsertInputRadio", "插入单选钮", "FormRadio.gif");
		sMenu += getFormatMenuRow("InsertInputCheckbox", "插入复选钮", "FormCheckBox.gif");
		sMenu += getFormatMenuRow("InsertSelectDropdown", "插入下拉框", "FormDropdown.gif");
		sMenu += getFormatMenuRow("InsertButton", "插入按钮", "FormButton.gif");
		height = 120;
		break;
	case "zoom":		// 缩放菜单
		for (var i=0; i<aZoomSize.length; i++){
			if (aZoomSize[i]==nCurrZoomSize){
				sMenu += getMenuRow("", "doZoom("+aZoomSize[i]+")", "checked.gif", aZoomSize[i]+"%");
			}else{
				sMenu += getMenuRow("", "doZoom("+aZoomSize[i]+")", "space.gif", aZoomSize[i]+"%");
			}
			height += 20;
		}
		break;
	}

	sMenu = sMenu1 + sMenu + sMenu2;

	oPopDocument.open();
	oPopDocument.write(config.StyleMenuHeader+sMenu);
	oPopDocument.close();

	height+=2;
	if(lefter+width > document.body.clientWidth) lefter=lefter-width;

	oPopupMenu.show(lefter - leftoff - 2, topper - topoff + 22, width, height, document.body);

	return false;
}

//==================================================================
//LayOut(TextboxID) 文章内容排版
//==================================================================
function LayOut()
{
    var newLineChar="\r\n";
    var segHead="    ";
    var text = HtmlEdit.document.body.innerText;
    var textContainer = new Array();
    var ContainerArrayIndex = 0;
    var startIndex=0;
    var endIndex=0;
    var textLength=text.length;
    var returnString="";
    var isRubbish=true;
    var rubbish=new String(" \t　\r\n");

    for(var count = 0; count < textLength; count++)
    {
        if(rubbish.indexOf(text.charAt(count))==-1) isRubbish=false;

        if(count==textLength-1&&isRubbish==false)
        {
            textContainer[ContainerArrayIndex]=Trim(text.substring(startIndex,textLength));
            ContainerArrayIndex++;
        }
        else
        {
            if(text.substring(count,count+2)==newLineChar)
            {
                endIndex=count+2;
                if(endIndex-startIndex>2&&isRubbish==false)
                {
                    textContainer[ContainerArrayIndex]=Trim(text.substring(startIndex,endIndex-2))+text.substring(endIndex-2,endIndex);
                    ContainerArrayIndex++;
                }
                startIndex=endIndex;
                count++;
                isRubbish=true;
            }
        }
    }

    for(var count = 0; count < ContainerArrayIndex; count++)
    {
        returnString+=segHead+textContainer[count]+newLineChar;
    }

    HtmlEdit.document.body.innerText = returnString;
}
/*
==================================================================
LTrim(string):去除左边的空格
==================================================================
*/
function LTrim(str)
{
    var whitespace = new String(" \t　");
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(0)) != -1)
    {
        var j=0, i = s.length;
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
        {
            j++;
        }
        s = s.substring(j, i);
    }
    return s;
}
/*
==================================================================
RTrim(string):去除右边的空格
==================================================================
*/
function RTrim(str)
{
    var whitespace = new String(" \t　");
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(s.length-1)) != -1)
    {
        var i = s.length - 1;
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
        {
            i--;
        }
        s = s.substring(0, i+1);
    }
    return s;
}
/*
==================================================================
Trim(string):去除前后空格
==================================================================
*/
function Trim(str)
{
    return RTrim(LTrim(str));
}


