/*
Tencent QQMail HtmlEditor 2007 Version
File:		editor.js
Author:	angusdu
Date:	07-3-19
Usage: must import editor.css first; use this script and write iframe in html with id=HtmlEditor
*/

/*--------------------------------global base def & fun-------------------------*/
var gsAgent = navigator.userAgent;
var gfAppVer = parseFloat(navigator.appVersion);
var gIsOpera = gsAgent.indexOf("Opera") > -1;
var gIsKHTML = gsAgent.indexOf("KHTML") > -1 || gsAgent.indexOf("Konqueror") > -1 || gsAgent.indexOf("AppleWebKit") > -1;
var gIsSafari = gsAgent.indexOf("AppleWebKit") > -1;
var gIsIE = gsAgent.indexOf("compatible") > -1 && !gIsOpera;//&& gsAgent.indexOf("MSIE") > -1;
var gIsTT = gIsIE ? (navigator.appVersion.indexOf("TencentTraveler") != -1 ? 1 : 0) : 0;
var gIsFF = gsAgent.indexOf("Gecko") > -1 && !gIsKHTML;
var gIsNS = !gIsIE && !gIsOpera && !gIsKHTML && (gsAgent.indexOf("Mozilla") == 0) && (navigator.appName == "Netscape");
if (gIsIE) {
	var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
	reIE.test(navigator.userAgent);
	var gIEVer = parseFloat(RegExp["$1"]);
}


var gd = document;
function Gel(id, ob) {
	return (ob ? ob : gd).getElementById(id);
}
function GelTags(tag, ob) {
	return (ob ? ob : gd).getElementsByTagName(tag);
}
function S(i, win) {
	return (win?win:window).document.getElementById(i);
}
function SO(i, o) {
	return Gel(i, o);
}
function SN(i, win) {
	return (win?win:window).document.getElementsByName(i);
}
function SNO(i, o) {
	return (o ? o : gd).getElementsByName(i);
}
function F(sID, win) {
	if(!sID) return null;
	var frame = S(sID, win);
	if(!frame) return null;
	return frame.contentWindow?frame.contentWindow:(win?win:window).frames[sID];
}
function fAddEvent(oTarget, sType, fHandler, bRemove) {
	if (oTarget.addEventListener) {
		bRemove ? oTarget.removeEventListener(sType, fHandler, false) : oTarget.addEventListener(sType, fHandler, false);
	}
	else if (oTarget.attachEvent) {
		bRemove ? oTarget.detachEvent("on" + sType, fHandler) : oTarget.attachEvent("on" + sType, fHandler);
	}
	else {
		oTarget["on" +sType] = bRemove ? null : fHandler;
	}
}
function PutTextareaValue(o, val) {
	if (o.tagName != "TEXTAREA" && o.tagName != "textarea") return false;
	o.innerText != null ? o.innerText = val : o.value = val;
	return true;
}

function AddTextareaValue(o, val) {
	if (o.tagName != "TEXTAREA" && o.tagName != "textarea") return false;
	o.innerText != null ? o.innerText += val : o.value += val;
	return true;
}

function GetTextareaValue(o) {
	if (o.tagName != "TEXTAREA" && o.tagName != "textarea") return null;
	return o.value;
}
function TextToHtml(content) {
	//the attr of innerHTML in firefox is diff in ie
	var res = "<DIV>" + content.replace((content.indexOf("<BR>") >= 0)? /<BR>/ig: /\n/g, "</DIV><DIV>") + "</DIV>";
	res = res.replace(new RegExp("\x0D","g"), "");
	res = res.replace(new RegExp("\x20","g"), "&nbsp;");
	res = res.replace(new RegExp("(<DIV><\/DIV>)*$","g"), "");
	return res.replace(/<DIV><\/DIV>/g, "<DIV>&nbsp;</DIV>");
}
function HtmlToText(content) {
	//function for firefox
	//manal change div,p,br
	var res = content.replace(/<\/div>/ig, "\n");
	res = res.replace(/<\/p>/ig, "\n");
	return res.replace(/<br>/ig, "\n");
}

