

//global def
var gIsInitEditor = 0;
var gHtmlId = "HtmlEditor";
var gSourceId = "SourceEditor";
var gTextId = "TextEditor";
var gEditorCurId = null;
var gEditorPath = "editor/";
var gEditorToolBarId = "editor_toolbar";
var gEditorToolBarBtnContainerId = "editor_toolbar_btn_container";
var gEditorToolBarSet = {};
var gEditorTxtRange = null;
var gEditorStopCurIni = false;
var gScreenSnapObj = null;
var gEditorMinHeight = null;
var gIsPageLoadedFinish = false;
var gContentId = null;
var gFrame = 0;//框架中调用 
var gEditorMode=0;//HTML编 辑模式

//inteface
function OutputEditorLoading( win ) {
	win = win || window;
	return [ 
		'<div id="HtmlEditorLoading" style="position:absolute;*width:100%;">', 
			'<div class="infobar addrtitle" style="margin:1px;padding:2px;border:0;">',
				!win.IniEditor || !win.S ? 
				'<b style="color:red;">编辑器加载失败...请尝试清空缓存然后重新登陆邮箱！</b>' : 
				'&nbsp;&nbsp;数据加载中，数据量比较大，可能需要一定时间，请稍候...',
			'</div>', 
		'</div>'
		].join( "" );
}



function select_a_ok(s,obj)
//s如：file_name=图1.jpg,file_path=sss.bmp,ytd_files_id_=198注意：传过来的值要在asp中server.urlEncode过
//obj是input框如：t$zdy__1$23,23是记录id,---在asp中，输入 方法是request("cur_input_name")
{
	
	var file_name='',file_path='',ytd_files_id_="";
	var arr_n=obj.split('$');
	var arr=s.split(","),arr1,n,o;
	if(s.indexOf('file_name='))
	{
		file_name=s.split('file_name=')[1];
		file_name=(file_name+",").split(',')[0];
	}
	
//	if(s.indexOf('file_path='))
//	{
//		file_path=s.split('file_path=')[1];
//		file_path=(file_path+",").split(',')[0];
//	}
	
	if(s.indexOf('ytd_files_id_='))
	{
		ytd_files_id_=s.split('ytd_files_id_=')[1];
		ytd_files_id_=(ytd_files_id_+",").split(',')[0];
	}
	
	
	if(obj.indexOf('picture')>-1)	{select_file_ok(ytd_files_id_)}
	if(obj.indexOf('link_path')>-1)	{select_file_link_ok(ytd_files_id_)}
}
function select_file_ok(id)
{
	var file_fileName=top.gbl('file_select_from');
	if(file_fileName==''){alert('没有设置文件源或调用位置不正确。');return;}
	var url="/sys/mis/asp/file.asp?fileName="+file_fileName+"&id="+id;

	document.getElementsByName("picture")[0].value=url;	//将图片的路径付给文本框
}

function select_file_link_ok(id)//用于连接，要选择成功后，由ok()函数来调用
{
	var file_fileName=top.gbl('file_select_from');
	if(file_fileName==''){alert('没有设置文件源或调用位置不正确。');return;}
	var url="/sys/mis/asp/file.asp?fileName="+file_fileName+"&id="+id;
	document.getElementsByName("link_path")[0].value=url;	//将文件的路径付给文本框
}

function select_file()//选择网络U盘中的文件
{
	
	var file_fileName=top.gbl('file_select_from');

	if(file_fileName==''){alert('没有设置文件源或调用位置不正确。');return;}
	window.showModalDialog('../mis/main/select_record_a.htm?cur_input_name=picture&to_fileName=not&to_cols=file_name;file_path&from_cols=file_name;filePath&from_fileName='+file_fileName,window,'resizable:yes;dialogWidth:800px;dialogHeight:600px')
}

function select_file_link()//选择网络U盘中的文件，用作附件
{
	var file_fileName=top.gbl('file_select_from');
	if(file_fileName==''){alert('没有设置文件源或调用位置不正确。');return;}
	window.showModalDialog('../mis/main/select_record_a.htm?cur_input_name=link_path&to_fileName=not&to_cols=file_name;file_path&from_cols=file_name;filePath&from_fileName='+file_fileName,window,'resizable:yes;dialogWidth:800px;dialogHeight:600px')
}