/*--------------------------------editor start-------------------------*/
//global def
var gHtmlId = "HtmlEditor";
var gSourceId = "SourceEditor";
var gTextId = "TextEditor";
var gEditorCurId = null;
var gEditorPath = "/public/external/edit/";
var gEditorToolBarId = "editor_toolbar";
var gEditorToolBarBtnContainerId = "editor_toolbar_btn_container";
var gEditorToolBarPlusId = "editor_toolbar_plus";
var gEditorToolBarPlusBtnContainerId = "editor_toolbar_plus_btn_container";
var gEditorToolBarPlusMode = 0;
var gEditorToolBarPlusContainerId = "editor_toolbar_plus_container";
var gEditorTxtRange = null;

var gBgMusic = "";

/*--------------------------------editor interface-------------------------*/
function IniQQMailEditor(
	content, 
	bIsDispToolBar, 
	bIsDispToolBarPlus, 
	bTooBarPlusAddInToolBar, 
	bIsDispToolBarPlusSepLine, 
	bIsDispToolBarPlusPhoto, 
	bIsDispToolBarPlusMo, 
	bFocus) {
	fEditorInit(
		content, 
		bIsDispToolBar, 
		bIsDispToolBarPlus, 
		bTooBarPlusAddInToolBar, 
		bIsDispToolBarPlusSepLine, 
		bIsDispToolBarPlusPhoto, 
		bIsDispToolBarPlusMo, 
		bFocus);
}

function AddContent(content) {
	switch(gEditorCurId) {
		case gHtmlId:
			return fAddContent(content);
		case gSourceId:
			return AddTextareaValue(S(gSourceId), content);
		case gTextId:
			if (!fAddContent(gIsIE ? content : HtmlToText(content))) return AddTextareaValue(S(gTextId), "数据加载失败!"); 
			return AddTextareaValue(S(gTextId), fGetPlainContent());
	}
	return false;
}

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;
}
//0:html 1:text 2:<->
function ChangeContentType(flag, nowarn) {
	var h = S(gHtmlId);
	var d = S("editor_text_span");
	var c = (gEditorCurId != gTextId);
	if ((c && !flag) || (!c && flag == 1)) return ;

	var t = S("contenttype");
	if (!nowarn && c && (flag == 2 || flag == 1) && !window.confirm("转换信件为纯文本格式有可能丢失某些格式，确定使用纯文本吗？")) {
		t && t.checked ? t.checked = false : null;
		return fSetEditorFocus();
	}
	t && t.checked ? t.checked = (c ? true : false) : null;

	try{fClearBGMusic();}catch(e){}
	try{fChangeEditor(0);}catch(e){}

	if (!d) {
		d = document.createElement("div");
		d.id = "editor_text_span";
		d.innerHTML = "<textarea  class=editor_source id='"+gTextId+"' style='height:"+h.style.height+";'>"+s+"</textarea>";
		fDisp(d, 0);
		h.nextSibling ? h.parentNode.insertBefore(d, h.nextSibling) : h.parentNode.appendChild(d);
	}

	var s = S(gTextId);
	gEditorCurId = c ? gTextId : gHtmlId;
	PutContent(c ? fGetContent() : TextToHtml(GetTextareaValue(s)));

	fDisp(h, 2);
	fDisp(d, 2);
	fDisp(S(gEditorToolBarBtnContainerId), 2);
	fDisp(S(gEditorToolBarPlusBtnContainerId), 2);
	fDisp(S(gEditorToolBarPlusContainerId), 2);
	fDisp(S(gEditorToolBarId), 2);
	return fSetEditorFocus();
}
function IsEditorLoadFinish() {
	return gEditorCurId != null;
}

//toolbar & plus callback inteface
function fDispToolBar(flag) {
	var tb = S(gEditorToolBarId);
	if (!tb && flag == 0) return;
	if (!tb) {
		setTimeout('fLoadJsFile(gEditorPath+"editor_toolbar.js", 1)', 0);
		if (gEditorToolBarPlusContainerId == "editor_toolbarplus") fDispToolBarPlus(1);
	}
	fDisp(tb, flag);
	var t = S(gEditorToolBarBtnContainerId);
	if (t) {
		t = t.childNodes;
		fDisp(t[0], 2);
		fDisp(t[1], 2);
	}
}
function fDispToolBarPlus(flag) {
	var tbp = S(gEditorToolBarPlusId);
	if (!tbp && flag == 0) return ;
	if (!tbp) {
		if (!gEditorToolBarPlusContainerId) return;
		setTimeout('fLoadJsFile(gEditorPath+"editor_toolbar_plus.js", 1)', 0);
		//return;
	}
	fDisp(tbp, flag);
	var t = S(gEditorToolBarPlusBtnContainerId);
	if (t) {
		t = t.childNodes;
		fDisp(t[0], 2);
		fDisp(t[1], 2);
	}
}
function fLoadEditorToolBarCallBack() {
	if (S(gEditorToolBarId)) return;
	if (!S(gHtmlId)) {
		setTimeout("fLoadEditorToolBarCallBack();", 300);
		return;
	}
	var d = document.createElement("div");
	d.innerHTML = fGenToolBarHtml();
	S(gHtmlId).parentNode.insertBefore(d, S(gHtmlId));
}
function fLoadEditorToolBarPlusCallBack() {
	if (S(gEditorToolBarPlusId) || !gEditorToolBarPlusContainerId) return;
	//Here check HtmlEditor exist for controling the plus disp delay HtmlEditor
	if (!S(gEditorToolBarPlusContainerId)) {
		setTimeout("fLoadEditorToolBarPlusCallBack();", 300);
		return;
	}
	var d = document.createElement("span");
	d.innerHTML = fGenToolBarPlusHtml();
	S(gEditorToolBarPlusContainerId).appendChild(d);
}

//base fun
function fLoadJsFile(file, checked) {
	if (checked) {
		var s = GelTags("script");
		for (var i = s.length - 1; i >= 0; i--) {
			if (s[i].src.indexOf(file) != -1) return;
		}
	}
	var o = document.createElement("script");
	o.language = "javascript";
	o.src = file;
	document.getElementsByTagName("head")[0].appendChild(o);
}
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 += templ.join("");
	}
	return code;
}
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 fPutContent(content) {
	try {F(gHtmlId).document.body.innerHTML = content;}catch(e){return false;}
	setTimeout(function(){fSetEditable();}, 0);
	return true;
}