//=============== 设置所属表单的提交或reset事件
function setLinkedField() {
	if (! oLinkField) return ;
	var oForm = oLinkField.form ;
	if (!oForm) return ;
	// 附加submit事件
	oForm.attachEvent("onsubmit", AttachSubmit) ;
	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提交事件,大表单数据提交,保存eWebEditor中的内容
function AttachSubmit() { 
	var oForm = oLinkField.form ;
	if (!oForm) return;
	var html = GetContent();//getHTML()
	//ContentEdit.value = html;
	//if (sCurrMode=="TEXT"){
	//	html = HTMLEncode(html);
	//}
	oLinkField.value=html;//父窗口中需要编辑的那个textarea
	//splitTextField(oLinkField, html);
} 


// 附加Reset事件
function AttachReset(){
	
	if(gEditorMode==0)//编辑模式为HTML
	{
		HtmlEditor.document.body.innerHTML = ContentLoad.value;
	}
	else
	{
		document.getElementsByName('editor_source')[0].value = ContentLoad.value;
	}
}
// end =============== 设置所属表单的提交或reset事件


function IniEditor(noinclude) {
	if (gIsInitEditor == 0) {
		StartIniEditor(noinclude);
	}
}
function StartIniEditor(noinclude)
{
	try
	{
		gIsInitEditor = 1;
		var l = location.href;
		var snews = "";
		var s =  "";
		if(gFrame==1){
		    if(gContentId!=null) s = document.getElementsByName(gContentId)[0].value;	
		}else{
			if(gContentId!=null) s = parent.document.getElementsByName(gContentId)[0].value;
		}
		
		var focusFunc;
		fEditorInit(s);
		try{focusFunc();}catch(e){}
	}
	catch(e) {setTimeout(function(){if(!gEditorStopCurIni)StartIniEditor(noinclude);}, 50);return;}
}

function PutContent(content) {
	switch(gEditorCurId) {
		case gHtmlId:
			return fPutContent(content);
		case gSourceId:
			return PutTextareaValue(S(gSourceId), content);
		case gTextId:
			if (!fPutContent(gIsIE ? content : HtmlToText(content))) return PutTextareaValue(S(gTextId), "数据加载失败!"); 
			return PutTextareaValue(S(gTextId), fGetPlainContent());
	}
	return false;
}
function GetContent() {
	switch(gEditorCurId) {
		case gHtmlId:
			return fGetContent();
		case gSourceId:
			return GetTextareaValue(S(gSourceId));
		case gTextId:
			return GetTextareaValue(S(gTextId));
	}
	return null;
}
//toolbar & plus callback inteface
function fDispToolBar(flag) {
	var tb = S(gEditorToolBarId);
	if (!tb && flag == 0) return;
	if (!tb) {
		if(window.fGenToolBarHtml) fLoadEditorToolBarCallBack();
	}
	fDisp(tb, flag);

	var t = S(gEditorToolBarBtnContainerId);
	if (t) {
		t = t.childNodes;
		fDisp(t[0], 2);
		fDisp(t[1], 2);
	}
}

function fLoadEditorToolBarCallBack() {
	if (S(gEditorToolBarId) || !gIsInitEditor) return;
	if (!S(gHtmlId)) {
		setTimeout("fLoadEditorToolBarCallBack();", 100);
		return;
	}
	var d = document.createElement("div");
	d.innerHTML = fGenToolBarHtml();
	S(gHtmlId).parentNode.insertBefore(d, S(gHtmlId));
}

//base fun
function fGenHtml(dat, templ, bCustom) {
	var code = [];
	for(var i= bCustom ? 1 : 0;i<dat.length;i++) {
		var l = bCustom ? dat[0].length : dat[i].length;
		for(var j = 0; j < l; j++)
			if (templ[j*2+1]) templ[j*2+1] = bCustom ? dat[i][dat[0][j]] : dat[i][j];
		code.push( templ.join("") );
	}
	return code.join( "" );
}
function fDisp(obj, flag) {
	obj = (typeof(obj) == "string" ? S(obj) : obj);
	if (obj) obj.style.display =  (flag == 0 ? "none" : (flag == 2 ? (obj.style.display == "" ? "none" : "") : ""));
}
function fIsDisp(obj) {
	obj = (typeof(obj) == "string" ? S(obj) : obj);
	if (obj) return obj.style.display != "none";
	return false;
}
function fGetBreakLine(n) {
	 return ( new Array( ( n || 1 ) + 1  ) ).join( gIsIE ? "<div>&nbsp;</div>" : "<br>" );
}
function fPutContent(content) {
	try {
		F(gHtmlId).document.body.innerHTML = content;
		fFixHtmlContent();
	}catch(e){return false;}
	return true;
}
function fGetContent() {
	var b = F(gHtmlId).document.body;
	return b ? b.innerHTML : null;
}
function fGetPlainContent() {
	var b = F(gHtmlId).document.body;
	return b ? (b.innerText != null ? b.innerText : b.textContent) : null;
}
function fOnMenuMouseOver(obj) {
	obj.className = "editor_menu_mover";
}
function fOnMenuMouseOut(obj) {
	obj.className = "editor_menu";
}
function fSavePos() {
	if (document.selection) gEditorTxtRange = F(gHtmlId).document.selection.createRange();
}
function fLoadPos() {
	if (gEditorTxtRange) {
		fSetEditorFocus();
		gEditorTxtRange.select();
		gEditorTxtRange = null;
	}
}
//a
function fIndexCreater(a) {
	var idx = {};
	for (var i = a.length - 1; i >= 0; i--) idx[a[i]] = i;
	return idx;
}
//A
function fSetEditable( d ){
	d = d || F(gHtmlId).document;

	if ( d.designMode && d.designMode.toString().toLowerCase() == "off" )
		d.designMode = "on";
	else
		d.body.contentEditable = true;
	
	try{d.execCommand("useCSS", false, false);}catch(e){}
}
function fSetEditorContent( d, content ) {
	d.open();
	d.writeln ([
	'<html>', 
		'<head><style>', 
			'body {padding:4px 4px;*padding:1px 4px;font:normal 14px Verdana;background:#fff}',
			'body, p, font, div, li { line-height: 160%;}',
			//'p {margin:0;padding:0;display:block;}',
			'pre {white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;}', 
		'</style></head>', 
		'<body>', content, '</body>', 
	'</html>'
	].join( "" ) );
	d.close();
}
function fSetEditorFocus( pos, d ) {
	var o = d && d.parentWindow;
	var isWindow = true;

	if ( !o ) {
		switch(gEditorCurId) {
			case gHtmlId:
				o = F(gHtmlId);
				break;
			case gSourceId:
			case gTextId:
				o = S(gEditorCurId);
				isWindow = false;
				break;
		}
	}

	if ( isWindow ) {
		try {
			var obj = o.parent.document.activeElement;
			obj = obj && obj.tagName == "IFRAME" ? obj.contentWindow : null;
			if ( o != obj )
				o.focus();
		}
		catch( e ) {
			o.focus();
		}
	}
	else {
		o.focus();
	}

	if (typeof(pos) == "number")
	{
		if (gIsIE) {
			var r = o.createTextRange ? o.createTextRange() : o.document.body.createTextRange();
			r.moveStart("character", pos);
			r.collapse(true);
			r.select();
		}
		else {
			if ( o.document ) {
				o.getSelection().collapse( o.document.body, pos );
			}
			else {
				o.selectionStart = pos;
				o.selectionEnd = pos;
			}
		}
	}
}
function fSetToolBarChangeBtn() {
	var o = S( gEditorToolBarBtnContainerId );
	var t = T( [
		"<a onclick='fDispToolBar($parm$);' unselectable='on' title='$title$' style='$style$'>", 
			"<input type='button'  style='background:url(", gEditorPath, "images/editoricon.gif) -514px -4px;", 
			"width:18px;height:14px;border:none;padding:0;vertical-align:middle!important;vertical-align:auto;'>", 
			"$text$", 
		"</a>" ].join( "" ) );
	if (o) 
		o.innerHTML = [ 
			t.replace( {parm:1, title:"显示文字格式工具条", text:"文字格式↓"} ),
			t.replace( {parm:0, title:"隐藏格式编辑工具条", text:"文字格式↑", style:"display:none"} )
		].join( "" );
}
//A
function fFixHtmlContent( d ) {
	if ( gIsIE ) {
		E( GelTags("div", d || F(gHtmlId).document), function( node ) {
			var childs = node.childNodes;
			if ( childs.length == 1 && node.innerHTML == "&nbsp;" )
				node.innerHTML = "";
		} );
	}
}

//AA ini fun
function fEditorOnLoad(content, bFocus) {
	S(gHtmlId).hideFocus = true;

	var d = F(gHtmlId).document;

	gEditorCurId = gHtmlId;

	fSetEditorContent( d, content );
	fSetEditable( d );
	fFixHtmlContent( d );
	//del 2
	Show( "HtmlEditorLoading", false );
}
//AA
function fEditorInit(content, bTB, bTBP, bTBPinTB, bTBPSep, bTBPPhoto, bTBPMo, 
	bTBPSnap, bTBPMusic, bFocus, sTBPUi, oTBSet) {

	if ( !S(gHtmlId) ) {
		return false;
	}

	fEditorOnLoad(content, bFocus);

	//把这里的操作变成异步,优先原始编辑器
	if ( !gIsSafari ) {
		var img = new Image();
		img.onload = img.onerror = function() {
			fSetToolBarChangeBtn();
			fDispToolBar(bTB, bTBPinTB);
		};
		img.src = [gEditorPath, "images/editoricon.gif"].join("");
	}

	return true;
}
function DoProcess(){
	var c = GetContent();
	if(c == "" || c ==null || c==fGetBreakLine(1) || c==fGetBreakLine(1).toUpperCase().replace(/NBSP/g,"nbsp"))
	{
	    return false;	
	}
	else
	{
		if(gFrame==1){
		    document.getElementsByName(gContentId)[0].value = c;
		}else{
			parent.document.getElementsByName(gContentId)[0].value = c;
		}
		return true;	
	}
}

//为了避免由于信件标签不规范导致无法进行初始化现象
fAddEvent(window, "load", function(){
	gIsPageLoadedFinish = true;
	if(gIsInitEditor == 0 && location.href.indexOf("readmail_group") == -1)
		IniEditor(window.noinclude?window.noinclude:0);
});
fAddEvent(window, "unload", function() {
	//top.CancelDoSend();
	//top.HideModelDialog();
})