function fAddContent(content) {
	try {F(gHtmlId).document.body.innerHTML += content;}catch(e){return false;}
	setTimeout(function(){fSetEditable();}, 0);
	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 fIsInObj(nObj, oObj) {
	if (typeof(oObj) == "string" ? nObj.id == oObj : nObj == oObj) return true;
	var p = nObj.parentNode;
	if(p) return fIsInObj(p, oObj);
	return false;
}
function fSavePos() {
	if (document.selection) gEditorTxtRange = F(gHtmlId).document.selection.createRange();
}
function fLoadPos() {
	if (gEditorTxtRange) {
		fSetEditorFocus();
		gEditorTxtRange.select();
		gEditorTxtRange = null;
	}
}
function fIndexCreater(a) {
	var idx = {};
	for (var i = a.length - 1; i >= 0; i--) idx[a[i]] = i;
	return idx;
}
function fSetEditorStyle(d) {
	var b = d.body;
	b.style.background = "#fff";
	b.style.font = 'normal 14px Verdana';
	b.style.margin = "3px";
}
function fOnEditorClick() {
	try{fHideTBMenu();}catch(e){}
	try{fHideTBPMenu();}catch(e){}
}
function fOnEditorKeyPress() {
	//按键处理
}
function fSetEditorEvent(d, mode) {
	if (!mode) {
		fAddEvent(d, "click", fOnEditorClick, 1);
		fAddEvent(d, "click", fOnEditorClick);
	}
	fAddEvent(d, "click", fOnEditorKeyPress, 1);
	fAddEvent(d, "click", fOnEditorKeyPress);
}
function fSetEditable(){
	var d = F(gHtmlId).document;
	d.designMode = "on";
	if(!gIsIE) try{d.execCommand("useCSS", false, false);}catch(e){}
}
function fSetEditorFocus() {
	switch(gEditorCurId) {
		case gHtmlId:
			F(gHtmlId).focus();
			break;
		case gSourceId:
		case gTextId:
			S(gEditorCurId).focus();
			break;
	}
	return;
}
function fSetEditorCursorToStart() {
	try{
		var el = fIsDisp(gHtmlId) ? F(gHtmlId) : S(gSourceId);
		el.focus();
		if (gIsIE) {
			var sel=document.selection.createRange();
			sel.moveToPoint(0,0);
			sel.select();
		}
		else {
			//由于firefox在html编辑器上失效，所以干脆屏蔽了
			el.selectionStart = 0;
			el.selectionEnd = 0;
		}
	}catch(e){}
}
function fSetToolBarChangeBtn() {
	var o = S(gEditorToolBarBtnContainerId);
	if (o) o.innerHTML = "<a onclick='fDispToolBar(1);'>显示工具条↓</a><a onclick='try{fChangeEditor(0);}catch(e){}fDispToolBar(0);' style='display:none;'>隐藏工具条↑</a>"; 
}
function fSetToolBarPlusChangeBtn() {
	var o = S(gEditorToolBarPlusBtnContainerId);
	if (o) o.innerHTML = "<a onclick='fDispToolBarPlus(1);'>显示插件条</a><a onclick='fDispToolBarPlus(0);' style='display:none;'>隐藏插件条</a>"; 
}
function fSetToolBarPlusInitData(containerId, bTBPSep, bTBPPhoto, bTBPMo) {
	gEditorToolBarPlusContainerId = containerId;
	gEditorToolBarPlusMode = (bTBPSep ? 4 : 0) + (bTBPPhoto ? 2 : 0) + (bTBPMo ? 1 : 0);
}

//ini fun
function fEditorOnLoad(content, bFocus) {
	try{
		var d = F(gHtmlId).document;
		if (!d.body) return setTimeout(function(){fEditorOnLoad(content, bFocus);}, 200);
		fSetEditorStyle(d);
		fSetEditorEvent(d);
		fSetEditorEvent(document, 1);	
		if (!fPutContent(content)) return setTimeout(function(){fEditorOnLoad(content, bFocus);}, 200);
		if (gIsNS) {setTimeout(function(){try{fPutContent(content);setTimeout(function(){fSetEditorStyle(F(gHtmlId).document);},0);}catch(e){}},0);}
		gEditorCurId = gHtmlId;
		try{
			//make sure ok!!! so -> try catch
			if (bFocus) fSetEditorFocus();
		}catch(e){}
	}catch(e){setTimeout(function(){fEditorOnLoad(content, bFocus);}, 200);}
}
function fEditorInit(content, bTB, bTBP, bTBPinTB, bTBPSep, bTBPPhoto, bTBPMo, bFocus) {
	if (!gIsSafari) {
		fSetToolBarPlusInitData(bTBPinTB ? "editor_toolbarplus" : gEditorToolBarPlusContainerId, bTBPSep, bTBPPhoto, bTBPMo);
		if (!bTBPinTB) {
			fSetToolBarPlusChangeBtn();
			fDispToolBarPlus(bTBP);
		}
		fSetToolBarChangeBtn();
		fDispToolBar(bTB, bTBPinTB);
	}
	fSetEditable();
	//just keep on fSetEditable and  fEditorOnLoad not in one process ok
	setTimeout(function(){fEditorOnLoad(content, bFocus)},0);
}
