

function GetDomain() {
	 return location.href.indexOf("foxmail.com") > -1 ? "foxmail.com" : "qq.com";
}

function RegFilter(str)
{
	return str.replace(/([\^\.\[\$\(\)\|\*\+\?\{\\])/ig, "\\$1");
}
function Template(t, f)
{
	var _t = t ? t : "";
	var _tD, _lD, _f = f ? f : "$", _rf = RegFilter(_f);
	var rP =  function(p) {
		if (!_tD) _lD = (_tD = _t.split( _f )).concat();
		for (var i = 1, _len = _tD.length; i < _len; i += 2) _lD[i] = p[_tD[i]];
		return _lD.join("");
	};
	var rRE = function(p) {
		return _t.replace(new RegExp([_rf, "(.*?)", _rf].join(""), "ig"), function(m, v){return p[v];});
	};
	this.toString = function() {
		return _t;
	};
	this.replace = function(p, defaultFunc) {
		return (defaultFunc == "parse" || !(document.all && !(/opera/i.test(navigator.userAgent))) ? rP : rRE)(p);
	};
};
function T(t, f)
{
	return new Template(t, f);
}

//activex api
var gActiveXCab = "TencentMailActiveX.cab";
var gActiveXExe = "TencentMailActiveXInstall.exe";
var gActiveXObj = [["TXGYMailActiveX.ScreenCapture", "TXGYMailActiveX.UploadFilePartition", "TXGYMailActiveX.Uploader", "TXFTNActiveX.FTNUpload"], ["FMO.ScreenCapture", "TXGYUploader.UploadFilePartition", "FMO.Uploader", "TXFTNActiveX.FTNUpload"]];
var gActivexLastVerNo = ["1.0.1.28", "1.0.1.29", "1.0.1.28", "1.0.0.3"];
var gEditorAxMinVer = [(GetDomain()=="foxmail.com")?"1.0.0.5":"1.0.0.28", "1.0.1.28", "1.0.1.28", "1.0.0.3"];
function CreateActiveX(activexId)
{
	if (activexId >= 0 && activexId <= 3)
	{
		for (var i = 0, len = gActiveXObj.length; i < len; i++)
		{
			try
			{
				var o = new ActiveXObject(gActiveXObj[i][activexId]);
				if (o)
				{
					return o;
				}
			}
			catch (e)
			{
			}
		}
	}
	return null;
}
//activexId: 0 - screen capture; 1 - upload file partition; 2 - upload; detectType: 0 - exist; 1 - min exist; 2 - new exist
function DetectActiveX(activexId, detectType)
{
	var activeXObj = CreateActiveX(activexId);
	if (activeXObj == null)
	{
		return false;
	}
	if (detectType != 1 && detectType != 2)
	{
		return true;
	}
	if (parseInt(GetActiveXVer(activeXObj).split(".").join("")) >= 
		parseInt((detectType == 1 ? gEditorAxMinVer : gActivexLastVerNo)[activexId].split(".").join("")))
	{
		return true;
	}
	else
	{
		return false;
	}
}
//parm: activexid or activexobj
function GetActiveXVer(parm)
{
	try
	{
		var activeXObj = typeof(parm) == "number" ? CreateActiveX(parm) : parm;
		var version = activeXObj ? (activeXObj.version ? activeXObj.version : "1.0.0.3") : "";
	}
	catch (e)
	{
		var version = "";
	}
	return version;
}

//global msg
var msgNoSubject = "请填写邮件主题";
var msgSend = "邮件正在发送中... ";
var msgSave = "&nbsp;&nbsp;&nbsp;邮件正在保存到草稿箱...";
var msgSaveOk = "邮件成功保存到草稿箱";
var msgAutoSave = "&nbsp;&nbsp;&nbsp;邮件正在保存到草稿箱...";
var msgAutoSaveOk = "邮件自动保存到草稿箱";
var msgSendErrorSaveOK = "信件已被保存到草稿箱";
var msgSaveErr = "邮件未能保存到草稿箱";
var msgNoSender = "请填写收件人后再发送";
var msgNoCardSender = "请填写收卡人后再发送";
var msgNoCard = "请选中贺卡后再发送";
var msgAddrSearchErr = "请输入搜索内容";
var msgMailSearchErr = "请输入搜索内容";
var msgSettingOk = "设置更改保存成功";
var msgWarnningType = "您的附件中包含可执行文件，出于安全性考虑，不允许发送此类文件";
var msgLinkErr = "网络应答失败";
var msgRejectAlert = "系统会把此邮件地址放入“黑名单”中，您将不再收到来自此地址的邮件。\n\n确认要拒收此发件人的邮件吗？";
//var msgSpamAlert = "您确定要举报此邮件吗？\n\n(您的举报会对" + ( ( GetDomain() == "qq.com" ) ? "QQ" : "Foxmail.com" ) + "邮箱反垃圾邮件工作有很大帮助。)";
var msgCheatAlert = "系统会将此邮件移入到“垃圾邮件”中，并把邮件内容提交给邮箱管理员。\n\n您确定要举报此邮件吗？";
var msgSendTimeErr = "您设置的发送时间不存在";
var msgCreateTimeErr = "您设置的时间不存在";
var msgRemindTimeErr = "您设置的提醒时间不存在";
var msgModifySendTimeMsg = "修改定时邮件将会被暂停发送，您确定要修改定时邮件吗？";
var msgSendMailNoMove="请不要选择定时邮件，您不能移动定时邮件。";
var msgMoveMailSameFldErr="不能移动到相同的目录";

//global base function
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 E(list, Func, start, end)
{
	if (!list) return;
	if (list.constructor == Array)
	{
		var len = list.length;
		for (var i = (start || 0), end = end < 0 ? (len + end) : (end < len ? end : len); i < end; i++)
		{
			try{Func(list[i], i, len);}catch(e){}
		}
	}
	else
	{
		for (var i in list)
		{
			try{Func(list[i], i);}catch(e){}
		}
	}
}
function DP(obj, property)
{
	try{delete obj[property];}catch(e){}
	return obj;
}
function InsertHTML(el, where, html)
{
	if (!el) return;
	if (el.insertAdjacentHTML)
	{
		el.insertAdjacentHTML(where, html);
	}
	else
	{
		var range = el.ownerDocument.createRange();
		var isBefore = where.indexOf("before") == 0;
		var isBegin = where.indexOf("Begin") != -1;
		if (isBefore == isBegin)
		{
			range[isBefore ? "setStartBefore" : "setStartAfter"](el);
			el.parentNode.insertBefore(range.createContextualFragment(html), isBegin ? el : el.nextSibling);
		}
		else
		{
			var obj = el[isBefore ? "lastChild" : "firstChild"];
			if (obj)
			{
				range[isBefore ? "setStartAfter" : "setStartBefore"](obj);
				el[isBefore ? "appendChild" : "insertBefore"](range.createContextualFragment(html), obj);
			}
			else
			{
				el.innerHTML = html;
			}
		}
	}
}
function GetSid() {
	try {var s = top.g_sid;}catch(e){}
	s = s ? s : (S("sid") ? S("sid").value : "");
	if (!s) {
		s = (top.location.href.split("?")[1]).split("&");
		s = s[0].split("=")[1];
	}
	return s;
}
function IsShow(obj) {
	obj = (typeof(obj) == "string" ? S(obj) : obj);
	if (!obj) return false;
	return obj.style.display != "none";
}
function Show(obj, bShow) {
	obj = (typeof(obj) == "string" ? S(obj) : obj);
	if (obj) obj.style.display= (bShow ? "" : "none");
}
function ShowN(name, bShow) {
	var o = SN(name);
	for (var i = o.length - 1; i >= 0; i--) {
		Show(o[i], bShow);
	}
}
function GetPath(type, bMustFull) {
	var p = "";
	switch (type) {
		case "image":
			try {p = top.images_path;}catch(e){}
			if(!p) p = "/zh_CN/htmledition/images/";
			break;
		case "js":
			try {p = top.js_path;}catch(e){}
			if(!p) p = "/zh_CN/htmledition/js/";
			break;
		case "css":
			try {p = top.css_path;}catch(e){}
			if(!p) p = "/zh_CN/htmledition/style/";
			break;
		case "stationery":
			try {p = top.stationery_path;}catch(e){}
			if(!p) p = "http://m33.mail.qq.com/";
			break;
		case "card":
			try {p = top.card_path;}catch(e){}
			if(!p) p = "http://m33.mail.qq.com/";
			break;
		case "mo":
			try {p = top.mo_path;}catch(e){}
			if(!p) p = "http://m33.mail.qq.com/";
			break;
		case "editor":
			try {p = top.editor_path;}catch(e){}
			if(!p) p = "/zh_CN/htmledition/qqmaileditor/";
			break;
		case "skin":
			try {p = top.skin_path;}catch(e){}
			if(!p) p = "0";
			break;
	}
	if (bMustFull && type != "skin" && p.indexOf("http://") == -1) p = "http://" + location.host + p;
	return p;
}
function GetEmptyCacheMethod()
{
	if (gIsIE)
	{
		return "Internet选项-->常规-->Internet临时文件-->删除文件-->确定";
	}
	if (gIsFF)
	{
		return "工具-->清除隐私数据-->立即清除隐私信息";
	}
	if (gIsOpera)
	{
		return "工具-->删除私人数据-->删除";
	}
	if (gIsSafari)
	{
		return "Edit-->Empty Cache-->Empty";
	}
	return "刷新页面";
}
function GetTopWin() {
	return top.topFrame ? top.topFrame : top;
}
function GetTempWin() {
	return top.tempFrame;
}
function GetMainWin() {
	return top.mainFrame ? top.mainFrame : top;
}
function GetActionWin() {
	return GetTopWin().actionFrame;
}
function GetLeftWin() {
	return top.leftFrame;
}
function GetSignatureWin() {
	return top.signatureFrame;
}
function CheckSignatureFrame()
{
	if (top.loadSignTimeout)
	{
		top.clearTimeout(top.loadSignTimeout);
		top.loadSignTimeout = null;
	}
	if (GetSignatureFrameObj().src)
	{
		top.signStatus = "finish";
		var isSuccess = true;
		try
		{
			if (!GetSignatureWin().GetUserSignature)
			{
				isSuccess = false;
			}
		}
		catch (e)
		{
			isSuccess = false;
		}
		if (!isSuccess)
		{
			// find err -> 1s after reload
			if (top.reloadSignTimeout == null)
			{
				top.reloadSignTimeout = top.setTimeout("top.ReloadSignature(true);", 5000);
			}
		}
	}
}
function GetSignatureFrameObj()
{
	var sw = S("signatureFrame", top);
	if (!sw)
	{
		InsertHTML(top.document.body, "afterBegin", "<iframe id='signatureFrame' name='signatureFrame' style='display:none;' onload='top.CheckSignatureFrame();'></iframe>");
		sw = S("signatureFrame", top);
	}
	return sw;
}
function LoadSignature()
{
	try
	{
		if (GetSignatureFrameObj().src == "")
		{
			ReloadSignature();
		}
	}
	catch(e) {return;}
	if (top.signStatus != "finish")
	{
		throw {message: "get sign error..."};
	}
}
function ReloadSignature(isError, isDispQzone)
{
	if (isError)
	{
		if (top.gReloadSignatureErrorTime == null)
		{
			top.gReloadSignatureErrorTime = 0;
		}
		if (top.gReloadSignatureErrorTime > 4)
		{
			return;
		}
		top.gReloadSignatureErrorTime++;			
	}

	if (top.reloadSignTimeout)
	{
		top.clearTimeout(top.reloadSignTimeout);
		top.reloadSignTimeout = null;
	}
	top.signStatus = "load";
	GetSignatureFrameObj().src = 
		["/cgi-bin/getcomposedata?templatename=signature&fun=compose&r=", (new Date()).getTime(), 
			"&sid=" + GetSid(), isDispQzone ? "&qzonesign=disp" : ""].join("");
	if (top.loadSignTimeout)
	{
		top.clearTimeout(top.loadSignTimeout);
		top.loadSignTimeout = null;
	}
	top.loadSignTimeout = top.setTimeout("top.CheckSignatureFrame();", 10000);
}
function GetSignature(bReplaced) {
	try{return bReplaced ? GetSignatureWin().GetReplacedSignature() : GetSignatureWin().GetUserSignature();}
	catch(e){LoadSignature();return "";}
}
function GetHasQzoneSign() {
	try{return GetSignatureWin().HasQzoneSign();}
	catch(e){LoadSignature();return 0;}
}
function GetDetaultStationery(type)
{
	try{return type == "Header" ? GetSignatureWin().GetUserDefaultStationeryHeader() : GetSignatureWin().GetUserDefaultStationeryBottom();}
	catch (e){	LoadSignature();return "";}
}
function GetDefaultEditor() {
	try{return GetSignatureWin().GetUserDefaultEditor();}
	catch(e) {LoadSignature();return 0;}
}
function GetUserNick(){
	try{return GetSignatureWin().GetUserNick();}
	catch(e) {LoadSignature();return 0;}
}
function GetDefaultSaveSendbox() {
	try{return GetSignatureWin().GetSaveSendbox();}
	catch(e){LoadSignature();return 0;}
}
function GV_GetUserAlias() {
	try{return GetSignatureWin().GetUserAlias();}
	catch(e) {LoadSignature();return "";}
}
function GetDefalutAllMail() {
	try{return GetSignatureWin().GetAllMail();}
	catch(e) {LoadSignature();return "";}
}
function GetIsQQClub() {
	try {return GetSignatureWin().IsQQClub();}
	catch(e) {LoadSignature();return false;}
}
function GetDefaultCardCates() {
	try {return GetSignatureWin().GetCardCates();}
	catch(e) {LoadSignature();return [[]];}
}
function GetUserInfoText(type) {
	try{
		var o = S("user" + type, GetTopWin());
		var val = o.innerText == null ? o.textContent : o.innerText;
	}catch(e){}
	return val ? val : "";
}
function GetUserInfo(type) {
	try{
		var o = S("user" + type, GetTopWin());
		var val = o.innerHTML;
	}catch(e){}
	return val ? val : "";
}
function SetUserInfo(type, val) {
	try{
		S("user" + type, GetTopWin()).innerHTML = HtmlEncode(val);
		return true;
	}catch(e){return false;}
}
//js cookie operation global function
function SetCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) {
	if (sName == null && sValue == null) return false;
	var sCookie = sName + "=" + encodeURIComponent(sValue);
	if (oExpires) 	sCookie += "; expires=" + oExpires.toGMTString();
	if (sPath) sCookie += "; path=" + sPath;
	if (sDomain) 	sCookie += "; domain=" + sDomain;
	if (bSecure) sCookie += "; secure";
	gd.cookie = sCookie;
	return true;
}
function GetCookie(sName) {
	var oRE = new RegExp("(?:; )?" + sName + "=([^;]*);?");
	return oRE.test(gd.cookie) ? decodeURIComponent(RegExp["$1"]) : null;
}
function DeleteCookie(sName, sPath, sDomain) {
	SetCookie(sName, "", new Date(0), sPath, sDomain);
}
function GetCookieFlags(_name) {
   var a=GetCookie(_name);
   if(null==a)a="";
   for(var i=a.length;i<6;i++) a+='0';
   return a.split("");
}
function SetCookieFlag(_name,i,flag,_cookie) {
	 if(null==_cookie) _cookie=GetCookieFlags(_name);
	 _cookie[i]=flag;
	 var expdate = new Date();
	 expdate.setTime(expdate.getTime() + ( 30 * 24 * 3600 * 1000 ));
	 SetCookie(_name, _cookie.join(""), expdate, '/', GetDomain());
	 return _cookie;
}
//Event Mng Fun
function fAddEvent(oTarget, sType, fHandler, bRemove) {
	if (!oTarget)
	{
		return;
	}
	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 fRemoveEvent(oTarget, sType, fHandler) {
	if (!oTarget)
	{
		return;
	}
	if (oTarget.removeEventListener) {
		oTarget.removeEventListener(sType, fHandler, false);
	} 
	else if (oTarget.detachEvent) {
		oTarget.detachEvent("on" + sType, fHandler);
	}
	else {
		oTarget["on" + sEventType] = null;
	}
}
function fPreventDefault(oEvent)
{
	if (oEvent.preventDefault)
	{
		oEvent.preventDefault();
	}
	else
	{
		oEvent.returnValue = false;
	}
}
function fStopPropagation(oEvent)
{
	if (oEvent.stopPropagationi)
	{
		oEvent.stopPropagationi();
	}
	else
	{
		oEvent.cancelBubble = true;
	}
}
function fLoadJsFile(file, checked, doc) {
	doc = doc ? doc : document;
	if (checked) {
		var s = GelTags("script", doc);
		for (var i = s.length - 1; i >= 0; i--) {
			if (s[i].src.indexOf(file) != -1) return;
		}
	}
	var o = doc.createElement("script");
	o.language = "javascript";
	o.charset = "gb2312";
	o.src = file;
	var h = GelTags("head", doc)[0];
	if (h) h.appendChild(o);
}
function fLoadCssFile(file, checked, doc) {
	doc = doc ? doc : document;
	if (checked) {
		var s = GelTags("link", doc);
		for (var i = s.length - 1; i >= 0; i--) {
			if (s[i].href.indexOf(file) != -1) return;
		}
	}
	var o = doc.createElement("link");
	o.type = "text/css";
	o.rel = "stylesheet";
	o.href = file;
	var h = GelTags("head", doc)[0];
	if (h) h.appendChild(o);
}
function fReplaceCssFile(pattern, file, doc)
{
	if (!pattern || !file) return;
	doc = doc || document;

	var s = GelTags("link", doc);
	E(s, function(o)
	{
		if (o.href.indexOf(pattern) != -1)
		{
			o.parentNode.removeChild(o);
		}
	});

	if (file) fLoadCssFile(file, false, doc);
}
function fReplaceCss(win, skinId)
{
	fReplaceCssFile("skin", [GetPath("css", true), "skin", (skinId || top.skin_path), ".css"].join(""), (win || window).document);
}
function fChangeStyle(skinId)
{
	skinId = skinId || top.skin_path;
	top.gTempSkinId = skinId;

	try { S("imglogo", top).style.backgroundImage = 
		S("imglogo", top).style.backgroundImage.replace(/_[0-9]*_/, ["_", skinId, "_"].join(""));} catch(e) {}

	var wins = [top, GetLeftWin(), GetMainWin()];
	E(top.dialog_list, function(o, i) {wins.push(F(i, top));});

	E(wins, function(o) {fReplaceCss(o, skinId);});
}
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;
}
//object rewrite --> for ie active problom
function fParamsInTag(o) {
	var c = "";
	var p = GelTags("PARAM", o);
	for (var i = p.length - 1; i >= 0; i--) {
		c += p[i].outerHTML;
	}
	return c;
}
function fTagRewrite(tag, doc) {
	var o = GelTags(tag, doc);
	for (var i = o.length - 1; i >= 0; i--) {
		o[i].outerHTML = o[i].outerHTML.split(">")[0] + ">" + fParamsInTag(o[i]) /*+ o[i].innerHTML*/ + "</" + o[i].tagName + ">";
	}
}
function fObjectActive(doc) {
	if (gIsIE) {
		fTagRewrite("embed", doc);
		fTagRewrite("object", doc);
	}
}
//quick replace
function StrReplace(s, o, d) {
	return s.replace(new RegExp(o), d);
}
function HighLight(filter, head, end) {
	return function(str) {
		return str.replace(new RegExp(["(", RegFilter(filter), ")"].join(""), "ig"), [head, "$1", end].join(""));
	};
}
//textarea api
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 GetTextareaValue(o) {
	if (o.tagName != "TEXTAREA" && o.tagName != "textarea") return null;
	return o.value;
}
//other api
function ScrollIntoMidView(obj, container, bforce, win) {
	if (!container) container = (win ? win : window).document.body;
	var ot = 0;
	for (var o = obj; o && o != container;o = o.offsetParent) ot += o.offsetTop;
	var h = ot - container.scrollTop;
	if (bforce || h < 0 || h + obj.offsetHeight  > container.clientHeight) {
		container.scrollTop = ot - (container.clientHeight - obj.offsetHeight) / 2
	}
}
//
if(!Function.prototype.apply) {
	Function.prototype.apply = function (obj, argu) {
		if (obj) obj._caller = this;
		var argus = new Array();
		for (var i=0;i<argu.length;i++) {
			argus[i] = "argu[" + i + "]";
		}
		var r;
		eval("r = " + (obj ? ("obj._caller(" + argus.join(",") + ");") : ("this(" + argus.join(",") + ");"))); 
		return r;
	};
}
if(!Array.prototype.push) {
	Array.prototype.push=function() {
		for(var i=0;i<arguments.length;i++) {
			this[this.length]=arguments[i];
		}
	}
}

//出错显示函数 －－ 取代alert的显示
//mbtype消息框类型,默认为提示提示框
//mbtype  success 成功
//              空          错误
//              moduel  弹出框
function fMessageBox(msg, mbtype, bHide, hidetime, dialogTitle, win) {
	try
	{
		win = win ? win : window;
		if (msg == null)
		{
			var oMsgObj = S("msg_txt", win) ? S("msg_txt", win) : S("msg_txt", GetActionWin());
			if (oMsgObj)
			{
				var txt = oMsgObj.innerText == null ? oMsgObj.textContent : oMsgObj.innerText;
				if (txt) 
				{
					return setTimeout(function(){fMessageBox(oMsgObj.innerHTML.replace(/<script .*>(.|\n)*<\/script>/ig, ""), mbtype, bHide, hidetime, dialogTitle, win);}, 0);
				}
			}
			return;
		}
		if (!msg)
		{
			return;
		}
		if (mbtype == "dialog")
		{
			GetActionWin().document.body.innerHTML = "";
			return ModelDialog(1, dialogTitle ? dialogTitle : "确认",
				"<div style='padding:10px 0 5px 10px;text-align:left;'>" + 
					"<img src='"+GetPath("image", true)+"ico_question.gif' align='absmiddle' style='float:left;margin:5px 0 0 10px;'>" + 
					"<div style='width:300px;height:80px;overflow:hidden;'><table width=300px height=80px><tr><td>" + msg + "</td></tr></table></div>" + 
				"</div>" +
				"<div style='text-align:right;padding:0 10px 10px 0;'>" + 
					"<input class='wd2 btn' type=button id=confirm value=确认>" + 
				"</div>", "confirm", ["confirm"],[function(){HideModelDialog();}]);
		}
		top.bMessageBoxHide = bHide;
		var actionBody = GetActionWin().document.body;
		var divstyle = (mbtype=="success"?"msg":"errmsg");
		
		actionBody.innerHTML = 
		"<body>" +
			"<link rel='stylesheet' type='text/css' href='"+GetPath("css", true)+"comm.css' />" +
			"<link rel='stylesheet' type='text/css' href='"+GetPath("css", true)+"skin"+GetPath("skin")+".css' />" +	
			'<div id="msg" class="'+divstyle+'" style="' + ((hidetime == 0 && bHide) ? "display:none;" : "") + '">' + msg + '</div>' +
		"</body>";
		actionBody.className = "";
		actionBody.style.margin = "0";
		actionBody.style.backgroundColor = "transparent";
		actionBody.style.textAlign = "center";
		if(bHide && hidetime != 0)
		{
				if (top.msgBoxTimer)
				{
					top.clearInterval(top.msgBoxTimer);
					top.msgBoxTimer = null;
				}
				top.msgBoxTimer = top.setInterval("top.clearInterval(top.msgBoxTimer);top.msgBoxTimer=null;top.HiddenMsg();", hidetime ? hidetime : 5000);
		}
	} 
	catch(e)
	{
		var w = S("actionFrame", GetTopWin());
		if (w)
		{
			w.src = "about:blank";
			showError("未知错误");
		}
		else
		{
			//暂时为read_note特殊处理,显示不存在的note的错误提示
			var m = S("msg_txt");
			if(m) m.style.display = "block";
		}
	}
}
function showError(err, dtime) {
	fMessageBox(err, "", true, dtime? dtime:5000);
}
function showInfo(info, dtime) {
	fMessageBox(info, "success", true, dtime? dtime:5000);
}
function HiddenMsg() {
	Show(S("msg",GetActionWin()), false);
}
function ShowMsg() {
	Show(S("msg",GetActionWin()), true);
}
//maximize
function IsMaximizeMainFrame() {
	if (top.isMaximizeMainFrame == null)
	{
		var o = S("mainFrame", top);
		if (o) top.isMaximizeMainFrame = o.parentNode.style.marginLeft == "6px";
	}
	return top.isMaximizeMainFrame;
}
function MaximizeMainFrame(bMax) {
	bMax = bMax != null ? bMax : 1;
	var o = S("mainFrame", top);
	var img = S("img_line", top);
	if (!o || !img || bMax == (IsMaximizeMainFrame() ? 1 : 0))
	{
		return false;
	}
	o = o.parentNode;
	bMax = bMax == 2 ? (IsMaximizeMainFrame() ? 0 : 1) : bMax;
	top.isMaximizeMainFrame = bMax;

	if (top.maximizeTimer)
	{
		top.clearInterval(top.maximizeTimer);
		top.maximizeTimer = 0;
	}

	var leftFrame = S("leftFrame", top).parentNode;
	var value = [parseInt(o.style.marginLeft), parseInt(leftFrame.style.width)];
	try
	{
		var step = GetMainWin().location.href.indexOf("/cgi-bin/mail_list?") != -1 ? 100 : 40;
	}
	catch(e)
	{
		var step = 40;
	}
	step = (bMax ? -1 : 1) * step;

	Show(leftFrame, true);
	Show(img, true);
	top.maximizeTimer = top.setInterval(function()
	{
		value[0] = value[0] + step;
		value[1] = value[1] + step;
		if (bMax ? (value[1] < 0) : (value[1] > "188"))
		{
			top.clearInterval(top.maximizeTimer);
			top.maximizeTimer = 0;
			o.style.marginLeft = bMax ? "6px" : (gIsIE ? "188px" : "191px");
			Show(leftFrame, !bMax);
			Show(img, !bMax);
			return;
		}
		o.style.marginLeft = value[0];
		leftFrame.style.width = value[1];
	}, 10);

	return true;
}
function GetHttpProcesser()
{
	var httpProcesser = top.gCurHttpProcesser;
	httpProcesser = httpProcesser == null ? 0 : httpProcesser;
	top.gCurHttpProcesser = (httpProcesser + 1) % 30;
	try
	{
		if (top.gHttpProcesserContainer[httpProcesser] != null)
		{
			delete top.gHttpProcesserContainer[httpProcesser];
		}
	}
	catch (e)
	{
		top.gHttpProcesserContainer = {};
	}
	top.gHttpProcesserContainer[httpProcesser] = new Image();
	return top.gHttpProcesserContainer[httpProcesser];
}
function RunUrlWithSid(param)
{
	try
	{
		var obj = GetHttpProcesser();
		if (obj) obj.src = param + "&sid="+GetSid() + "&r=" + Math.random();
	}
	catch(e){}
}
function SetKeepAlive(win)
{
	if (top.gKeepAliveNum == null)
	{
		top.gKeepAliveNum = 0;
	}
	if (win == null || win.gHasSetKeepAlive == true)
	{
		return;
	}
	win.gHasSetKeepAlive = true;
	top.gKeepAliveNum++;
	if (top.gKeepAliveTimer == null)
	{
		//15 minute
		top.gKeepAliveTimer = top.setInterval(function()
		{
			top.RunUrlWithSid("/cgi-bin/readtemplate?templatename=keep_alive");
		}, 900000);
	}
	fAddEvent(win, "unload", function()
	{
		win.gHasSetKeepAlive = false;
		top.gKeepAliveNum--;
		if (top.gKeepAliveNum == 0)
		{
			top.clearInterval(top.gKeepAliveTimer);
			top.gKeepAliveTimer = null;
		}
	});
}
function RecodeComposeStatus(actionId, mailid, failCode, isMust)
{
	if (!top.gSendTimeStart || !top.gSendTimeStart.valueOf)
	{
		if (isMust)
		{
			var time = 0;
		}
		else
		{
			return;
		}
	}
	else
	{
		var time = (new Date()).valueOf() - top.gSendTimeStart.valueOf();
		top.gSendTimeStart = null;
	}
	RunUrlWithSid("/cgi-bin/getinvestigate?stat=compose_send&t="+time+"&actionId="+actionId+"&mailid="+(mailid == null ? "" : mailid) + "&isActivex=" + (top.isUseActiveXCompose ? 1 : 0) + "&failCode=" + (failCode == null ? "" : failCode));
	top.isUseActiveXCompose = false;
}
function ReloadFrm(frm) {
	if (frm)
	{
		frm.location.replace(frm.location.href);
	}
}
function ReloadAllFrm(bReloadTop, bReloadTemp, bReloadLeft, bReloadMain) {
	if(bReloadTop==null || bReloadTop) setTimeout("ReloadFrm(GetTopWin())",0);
	if(bReloadTemp==null || bReloadTemp) setTimeout("ReloadFrm(GetTempWin())",0);
	if(bReloadLeft==null || bReloadLeft) setTimeout("ReloadFrm(GetLeftWin())",0);
	if(bReloadMain==null || bReloadMain) setTimeout("ReloadFrm(GetMainWin())",0);
}
function ReloadFrmLeftMain(bReloadLeft, bReloadMain) {
	ReloadAllFrm(false, false, bReloadLeft, bReloadMain);
}
function ReloadFrmLeftMainNewWin(bReloadLeft,bReloadMain) {
	var op = top.opener;
	var hf = op ? (op.GetMainWin ? op.GetMainWin().location.href : "") : "";
	if (hf.indexOf("readmail") != -1) {
		op.top.GoUrlMainFrm("/cgi-bin/mail_list?sid="+ GetSid());
	}
	else if (hf.indexOf("mail_list") != -1) {
		op.top.ReloadFrmLeftMain(bReloadLeft,bReloadMain);
	}
}
function GoUrlMainFrm(url, bReloadLeft, bNoHistroy) {
	if (bNoHistroy)
	{
		GetMainWin().location.replace(url);
	}
	else
	{
		GetMainWin().location.href = url;
	}
	if(bReloadLeft==null || bReloadLeft==true)
	{
		setTimeout("ReloadFrm(GetLeftWin())",0);
	}
}
function HtmlDecode(s) {
	return (s == null)?s:s.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,"\"");
}
function HtmlEncode(s) {
	return (s == null)?s:s.replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
}
//editor api
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");
}
//do post finish check
function ActionFinishCheck()
{
	if (GetCookieFlags("CCSHOW")[4] == "1")
	{
		SetCookieFlag("CCSHOW",4,"0");
		S("actionFrame", GetTopWin()).src = "about:blank";
		return;
	}
	ErrorProcess();
	
	var isErrResponse = false;
	try 
	{
		var f = F("actionFrame", GetTopWin());
		var b = f.document.body;
		isErrResponse = !(f.location.href == "about:blank"  || b.className != "" || b.style.cssText != "");
		b.style.cssText = "background:transparent;margin:0;padding:0;height:22px;";
		InitPageEvent(f);
	}
	catch(e)
	{
		isErrResponse = true;
	}
	if (isErrResponse)
	{
		S("actionFrame", GetTopWin()).src = "about:blank";
		setTimeout(function(){showError(msgLinkErr);}, 0);	
	}
 }
function DoSendFinishCheck(frameObj)
{
	if (!frameObj.id)
	{
		return;
	}
	var responseContent = null;
	var isErrResponse = false;
	try 
	{
		var f = F(frameObj.id);
		var b = f.document.body;
		isErrResponse = !(f.location.href == "about:blank"  || b.className != "" || b.style.cssText != "");
		var tmp = f.document.documentElement;
		responseContent = encodeURIComponent((tmp.innerText == null ? tmp.textContent : tmp.innerText).substr(0, 30));
	}
	catch(e)
	{
		isErrResponse = true;
	}
	if (isErrResponse)
	{
		RecodeComposeStatus(2, null, responseContent == null ? 0 : responseContent);
		frameObj.src = "about:blank";
		ErrorProcess();
		fMessageBox("由于网络原因，邮件发送失败！", "dialog", true, 0, "失败信息");	
	}
}
function SubmitToActionFrm(oForm) {
	try {
		oForm.submit();
		return true;
	} catch(e) {
		showError(e.message);
		return false;
	}
}
function AfterAutoSave(attachlist, mailid, msg, notDisable) {
	if (mailid == "" || !mailid) return ;

	var mF = top.GetMainWin();
	var files = attachlist.split(" |");
	var fileCtls = new Array();
	for (var i = 0; i < mF.AttachID; i++) {
		var tmp = mF.Gel("Uploader" + i);
		if (tmp != null && !tmp.disabled && tmp.value != "")
			fileCtls.push(tmp);
	}
	var len = files.length - 1;
	var len2 = fileCtls.length;
	for (var i = 0; i < len; i++) {
		var isExist = false;
		for (var j = 0; j <= i && j < len2; j++) {
			if (!fileCtls[j].disabled && fileCtls[j].value.indexOf(files[i]) != -1) {
				fileCtls[j].disabled = true;
				isExist = true;
				try{
					if (gIsIE || gIsSafari) fileCtls[j].parentNode.childNodes[1].innerText = files[i];
				}catch(e){}
			}
		}
		if (!isExist) {
			var name = files[i] + " |";
			var pos = attachlist.indexOf(name);
			if (pos != -1) {
				attachlist = attachlist.substr(0, pos) + attachlist.substr(pos + name.length, attachlist.length - pos - name.length);
			}
		}
	}

	if (mF.S("fmailid").value != mailid) {
		mF.S("fmailid").value = mailid;
		setTimeout("ReloadFrm(GetLeftWin())",0);
	}

	mF.LoadValue();
	if (attachlist)	mF.S("fattachlist").value += attachlist;
	setTimeout(function(){showInfo(msg ? msg : (ParseStr((new Date()).getHours(), 2) + ":" + ParseStr((new Date()).getMinutes(), 2) + " " + top.msgSendErrorSaveOK));}, 0);
	if (IsDialogShow("btn_exit_notsave")) return GetDialogObj("btn_exit_notsave").onclick();
	if (!notDisable) mF.DisableAll(false);
	mF.bIsEnableAutoSave = true;
}
//flag: 0-hide 1-info 2-rate; bImg: is disp load img; parm: parameter
function ShowProcess(flag, isShowImg, parm, parm2, isHasCancel)
{
	var id = "load_process";
	var f = GetActionWin();
	var bar = S(id, f);
	if (flag == 0)
	{
		Show(bar, false);
		return;
	}
	if (!IsShow(bar))
	{
		if (!ShowActionWinProcess(isHasCancel))
		{
			return;
		}
	}
	var info = S(id+"_info", f);
	if (flag == 2)
	{
		if (parm2 != null)
		{
			S(id + "_plan_info", f).innerHTML = parm2;
		}
		parm = parseInt(parm);
		parm = isNaN(parm) ? 0 : (parm < 0 ? 0 : (parm > 100 ? 100 : parm));
		S(id + "_plan_rate", f).innerHTML = parm + "%";
		S(id + "_plan_bar", f).style.width = parm + "%";
		Show(S(id+"_plan", f), true);
		Show(S(id+"_img", f), false);
		Show(info, false);
	}
	else
	{
		if (parm != null)
		{
			info.innerHTML = parm;
		}
		Show(S(id+"_plan", f), false);
		Show(S(id+"_img", f), isShowImg);
		Show(info, true);	
	}
}
function ShowActionWinProcess(isHasCancel)
{
	var b = GetActionWin().document.body;
	if (!b) return false;
	var val = [[240, -120, "padding:0 38px 0 28px;width:174px!important;width:240px;"], [214, -107, "padding:0 0 0 28px;width:170px!important;width:214px;"]][isHasCancel ? 0 : 1];
	b.innerHTML = 
	"<body>" +
		"<link rel='stylesheet' type='text/css' href='"+GetPath("css", true)+"comm.css' />" +
		"<link rel='stylesheet' type='text/css' href='"+GetPath("css", true)+"skin"+GetPath("skin")+".css' />" +
		'<div id="load_process" style="width:' + val[0] +  'px;height:20px;position:absolute;left:50%;margin-left:' + val[1] +  'px;text-align:left;">' + 
			'<div id="load_process_plan" class="autosave autosave_txt" style="display:none;">' + 
				'<div style="font:1px;height:12px;border:1px solid white;width:104px;text-align:left;float:left;margin:4px 3px 0 0">' + 
					'<div id="load_process_plan_bar" style="background:#fff;height:8px;margin:1px 0 0 0;width:0%;"></div>' + 
				'</div>' + 
				'<div style="width:78px;line-height:18px;">' + 
					'<span id="load_process_plan_info">发信中</span>:<span id="load_process_plan_rate" style="width:35px;text-align:right;">0%</span>' + 
				'</div>' + 
			'</div>' + 
			'<div id="load_process_info" class="autosave autosave_txt" style="display:none;line-height:20px;text-align:center;' + val[2] +  '"></div>' + 
			'<div id="load_process_img" style="display:none;position:absolute;margin:-18px 0 0 5px!important;margin:-18px 0 0 5px;">' + 
				'<img src="'+GetPath("image", true)+'ico_loading.gif" style="width:16px;height:16px;">' + 
			'</div>' + 
			(isHasCancel ? '<div id="load_process_cancel" class="autosave" style="position:absolute;margin:-19px 0 0 200px!important;margin:-20px 0 0 200px;">[<a href="javascript:void(0);" onclick="top.GetMainWin().CancelDoSend();" style="color:white;">取消</a>]</div>' : '') +
		'</div>' +
	"</body>";
	b.className = "tipbg pos_center";
	b.style.textAlign = "center";
	b.style.width = "100%";
	return true;
}
function GetProcessInfo()
{
	var id = "load_process";
	var f = GetActionWin();
	if (IsShow(S(id, f)))
	{
		var info1 = S(id + "_plan_rate", f);
		var info2 = S(id + "_info", f);
		if (info2 && IsShow(info2))
		{
			return info2.innerHTML;
		}
		if (info1 && IsShow(S(id + "_plan", f)))
		{
			return parseInt(info1.innerHTML);
		}
	}
	return "";
}
function CancelDoSend()
{
	var w = GetMainWin();
	if (w.gSendMailObj)
	{
		top.isAbortByUser = true;
		w.gSendMailObj.StopUpload();
		w.gSendMailObj = null;
	}
	else
	{
		var f = top.S("sendmailFrame");
		if (f)
		{
			f.src = "about:blank";
		}
	}
	RecodeComposeStatus(3, null, 0);
	ShowProcess(0);
	ErrorProcess();
}
function QuickDoSend(frm, value)
{
	try
	{
		CreatePanel(top, 'sendmailFrame', null, 'DoSendFinishCheck(this)');
		ShowProcess(1, 1, msgSend, null, true);
		DisableCtl('source', true);
		frm.content.value = value;
		frm.target = "sendmailFrame";
		frm.submit();
		DisableCtl('sendbtn', true);	
	}
	catch (e)
	{
		showError("发送失败：" + e.message);
		DisableCtl('sendbtn', false);	
	}
}

function EmptyFolder() {
	return confirm("你确认要清空此文件夹吗？");
}
function EmptyFolder_inSpam() {
	return confirm("你确认要删除在垃圾邮件箱中的所有邮件吗？");
}
function MoveFolder(id,index,fun)
{
	try
	{
		var Fids=SN("F_ID");
		for (var i=0; i<Fids.length;i++ ) {
			if (Fids[i].id == id) break;
		}
		var j=-1;
		j= fun=="up"? (i==0?(i+Fids.length-1):i-1) : ((i + 1)%Fids.length);
		GetMainWin().idx1=i;
		GetMainWin().idx2=j;
		if (j>=0) {
			var sf=Gel("frm");
			sf.folder2.value = Fids[j].id;
			sf.index2.value = Fids[j].value;
			sf.folder1.value=id;
			sf.index1.value=index;
			sf.folderid.value=id;		
			sf.fun.value="updateindex";
			sf.act.value=fun;
			SubmitToActionFrm(sf);
		}
	}catch(e)
	{
	}
}
function SwitchFolder(id, bForce, win) {
	var lw = GetLeftWin();
	var b = (lw == win && top.gFolderNoneSeled == true);
	try
	{
		var folder_table = S("folder", lw);
		var folder_td = GelTags("li", folder_table);
		var len = folder_td.length;
		for(var i = 0; i < len; i++)
		{
			if(!folder_td[i].id)
			{
				continue;
			}
			folder_td[i].className = "fs";
		};
		var folder = S(id+"_td", lw);
		if (!b)
		{
			folder.className = "fn";
		}
		switch(folder.parentNode.id)
		{
			case "pop_folder":
			case "my_folder":
				ShowFolder(folder.parentNode.id, 1);
				break;
		}
		if (bForce)
		{
			if (top.gMyFolderStatus != null && top.gMyFolderStatus != S("my_folder", lw).style.display)
			{
				ShowFolder("my_folder");
			}
			if (top.gPopFolderStatus != null && top.gPopFolderStatus != S("pop_folder", lw).style.display)
			{
				ShowFolder("pop_folder");
			}
			top.gMyFolderStatus = null;
			top.gPopFolderStatus = null;
		}
		//这里的判断必现后于 folder 的收缩变化
		setTimeout(function()
		{
			if (top.gFolderMyScrollTop)
			{
				S("my_folder", lw).scrollTop = top.gFolderMyScrollTop;
				top.gFolderMyScrollTop = null;
			}
			if (top.gFolderPopScrollTop)
			{
				S("pop_folder", lw).scrollTop = top.gFolderPopScrollTop;
				top.gFolderPopScrollTop = null;
			}
			if (top.gFolderAllScrollTop)
			{
				S("folder", lw).scrollTop = top.gFolderAllScrollTop;
				top.gFolderMyScrollTop = null;
			}
			if (id != "folder_none" && id != "folder_newmail")
			{
				ScrollIntoMidView(folder, folder.parentNode.clientHeight == 0 ? S("folder", lw) : folder.parentNode);
			}
		}, 0);
	}
	catch(ex) {}
	top.gFolderNoneSeled = (id == "folder_none" || id == "folder_newmail" || b);
}
function SelectAll(flag) {
	var mail_list_table = S('list');
	var mail_list_checkbox = GelTags("input", mail_list_table);
	for(var i = mail_list_checkbox.length - 1;i >= 0; i--) {
		mail_list_checkbox[i].checked = flag;
	}
}
function SelectReadMail(flag) {
	var mail_list_table = S('list');
	var mail_list_checkbox = GelTags("input", mail_list_table);
	for(var i = mail_list_checkbox.length - 1;i >= 0; i--) {
		mail_list_checkbox[i].checked = (mail_list_checkbox[i].getAttribute('unread') != flag);
	}
}
function ReplaySelect(obj) {
	var type = obj.value;
	var frm = obj.form;
	if(type == "all") {
		frm.to.value = frm.toAll.value;
		frm.cc.value = frm.ccSrc.value;
		if (Gel("more1")) {
			Show(Gel("more1"), false);
			Show(Gel("more2"), true);
		}
	} else {
		frm.to.value = frm.toFrom.value;
		frm.cc.value = "";
		if (Gel("more1")) {
			Show(Gel("more1"), true);
			Show(Gel("more2"), false);
		}
	}
}
function RenameFolder(FolderID) {
	sNewName=prompt("请输入新名字\n\n\n","");
	if(sNewName!=null) {
		Gel("frm").name.value=sNewName;
		Gel("frm").folderid.value=FolderID;
		Gel("frm").fun.value="rename";
		SubmitToActionFrm(Gel("frm"));
	}
}
function Trim(sStr)
{
	return sStr.replace(/(^\s+)|(\s+$)/ig,"");
}
function ShowQuickReply(isShow)
{
	Show(S('quickreply'), isShow);
	Show(S('upreply'), !isShow);
	RunUrlWithSid("/cgi-bin/getcomposedata?Fun=setshowquickreply&isShowQuickReply=" + (isShow ? 0 : 1));
}
function HiddenReceipt()
{
	var receiptDiv = S("receiptDiv");
	if(receiptDiv) Show(receiptDiv, false);
}
function ParseStr(val, len) {
	var str = val.toString();
	for (var i = str.length; i < len; i++) {
		str = "0" + str;
	} 
	return str;
}
function CheckAddrSelected() {
	var List = GelTags("input");
	for (var Loop = 0; Loop < List.length; Loop++) {
		if (List[Loop].type == "checkbox" && List[Loop].checked) {
			return true;
		}
	}
	return false;
}
function PGV() {}
function InitAutoComplete() {
	var inputNames = [ "to","cc", "bcc"];
	var defaltTxt = ["", "", ""];
	var defaultCss = ["", "", ""];
	var clickObjNames = ["to_btn", "cc_btn", "bcc_btn"];
	var rightWidth = [null, null, null];
	var targetObj = [null, null, null];
	for(var i=0,len=inputNames.length;i<len;i++) {
		var input = S(inputNames[i]);
		if (input) (new QQMail.AutoCompleteAllAddr()).Init(input, AutoCompleteFrm, S("AutoCompleteFrmId"), true, defaltTxt[i], defaultCss[i], S(clickObjNames[i]), rightWidth[i], targetObj[i]);
	}
}
function ErrorProcess() {
	try{GetMainWin().ErrorCallBack();}catch(e){try{top.ErrorCallBack();}catch(e){}}
}
function IsDisableCtl(name) {
	var ctls = SN(name);
	for (i = ctls.length - 1; i >= 0; i--) {
		if (ctls[i].disabled) return true;
	}
	return false;
}
function DisableCtl(name, isDisabled) {
	var ctls = SN(name);
	for (i = ctls.length - 1; i >= 0; i--) {
		ctls[i].disabled = isDisabled;
	}
}
function DisableAll(isDisabled) {
	try{EnableAutoSave(!isDisabled);}catch(e){}
	DisableCtl("sendbtn", isDisabled);
	DisableCtl("savebtn", isDisabled);
	try{GetDialogObj("btn_exit_save").disabled = isDisabled;}catch(e){}
}
function VerifyCode(sSubTmpl)
{
	var mF = GetMainWin();
	frmVerify=S("frmVerify",mF);
	frmVerify.src="/cgi-bin/readtemplate?templatename=verifycode&subtmpl="+sSubTmpl+ "&sid="+ GetSid() + "&r=" + Math.random();
	Show(frmVerify, true);
}
//folderlist api
function FolderListResize()
{
	var f = GetLeftWin();
	if (!S("folder", f) || !S("my_folder", f) || !S("pop_folder", f)) return; 
	var cur = ((S("my_folder", f).style.display == "none") ? S("pop_folder", f) : S("my_folder", f));
	var dh = parseInt(f.document.body.clientHeight);
	var s = dh < 465;
	var p = cur.scrollHeight > (dh - 422);	
	var nt = f.g_bIsNoteEnabled == "1" ? 0 : 42;
	S("folder", f).style.height = dh > 120 ? dh - 120 : 1;
	S("folder", f).style.overflow = s ? "auto" : "hidden";
	cur.style.height = s ? "" : (p ? (dh - 422) + nt :  cur.scrollHeight );
	cur.style.overflow = s ? "" : (p ? "auto" : "");
	cur.style.overflowX = s ? "hidden" : (p ? "hidden" : "hidden");
}
function ShowFolder(fid, bForce)
{
	var fs = ["my_folder", "pop_folder"];
	var f = GetLeftWin();
	if (!f)
	{
		return;
	}
	for (var i = fs.length - 1; i >= 0; i--)
	{
		var value = [
			[false, "img_b showfd", ""], 
			[true, "img_b hidefd", "normal"]
		][(fs[i] == fid ? (S(fid, f).style.display == "none" || bForce ? 1 : 0) : 0)];
		Show(S(fs[i], f), value[0]);
		Show(S(fs[i]+"_mg", f), value[0]);
		Show(S(fs[i]+"_nb", f), !value[0]);

		S(fs[i] + "_img", f).className = value[1];
		S(fs[i] + "_nf", f).style.fontWeight = value[2];
	}
	setTimeout("top.FolderListResize();", 0);
}
function GetFolderUnread(fid) {
	return OptFolderUnread(0, fid);
}
function SetFolderUnread(fid, val, noBold) {
	return OptFolderUnread(1, fid, val ? val : 0, noBold);
}
function OptFolderUnread(type, fid, val, noBold) {
	if (fid == null) return;
	var f = GetLeftWin();
	o = S("folder_" + fid.toString().split("folder_").pop(), f);
	if (!o) return false;
	val = typeof(val) == "number" && val > 0 ? val : 0;
	var s = gIsIE || gIsSafari ? o.innerText : o.textContent;
	var p = s.lastIndexOf("(");
	var v = 0;
	o.title = "";
	if (p != -1) {
		v = s.substring(p + 1, s.indexOf(")"));
		v = parseInt(v);
		if (type == 0) return v;
		o.innerHTML = (val == 0 ? s.substring(0, p) : StrReplace(o.innerHTML, "\\("+v+"\\)", "("+val+")"));
	}
	else {
		if (type == 0 || val == 0) return 0;
		o.innerHTML = noBold ? (s + "(" + val + ")") : ("<b>" + s + "</b><b>(" + val + ")</b>");
	}
	//modify folder...
	fid = o.parentNode.parentNode.parentNode.id;
	o = S(fid + "_nb", f);
	if (o) {
		s = o.innerHTML;
		p = s.lastIndexOf("(");
		v = (p != -1 ? parseInt(s.substring(p + 1, s.indexOf(")"))) : 0) + val - v;
		o.innerHTML = v > 0 ? "(" + v + ")" : "";
		o.parentNode.title = "";
		S(fid + "_nf", f).className = v > 0 ? "bold" : "";
	}
	return true;
}
function DoFolderEmpty(folderid, frm) {
	frm.folderid.value=folderid;
	frm.rk.value = Math.random();
	SubmitToActionFrm(frm);
}
//mail_list api
function RecordReadedMailId(mailid, bforcenullpos) {
	top.gReadedMailId = mailid;
	try{top.gReadedPosition = mailid && !bforcenullpos ? GetMainWin().document.body.scrollTop : null;}catch(e){}
}
function RecordCompareReadedMailId(mailid) {
	if (mailid && top.gReadedMailId != mailid) {
		top.gReadedMailId = mailid;
		top.gReadedPosition = null;
	}
}
function SG(groupObj, bSessionMode) {
	var l = groupObj.className.length - 2;
	var bShow = groupObj.className.charAt(l) == "s" ? false : true;
	var pO = groupObj.previousSibling;
	if (pO.className == "one" || pO.className == "all") 
	{  
		bShow? pO.className="one" : pO.className="all";	
	}
	groupObj.className = groupObj.className.substr(0, l) + (bShow ? "st" : "ht");
	var div = (bSessionMode ? groupObj.parentNode : groupObj.parentNode).nextSibling;
	if (div.className != "toarea") div = div.nextSibling;
	if (div.className != "toarea") return;
	return Show(div, bShow);
}
function CA(cObj)
{
	//if (cObj.className== "one")
	//	return;
	var div = cObj.parentNode.nextSibling;
	if (div.className != "toarea") div = div.nextSibling;
	if (div.className != "toarea") return;
	var putlist=div.getElementsByTagName("input");
	for(i=putlist.length-1; i>=0; i--)
	{
		SetListCheck(putlist[i], cObj.checked);
	}
}

function RD(oEvent, mailid, unread, type, folderid, bunreadtmpl, bcheck, nXqqstyle) {
	if (oEvent) fPreventDefault(oEvent);
	if (bcheck && !confirm(msgModifySendTimeMsg)) return;
	RecordReadedMailId(mailid);
	var templatename = type == 0 ? (nXqqstyle==100 ? "compose_card&subtmpl=draft" : "compose&subtmpl=draft") : (type == 1 ? "readmail" : "readmail_group");
	var subtmpl = oEvent && oEvent.shiftKey ? ["&subtmpl=newwin", "&compose_new=compose"][type?0:1] : ["", "&subtmpl=from_unread_list", "&subtmpl=from_star_list"][bunreadtmpl != 1 && bunreadtmpl != 2 ? 0 : bunreadtmpl];
	var url = ['/cgi-bin/readmail?sid=', GetSid(), '&mailid=', mailid, '&folderid=', folderid, '&templatename=', templatename, subtmpl, (unread ? "&rflist=true" : "")].join("");

	if (oEvent && oEvent.shiftKey) {
		var target = oEvent.target ? oEvent.target : oEvent.srcElement;
		if (target) {
			for (; target && target.tagName != "DIV"; target = target.parentNode);
			if (target) SetItemReadedBefore(target);
		}
		var url = ['/cgi-bin/frame_html?sid=', GetSid(), '&mailid=', mailid, '&folderid=', folderid, '&templatename=newwin_frame&keep_templatename=', templatename, subtmpl, (unread ? "&rflist=true" : "")].join("");
		top.open(url);
	}
	else {
		GetMainWin().location.href = url;
	}
}

function CheckCheckBoxs() {
	if (frm.mailid && frm.mailid.length ) {
		for (var i=0;i<frm.mailid.length ; i++) {
			if (frm.mailid[i].checked) return true;
		}
	}
	else {
		if(frm.mailid){if(frm.mailid.checked) return true;}
	}
	return false;
}
function CheckPerDelML() {
    var str = "您确定要彻底删除选中的邮件吗？";
	if (CheckCheckBoxs() && confirm( str ) == false) 
	{
		top.focus();
		return false;
	}
	top.focus();
	frm.Fun.value="PerDel";
	frm.mailaction.value = "mail_del";
	frm.templatename.value = "mail_del";
	frm.action='/cgi-bin/mail_mgr';
	SubmitToActionFrm(frm);
	return true;
}
function OnSearch() {
	var f=gd.getElementById("frmSearch");
	f.receiver.value=f.subject.value;
	f.sender.value=f.subject.value;
	SubmitToActionFrm(f);
	return false;
}
function SetListCheck(obj, checked)
{
	if (obj.type != "checkbox")
	{
		return;
	}
	if (checked == null)
	{
		checked = obj.checked;
	}
	else
	{
		obj.checked = checked;
	}
	var a = obj.parentNode.parentNode;
	a.className = checked ? StrReplace(a.className, " B", "") + " B" : StrReplace(a.className, " B", "");
}
function SetItemReadedListCheck(isSelectMore)
{
	try
	{
		obj = GelTags("input", GetMainWin().gReadedBeforeImg.parentNode.parentNode)[0];
		obj.checked = !obj.checked;
		DoCheck(null, obj, isSelectMore);
		return true;
	}
	catch (e)
	{
		return false;
	}
}
function DoCheck(e, t, isSelectMore)
{
	e = e ? e : event;
	var obj = t ? t : (gIsIE ? e.srcElement : e.target);
	var w = GetMainWin();
	if (!obj || !w) return ;
	if(obj.className=="one"||obj.className=="all")
	{
		CA(obj);
	}
	SetListCheck(obj);
	//shift键 多选
	if ((e && e.shiftKey || isSelectMore) && w.gCurSelObj && w.gCurSelObj != obj && obj.checked == w.gCurSelObj.checked)
	{
		var s = w.GelTags("input");
		var c = 0;
		var l = s.length;
		for (var i = 0; i < l; i++) {
			if (s[i].type != "checkbox")
			{
				continue;
			}
			if ((s[i] == w.gCurSelObj || s[i] == obj) && c++ == 1)
			{
				break;
			}
			if (c == 1)
			{
				SetListCheck(s[i], obj.checked);
			}
		}
	}
	w.gCurSelObj = obj;
}
function CheckAll(CBName)
{
	var cbs = GelTags("input");
	for(var i=cbs.length-1; i>=0; i--)
	{
		if(cbs[i].name == CBName )
		{
			SetListCheck(cbs[i]);
		}
	}
}
var gReadedBeforeImg = null;
function SetItemReadedBefore(item) {
	var p = GelTags("b", item)[0];
	var img = p.childNodes[0];
	if (gReadedBeforeImg) Show(gReadedBeforeImg, 0);
	if (img.tagName == "IMG" || img.tagName == "img")	{
		Show(img, 1);
	}
	else {
		img = document.createElement("img");
		img.src = GetPath("image") + "ico_grouplight.gif";
		img.className = "showarrow";
		img.title = "这是您最近阅读的一封邮件";
		p.insertBefore(img, p.childNodes[0]);
	}
	gReadedBeforeImg = img;
	var mailid = GelTags("input", item)[0].value;
	tmpReadedMailId = top.gReadedMailId;
}
function SetPrevOrNextItemReadedBefore(mode) {
	var w = GetMainWin();
	if (!w.gMailListArr || w.gMailListArr.length == 0) return false;
	var pos = -1;
	if (w.gReadedBeforeImg != null) {
		var obj = w.gReadedBeforeImg.parentNode.parentNode;
		for (var i = w.gMailListArr.length - 1; i >= 0; i--) {
			if (obj == w.gMailListArr[i]) {
				pos = i;
				break;
			}
		}
	}
	pos += mode ? 1 : -1;
	if (pos > -1 && pos < w.gMailListArr.length) {
		w.SetItemReadedBefore(w.gMailListArr[pos]);
		w.ScrollIntoMidView(w.gMailListArr[pos], w.document.body, false);
	}
	return true;
}
function ReadReadedBeforeItem() {
	var w = GetMainWin();
	if (w.gReadedBeforeImg == null) return false;
	var as = GelTags("a", w.gReadedBeforeImg.parentNode.parentNode);
	if (as) as[1].onclick();//as[0].href ? w.location = as[0].href : as[0].onclick();
	return true;
}
function ModifyFolder(folderid, popacctid) {
	GetMainWin().location.href="/cgi-bin/foldermgr?sid=" + GetSid() + "&fun=detailpop&templatename=pop_detail&folderid="+folderid + "&acctid=" + popacctid;
}
function RecvPop(popacctid) {
	GetActionWin().location.href="/cgi-bin/foldermgr?sid=" + GetSid() + "&fun=recvpop&acctid=" + popacctid;
	try{
		Gel("tips").innerHTML="<img src='" + GetPath("image", true) + "ico_loading1.gif' align=absmiddle style='margin:0 4px 0 0'>正在收取邮件...&nbsp;整个过程可能需要花一些时间。";
		//设置自动刷新；
		setTimeout("ReloadFrmLeftMain(false,true)",10000);
	}catch(e){}
}
function RecvPop_creat(popacctid) {
	GetActionWin().location.href="/cgi-bin/foldermgr?sid=" + GetSid() + "&fun=recvpop&acctid=" + popacctid;
}
function RecvPopAll() {
	GetActionWin().location.href="/cgi-bin/foldermgr?sid=" + GetSid() + "&fun=recvpopall";
	try{
		//设置自动刷新；
		setTimeout("ReloadFrmLeftMain(false,true)",3000);
	}catch(e){}
}
function CheckReject() {
	 var o=gd.getElementsByTagName("INPUT"),cnt=0;
	 for(var i=0,len=o.length;i<len;i++){
	 	 	var t=o[i];
	 	  if(t.type=="checkbox" && t.name =="mailid" && t.checked){ 
	 	  	return true; 
	 	  }
	 }
	 return false;
}
function ReportSpam(nFrom)
{
	try{
		if(window.document.frm)
		{
			if(!CheckCheckBoxs())
			{
				var f = window.document.frm;
				f.mailaction.value = "mail_spam";
				f.templatename.value = "setmailspam";
				f.action='/cgi-bin/mail_mgr';
				SubmitToActionFrm(f);
				return false;
			}
		}
	}catch(e){};
	var callback = function(isOk)
	{
		try{
		if(isOk)
		{
			var f=window.document.mail_frm;
			if(f)
			{
				if(window.location.href.indexOf("quickreadmail")<0)
				{
					//读邮件时举报垃圾邮件
					f.subtmpl.value="readmail_spam";
				}
			}
			else
			{
				f=window.document.frm;
			}
			if(f)
			{
				f.isspam.value='true';
				f.mailaction.value = "mail_spam";
				f.templatename.value = "setmailspam";
				f.action='/cgi-bin/mail_mgr';
				typelist=GetDialogObj("frm_spamtype").reporttype;
				for(var i=0;i<typelist.length;i++)
				{
					if(typelist[i].checked)
						{
							f.reporttype.value=typelist[i].value;
							break;
						}
				}
				SubmitToActionFrm(f);
			}
		}
		}catch(e){}
		HideModelDialog();
	};

	return ModelDialog(1, "举报垃圾邮件",  
	"<div style='padding:10px 10px 0 30px;text-align:left;'>" + 
		"<form id='frm_spamtype'>" +
		"<div>您认为您所举报的邮件是以下哪种类型的：</div>" +
		"<div><input type=\"radio\" name=\"reporttype\" id=\"r0\" value=\"0\" checked><label for=\"r0\">未分类</label></div>" +
		"<div><input type=\"radio\" name=\"reporttype\" id=\"r4\" value=\"4\"><label for=\"r4\">广告邮件</label></div>" +
		"<div><input type=\"radio\" name=\"reporttype\" id=\"r1\" value=\"1\"><label for=\"r1\">欺诈邮件</label></div>" +
		"<div><input type=\"radio\" name=\"reporttype\" id=\"r5\" value=\"5\"><label for=\"r5\">色情邮件</label></div>" +
		"<div><input type=\"radio\" name=\"reporttype\" id=\"r6\" value=\"6\"><label for=\"r6\">反动邮件</label></div>" +
		"<div><input type=\"radio\" name=\"reporttype\" id=\"r7\" value=\"7\"><label for=\"r7\">病毒邮件</label></div>" +
		"<div><input type=\"radio\" name=\"reporttype\" id=\"r8\" value=\"8\"><label for=\"r8\">其他邮件</label></div></form>" +
	"</div><div style='padding:0 20px 15px 10px;text-align:right;'>" + 
		"<input type=button id='btn_ok' class='btn wd2' value=确定>" + 
		"<input type=button id='btn_cancel' class='btn wd2' value=取消>" + 
	"</div>", 
	"btn_cancel", 
	["btn_ok", "btn_cancel"], 
	[function(){callback(true);}, function(){callback(false);}],"400px","250px");
}
function CBCount(sName)
{
	var o=gd.getElementsByTagName("INPUT"),cnt=0;
	 for(var i=0,len=o.length;i<len;i++){
	 	 	var t=o[i];
	 	  if(t.type=="checkbox" && t.name == sName && t.checked){ 
	 	  	++cnt; 
	 	  }
	 }
	 return cnt;
}

function poperrdone(msg, mbtype, bHide, hidetime) {
	fMessageBox(msg, mbtype, bHide, hidetime);
	Showsubmitbtn();
}

function Showsubmitbtn()
{
	GetMainWin().S("submitbtn").disabled = false;
}
function Showpopsvr()
{
	GetMainWin().S("popsvrTR").style.display="";
}

function OnFldSelChg_ML(sel,frm,folderid)
{
	if(sel[sel.selectedIndex].value=="-2")
	{
		sel.selectedIndex=0;return;
	}
	frm.mailaction.value = "mail_move";
	frm.destfolderid.value=sel[sel.selectedIndex].value;
	if(frm.destfolderid.value == -1) 
	{
		 var nameValue;
		 while( (nameValue=prompt("请输入文件夹名字", "")) != null){
		 	  if(nameValue != "")  break;
		 }
		 if(nameValue == null){
		  	 sel.selectedIndex=0;
		 		 return false;
		 }
		frm.foldername.value=nameValue;
	}

	var o=gd.getElementsByTagName("INPUT"),cnt=0;
	for(var i=0,len=o.length;i<len;i++){
		var t=o[i];
		if(t.type=="checkbox" && t.name == "mailid" && t.checked && t.isendtime == 1){
			showError(msgSendMailNoMove);
			return false;
		}
	}
	sel.selectedIndex=0;
	if(folderid==frm.destfolderid.value ) 
	{
		showError(msgMoveMailSameFldErr); 
		return false;
	}
	frm.templatename.value = "mail_move";
	frm.action='/cgi-bin/mail_mgr?sid=' + GetSid();
	SubmitToActionFrm(frm);
}
//readmail api
function SwitchOption() {
	var res = [["隐藏↑", true],["更多操作↓", false]][Gel("trOption").style.display=="none" ? 0 : 1];
	S("aSwitchOption").innerHTML=res[0];
	Show(S("trOption"), res[1]);
}
function FindPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;// - document.body.scrollTop;
}
//readmail del spam move mail opt
function CheckPerDel(temp) {
    if (CheckNewwinPerDel()) {
		DelMail("PerDel", temp);
	}
}
function CheckNewwinPerDel(Type) {
	return confirm( (Type=="reject") ? "拒收后将无法收到来自<%fromaddr%>$DATA$<%/fromaddr%>的邮件，您确定要拒收吗？" : "彻底删除后此邮件将无法取回，您确定要删除吗？" );
}
function DelMail(fun, temp) {
	var f = mail_frm;
	f.action = "/cgi-bin/mail_mgr?sid=" + GetSid();
	f.Fun.value=fun;
	f.mailaction.value = "mail_del";
	f.templatename.value = (temp != null ? temp : "mail_del_readmail");
	f.subtmpl.value = window.newwinflag ? "newwin" + "_" + fun : "";
	SubmitToActionFrm(f);
}
function QuickSetStar(obj, mailid, bSet) {
	if (!star_frm) return false;
	if (obj) obj.id = "img_star";
	if (mailid) star_frm.mailid.value = mailid;
	star_frm.status.value = bSet ? "true" : "false";
	star_frm.submit();
	return false;
}
function SetMailFlag(frm, type, bIsStar, selObj) {
	if (selObj != null) {
		if (type == null) type = selObj.value;
		if (bIsStar == null) bIsStar = type.indexOf("star") != -1;
		if (bIsStar) type = type == "star";
		selObj.selectedIndex = 0;
	}
	if (type == "-2") return;
	frm.status.value = type;
	frm.mailaction.value='mail_flag';
	frm.flag.value = 'new';
	if(bIsStar) frm.flag.value = "star";
	frm.action='/cgi-bin/mail_mgr';
	frm.submit();
}
function SetMailType(type, isspam, isgroup) {
	var f = mail_frm;
	f.action = "/cgi-bin/mail_mgr?sid=" + GetSid();
	f.mailaction.value = "mail_spam";
	f.templatename.value = "setmailspam";
	var str = type == "cheat" ? "spam" : type;
	f.subtmpl.value = "readmail_" + (isspam ? (isgroup ? "group" : type) : ("not" + type)) + (newwinflag ? "_newwin" : "");
	f.isspam.value = isspam;
	f.reporttype.value = type == "cheat" ? "1" : "";
	SubmitToActionFrm(f);
}
function SetSpamMail(isspam, isgroup) {
	//SetMailType("spam", isspam, isgroup);
	if (isspam && !isgroup)
	{
		ReportSpam();
	}
	else
	{
		SetMailType("spam", isspam, isgroup);
	}
}
function SetCheatMail(isspam, isgroup) {	
	SetMailType("cheat", isspam, isgroup);
}
function doReject(isspam, isgroup) {
	if(confirm(msgRejectAlert)) SetMailType("reject", isspam, isgroup);
}

function MoveMail(obj) {
	var dfid = obj.value;
	obj.selectedIndex = 0;
	if (dfid < 1 && dfid != -1) return ;
	var f = mail_frm;
	if(dfid == -1)  {
		 var nameValue;
		 while((nameValue=prompt("请输入文件夹名字", "")) != null){
		 	  if(nameValue != "")  break;
		 }
		 if(nameValue == null){
			obj.selectedIndex = 0;
			return ;
		 }
		f.foldername.value=nameValue;
	}
	var sfid = (f.srcfolderid.value == 0 ? 1 : f.srcfolderid.value);
	if(dfid == sfid) {
		obj.selectedIndex = 0;
		showError(msgMoveMailSameFldErr);
		return ;
	}
	f.destfolderid.value = dfid;
	f.mailaction.value = "mail_move";
	f.templatename.value = "mail_move_readmail";
	f.subtmpl.value = (newwinflag ? "newwin" : "");
	f.action = "/cgi-bin/mail_mgr?sid=" + GetSid();
	SubmitToActionFrm(f);
}
function LinkMaker(htmlCode, linkNum, type, flag)
{
	var linkStr = htmlCode[linkNum], prevStr = htmlCode[linkNum - 1], nextStr = htmlCode[linkNum + 1];
	prevStr = Trim(prevStr).toLowerCase();

	var pos1 = prevStr.lastIndexOf("<a ");
	var pos2 = prevStr.lastIndexOf("</a>");
	//在<a>..</a>里面
	if (pos2 < pos1)
	{
		flag[linkNum] = 1;
		return linkStr;
	}
	var pos3 = prevStr.lastIndexOf("<");
	var pos4 = prevStr.lastIndexOf(">");
	//在<...>里面
	if (pos4 < pos3)
	{
		flag[linkNum] = 2;
		return linkStr;
	}

	nextStr = Trim(nextStr).toLowerCase();
	var pos5 = nextStr.indexOf("<a ");
	var pos6 = nextStr.indexOf("</a>");
	//在<a>..</a>里面
	if (pos6 < pos5 || (pos6 != -1 && pos5 == -1))
	{
		flag[linkNum] = 1;
		return linkStr;
	}
	var pos7 = nextStr.indexOf("<");
	pos8 = nextStr.indexOf(">");
	//在<...>里面
	if (pos8 < pos7 || (pos8 != -1 && pos7 == -1))
	{
		flag[linkNum] = 2;
		return linkStr;
	}

	if (linkNum - 2 > 0)
	{
		var preFlag = flag[linkNum - 2];
		if (preFlag == 1 && pos2 == -1)
		{
			flag[i] = 1;
			return linkStr;
		}
		else if (preFlag == 2 && pos4 == -1)
		{
			flag[i] = 2;
			return linkStr;
		}
	}

	if (type == 0 && nextStr)
	{
		if (nextStr)
		{
			var tmps = htmlCode[linkNum + 1].split("&nbsp;");
			if (nextStr.charAt(0) == "&" && tmps[0] != "")
			{
				var result = tmps.shift().replace(/([ \f\n\r\t\v\"\\:><\[\]\u2100-\uFFFF])/i, '<&&>$1<&&>').split("<&&>");
				linkStr += result.shift();
				
				htmlCode[linkNum + 1] = result.join("") + tmps.join("&nbsp;");
			}
		}
		var lastChar = linkStr.charAt(linkStr.length - 1);
		if (lastChar.replace(/[\.,!?]/, "") == "")
		{
			linkStr = linkStr.slice(0, -1);
			htmlCode[linkNum + 1] = lastChar + htmlCode[linkNum + 1];
		}
	}
	linkStr = '<a href="' + (type == 0 ? "" : "mailto:") + linkStr + '">' + linkStr + '</a>';
	return linkStr;
}
//0:http 1:email
function LinkIdentify(htmlCode, type) {
	if (!htmlCode) return htmlCode;
	if (!type) type = 0;
	htmlCode = type == 0 ? htmlCode.replace(/(https?:\/\/[\w.]+[^ \f\n\r\t\v\"\\><\[\]&\u2100-\uFFFF]*)/ig, '<&url&>$1<&url&>').split("<&url&>") :
		htmlCode.replace(/([a-zA-Z_0-9.-]+@[a-zA-Z_0-9.-]+\.\w+)/ig, '<&url&>$1<&url&>').split("<&url&>");
	var flag = new Array(htmlCode.length);
	for (var i = 1; i < htmlCode.length; i+=2) {
		htmlCode[i] = LinkMaker(htmlCode, i, type, flag);
	}
	return htmlCode.join("");
}
//readmail rewrite link to target
function SwapLink(id) {
	var obj = S(id);
	if (!obj) return;

	//识别链接以及邮箱地址
	var code = obj.innerHTML;
	code = LinkIdentify(code, 0);
	obj.innerHTML = "<div style='display:none;'>&nbsp;</div>" + LinkIdentify(code, 1);

	var as = GelTags("a", obj);
	for (var i = as.length - 1; i >= 0; i--) {
		if (as[i].name != "_QQMail_ReferenceGroupMail_" && 
			as[i].name != "_QQMail_DownloadGroupMailAttach_" && 
			as[i].name != "qqplusa") {
			as[i].target = "_blank";
			as[i].onclick = function() {
				return OpenExtLink(this);
			};
		}
	}
}
function ZoomImgToBody(obj, ajustValue, isInit)
{
	var objWidth = obj.getAttribute("ow");
	if (!objWidth)
	{
		objWidth = obj.width;
		if (!objWidth || !isInit)
		{
			return;
		}
		obj.setAttribute("ow", objWidth);
	}
	objWidth = parseInt(objWidth);
	var styles = ["点击查看实际尺寸", "zoom+.cur", "缩小图片到适应窗口", "zoom_.cur"];
	var bodyWidth = document.body.clientWidth - (ajustValue ? ajustValue : 80);
	if (objWidth > bodyWidth)
	{
		obj.width = bodyWidth;
		obj.style.cursor = GetPath("image") + styles[1];
		obj.title = styles[0];
		obj.onclick = function()
		{
			this.width = parseInt(this.width) > bodyWidth ? bodyWidth : (this.getAttribute("ow"));
			this.title = styles[parseInt(this.width) > bodyWidth ? 2 : 0];
			this.style.cursor = GetPath("image") + styles[parseInt(this.width) > bodyWidth ? 3 : 1];
		};
	}
	else if (parseInt(obj.width) < objWidth)
	{
		obj.width = objWidth;
		obj.style.cursor = "default";
		obj.title = "";
	}
}
function SwapImg(id, ajustValue)
{
	var as = GelTags("img", S(id));
	for (var i = 0; i < as.length; i++)
	{
		if (as[i].src)
		{
			ZoomImgToBody(as[i], ajustValue);
			as[i].onload = function()
			{
				ZoomImgToBody(this, ajustValue, true);
			};
		}
	}
}
function OpenExtLink(a) 
{
	if (a.href.indexOf("mailto:") == 0 && a.href.indexOf("@") != -1)
	{
		window.open("/cgi-bin/readtemplate?sid="+GetSid()+"&templatename=compose&subtmpl=cliwrite&newwin=true&email="+a.href.split("mailto:")[1]);
		return false;
	}
	else if (a.className == "qqmail_card_reply" || a.className == "qqmail_card_reply_btn")
	{
		GetMainWin().location = ["/cgi-bin/cardlist?sid=", GetSid(), 
			"&templatename=compose_card&today_tips=", (a.className.indexOf("btn") != -1 ? "112" : "111"), 
			"&ListType=No", (a.name ?  "&email=" + a.name : ""), 
			top.bnewwin ? "&newwin=true" : ""].join("");
		return false;
	}
	else if (a.className == "groupmail_open")
	{
		GetMainWin().location = "/cgi-bin/grouplist?sid=" + GetSid() + "&templatename=compose_group";
		return false;
	}
	else if (a.className == "reg_alias")
	{
		GetMainWin().location = "/cgi-bin/readtemplate?reg_step=1&templatename=regalias_announce&sid="+GetSid();
		return false;
	}

	var str = "http://mail.qq.com/cgi-bin/feed?u=";
	if (a.name == "_QQMAIL_QZONESIGN_" || a.href.indexOf(str) == 0)
	{
		if (a.name == "_QQMAIL_QZONESIGN_")
		{
			var dat = a.href.split("/");
			var uin = parseInt(dat[2]);
			var blog = parseInt(dat.pop());
			var parm = ["&sid=", GetSid(), "&feedurl=http%3A%2F%2Ffeeds.qzone.qq.com%2Fcgi-bin%2Fcgi_rss_out%3Fuin%3D", uin].join("");
		}
		else
		{
			var parm = ["&sid=", GetSid(), "&feedurl=", a.href.substr(str.length)].join("");
		}
		if (top.bnewwin)
		{
			top.location = ["/cgi-bin/frame_html?target=rssswitch", parm].join("");
		}
		else
		{
			GetMainWin().location = ["/cgi-bin/reader_switch?rssswitch=1", parm].join("");
		}
		return false;
	}

	return true;
}
//readmail go next mail
function GoNextMail(mode, subtmpl, msg, oth) {
	var w = GetMainWin();
	//var r = (mode == 2 ? [] : ["prevmail", "nextmail"]);
	var r = (["prevmail", "nextmail"]);
	for (var i = r.length - 1; i >= 0; i --) {
		var a = w.Gel(r[i]);
		if (a && !a.getAttribute("disabled")) {
			w.location = a.href + (msg ? ("&msg=" + msg) : "");
			return ;
		}
	}
	w.location = (top.bnewwin ? "/cgi-bin/readtemplate?templatename=compose_send_newwin&subtmpl=" + subtmpl : "/cgi-bin/mail_list?") + "&sid=" + GetSid() + (oth ? oth : "");
}
function GoPrevOrNextMail(mode) {
	var w = GetMainWin();
	var a = S(["prevmail", "nextmail"][mode?1:0], w);
	var a2 = S(["prevpage", "nextpage"][mode?1:0], w);
	if (a && !a.getAttribute("disabled")) w.location = a.href;
	else if (a2 && !a2.getAttribute("disabled")) w.location = a2.href;
}
function GoBackHistory() {
	var btn = SN("readmailBack",GetMainWin());
	if (btn.length > 0 && btn[0].style.display != "none") try{btn[0].onclick();return true;}catch(e){};
	return false;
}
//quick readmail
function QuickReadMail(obj, nofun)
{
	var w = GetMainWin();
	if (obj == null)
	{
		try
		{
			obj = GelTags("p", w.gReadedBeforeImg.parentNode.parentNode);
			obj = obj[obj.length - 1];
		}
		catch (e)
		{
			return false;
		}
	}
	var c = obj.parentNode;
	var n = c.nextSibling;
	var input = GelTags("input", c)[0];
	var id = input.value;
	if (!n || !n.className || n.className.indexOf("QRM") == -1) {
		InsertHTML(c, "afterEnd", 
		['<div class="qqshowbd QRM" style="height:244px;margin:4px 0;display:none;">',
			'<div id="err_', id, '" style="background:#ffffe9;padding:7px 0 5px 0;border-bottom:1px solid #e3e6eb;text-align:center;display:none">',
				'邮件读取不成功， <a href="javascript:ReQuickReadMail(\'' + id + '\')">点击重试</a>。',
			'</div>',
			'<div id="load_', id, '" style="background:#4b981d;color:#fff;padding:3px 8px;position:absolute;left:40%;margin-top:90px">',
				'<img width="16px" height="16px" src="', GetPath("image"), 'ico_loading.gif" style="margin:0 3px 0 0;" align="absmiddle"/>',
				'邮件正在读取中...',
			'</div>',
			'<iframe id="frame_', id, '" frameborder=0 width=100% height=100% src="',
				'/cgi-bin/readmail?mailid=', id, '&templatename=quickreadmail', (nofun ? "&nofun=1" : ""), '&sid=', GetSid(), (window.g_subtmpl == "newmail_list" ? "&subtmpl=newmail_list" : ""),
				'" onload="var o=Gel(\'load_', id, '\');if(IsShow(o)){Show(Gel(\'err_', id, '\'), 1);Show(o, 0);Show(o.nextSibling, 0);}"></iframe>',
		'</div>'].join(""));
		n = c.nextSibling;
	}
	else if (obj.className == "K" && S("err_" + id, w).style.display == "") {
		ReQuickReadMail(id);
	}
	if (w.gQRMOldObj) {
		var oldObj = w.gQRMOldObj.parentNode.parentNode;
		if (oldObj.nextSibling != n) {
			Show(oldObj.nextSibling, 0);
			oldObj = GelTags("p", oldObj);
			oldObj = oldObj[oldObj.length - 1];
			oldObj.className = "K";
		}
	}
	var b = w.document.body;
	var r = c.offsetTop + c.offsetHeight - b.scrollTop;
	if (r < 0 || r > b.clientHeight) c.scrollIntoView(true);
	SetItemReadedBefore(c);
	Show(n, n.style.display != "");
	if (n.style.display == "") {
		r = n.offsetTop + n.offsetHeight - b.scrollTop;
		if (r < 0 || r > b.clientHeight) n.scrollIntoView(false);
	}
	obj.className = (obj.className == "K" ? "K1" : "K");
	if (w.gQRMOldObj && w.gQRMOldObj != input) SetListCheck(w.gQRMOldObj, w.gQRMListSelectObj == w.gQRMOldObj);
	if (w.gQRMListSelectObj != input || n.style.display == "") {
		w.gQRMListSelectObj = input.checked ? input : null;
		SetListCheck(input, n.style.display == "");
	}
	w.gQRMOldObj = w.gQRMOldObj == input ? null : input;
	return true;
}
function ReQuickReadMail(id) {
	var w = GetMainWin();
	Show(S("err_" + id, w), 0);
	Show(S("frame_" + id, w), 0);
	Show(S("load_" + id, w), 1);
	ReloadFrm(F("frame_" + id, w));
}
function ScrollQuickReadedMail(bUp)
{
	try
	{
		var w = GetMainWin();
		var c =  w.gReadedBeforeImg.parentNode.parentNode;
		var n = c.nextSibling;
		if (!IsShow(n))
		{
			return false;
		}
		var frame = GelTags("iframe", n)[0];
		return F(frame.id, w).ScrollPage(bUp);
	}
	catch (e)
	{
		return false;
	}
}
function ListMouseMove()
{
	this.className = top.StrReplace(this.className," noroll"," rollbg");
}
function ListMouseOut()
{
	this.className = top.StrReplace(this.className," rollbg"," noroll");
}
var gMailListArr = [];
function ListIni() {
	var d = GelTags("div");
	var obj, cObj;
	var len = d.length;
	for (var i = 0; i < len; i++) {
		var o = d[i];
		if (o.className == "M" || o.className == "F") {
			if (len < 300)
			{
				o.className += " noroll";
				if (gIsIE) {
					o.onmouseenter = ListMouseMove;
					o.onmouseleave = ListMouseOut;
				}
				else {
					o.onmousemove = ListMouseMove;
					o.onmouseout = ListMouseOut;
				}
			}			
			var t = GelTags("input", o)[0];
			t.onclick = DoCheck;
			t.title = "按住shift点击不同邮件的勾选框 可方便快捷多选邮件";
			if (t.name == "mailid") gMailListArr.push(o);
			if (top.gReadedMailId == t.value) obj = o;
			if (top.gSelectedMailId == t.value) {
				SetListCheck(t, true);
				cObj = o;
				top.gSelectedMailId=null;
			}
			try {
				var a1 = GelTags("a", o)[0];
				if (a1.className.indexOf("R ") == 0) {
					a1.href = "javascript:;";
					a1.onclick = function(e) {
						eval(GelTags("a", this.parentNode)[1].onclick.toString().split("{")[1].split("}")[0].replace(/event/ig, "{shiftKey:true}"));
						fPreventDefault(e || window.event);
					};
				}
			} catch(e) {}
			o = GelTags("p", o);
			o = o[o.length - 1];
			if (o.className == "K") {
				o.onclick = function() {QuickReadMail(this);};
				o.title = "预览邮件";
			}
		}
	}
	setTimeout(function() {
		if (obj) {
			if (top.gReadedPosition != null) {
					GetMainWin().document.body.scrollTop = top.gReadedPosition;
					ScrollIntoMidView(obj, document.body);
			}
			else {
				ScrollIntoMidView(obj, document.body, true);
			}
			SetItemReadedBefore(obj);
		}
		RecordReadedMailId(null);
		if(cObj) {
			ScrollIntoMidView(cObj, document.body, true);
		}
	}, 0);
}
function ReadMailFinish(id, type, fid) {
	try{
		var m = GetMainWin();
		try {
			var o = m.Gel("load_" + id);
			Show(o, 0);
			o = o.parentNode.previousSibling;
		}
		catch (e) {
			var o = GelTags("input");
			for (var i = o.length - 1; i >= 0; i --) {
				if (o[i].type == "checkbox" && o[i].value == id) break;
			}
			// if find no ->  throw e and exit
			o = o[i].parentNode.parentNode;
		}
		if (o.className.indexOf("F") == 0) {
			o.className = StrReplace(o.className, "F", "M");

			o = GelTags("a", o)[0];
			o.className = StrReplace(o.className, "Ru", type == "r" ? "Rh" : (type == "f" ? "Rz" : "Rr"));

			o = m.Gel("_ur_c");
			if (o) {
				o.innerHTML = parseInt(o.innerHTML) - 1;
				Show(S("_ur", m), o.innerHTML != "0");
				if (!IsShow(S("_ur", m)) && !IsShow(S("_ui", m))) Show(S("_ua", m), false);
			}
			//if no left win -> throw e and exit
			SetFolderUnread(fid, GetFolderUnread(fid) - 1);
		}
		return true;
	}catch(e){
		return false;
	}
}
//mp3 player
function GetFlash(id) {
	return gIsIE ? window[id] : document[id];
}
function SetPlayer(container, url, name) {
	var d = S(container);
	if (!d) return;
	if (url) url = encodeURI(url);
	d.innerHTML = '<object id="qqmailmp3player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width=255 height=78><param name="wmode" value="opaque"><param name="movie" value="/zh_CN/htmledition/images/player/QQMailPlayer.swf"><param name="quality" value="high">'+(url ? ('<param name="FlashVars" value="ini_url='+url+(name?('&ini_name='+name):'')+'">') : '')+'<embed src="/zh_CN/htmledition/images/player/QQMailPlayer.swf" quality=high width=255 height=78 type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" swLiveConnect="true" wmode="opaque" name="qqmailmp3player" '+(url ? ('FlashVars="ini_url='+url+(name?('&ini_name='+name):'')+'"') : '')+'></embed></object>';
	Show(d, 1);
}
function PlayMp3(url, name) {
	var p = GetFlash("qqmailmp3player");
	if (!p) return SetPlayer("mp3player_container", url, name);
	p.SetVariable("music_url", encodeURI(url));
	if (name) p.SetVariable("music_name", name);
	p.SetVariable("opt_value", "play");
}
//为所有控件去掉ESC的捕获
function fDropEscKey(e) {
	var e = e ? e : event;
	var el = gIsIE ? e.srcElement : e.target;
	if (e.keyCode == 27) {
		el.blur();
	}
}
function fDropSpaceKey(e) {
	var e = e ? e : event;
	var el = gIsIE ? e.srcElement : e.target;
	if (e.keyCode == 32) {
		fPreventDefault(e);
	}
}
function fShiftClick(e)
{
	var e = e ? e : event;
	var el = gIsIE ? e.srcElement : e.target;
	var target = el.getAttribute("_target");
	if (!target)
	{
		target = el.target;
		el.setAttribute("_target", target);
	}
	el.target = e.shiftKey == true ? "_blank" : target;
}
function fIniAllInput(doc) {
	var o = GelTags("input", doc);
	for (var i = o.length - 1; i >= 0; i--) {
		if (o[i].type == "text") {
			fAddEvent(o[i], "keydown", fDropEscKey);
		}
		else if (o[i].type == "button") {
			fAddEvent(o[i], "keydown", fDropSpaceKey);
		}
	}
	o = GelTags("textarea", doc);
	for (var i = o.length - 1; i >= 0; i--) {
		fAddEvent(o[i], "keydown", fDropEscKey);
	}
	o = GelTags("a", doc);
	for (var i = o.length - 1; i >= 0; i--) {
		fAddEvent(o[i], "click", fShiftClick);
	}
}
function fIniAllKeyDow(e) {
	var target = e.target ? e.target : e.srcElement;
	if (e.ctrlKey)
	{
		if (e.altKey && e.keyCode == "68") {
			MaximizeMainFrame(2);
			fPreventDefault(e);
			return false;
		}
		else if (e.keyCode == "37" || e.keyCode == "39") {
			GoPrevOrNextMail(e.keyCode == "39");
			fPreventDefault(e);
			return false;
		}
	}
	if (e.keyCode == "46") {
		if (target.type != "text" && target.tagName != "TEXTAREA") {
			var btn = S(e.shiftKey ? "quick_completelydel" : "quick_del", GetMainWin());
			var btn2 = e.shiftKey ? S("quick_del", GetMainWin()) : null;
			if (btn && btn.style.display != "none" || btn2 && btn2.style.display != "none") {
				try{
					(btn ? btn : btn2).onclick();
					fPreventDefault(e);
					return false;
				}catch(e){}
			}
		}
	}
	if (e.keyCode == "8") {
		if (target.type != "text" && target.tagName != "TEXTAREA" && GoBackHistory()) {
			fPreventDefault(e);
			return false;
		}
	}
	if (e.keyCode == "13") {
		if (target.type != "text" && target.tagName != "TEXTAREA" && ReadReadedBeforeItem()) {
			fPreventDefault(e);
			return false;
		}
	}
	if (e.keyCode == "38" || e.keyCode == "40") {
		if (target.type != "text" && target.tagName != "TEXTAREA") {
			if (!e.ctrlKey && ScrollQuickReadedMail(e.keyCode == "38"))
			{
				fPreventDefault(e);
				return false;
			}
			else if (SetPrevOrNextItemReadedBefore(e.keyCode == "40"))
			{
				if (GetMainWin().gQRMOldObj != null)
				{
					QuickReadMail();
				}
				fPreventDefault(e);
				return false;
			}
		}
	}
	if (e.keyCode == "32" || e.keyCode == "90")
	{
		if (target.type != "text" && target.tagName != "TEXTAREA" && QuickReadMail()) {
			fPreventDefault(e);
			return false;
		}
	}
	if (e.keyCode == "88")
	{
		if (target.type != "text" && target.tagName != "TEXTAREA" && SetItemReadedListCheck(e.shiftKey))
		{
			fPreventDefault(e);
			return false;
		}
	}
}
function DayCtrl(oy,om,od){
	var mlen = monthdaylen[om.value-1];
	if( (oy.value%4==0&&oy.value%100!=0||oy.value%400==0) && om.value==2 )mlen++;
	if(od.options.length>mlen) od.options.length=mlen;
	for(var i=od.options.length;i<mlen;i++)
		od.options[i] = new Option(i+1,i+1);
}
function makeTimeSelect(sname,label,vObj,attr){
	var str;
	str = "<SELECT name='"+sname+"' id='"+sname+"' value='' "+attr+" >";
	for(k in vObj){
		if ( k=="Extend")continue;
		str += "<OPTION value='"+vObj[k]+"' >"+k+"</OPTION>";
	}
	str += "</SELECT> "+label;
	return str;
}
//验证时间有效性函数；
function CheckDateTime(strDate) {
	var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
	var para = strDate.match(reg);
	if(para == null)
		return false;
	var time = new Date(para[1], para[3]-1, para[4]);
	var strFeedback = time.getFullYear() + para[2] + (time.getMonth()+1) + para[2] + time.getDate();
	return strFeedback == strDate;
}
function CheckMail(strmail)
{
	if (strmail=="") {
		showError("添加的内容不能为空");
		return false;
	}
	var reg = /^[\.a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
	var para = strmail.match(reg);
	if(para == null)
	{
		showError("您输入的邮箱地址不正确，请重新输入");
		return false;
	}
	return true;
}
//检查添加的黑白名单是否为空
function CheckAndSubmit(i) {
	var strmail = Trim(S(i).value);
	if(!CheckMail(strmail))
	{
		S(i).focus();
		return false;
	}
	SubmitToActionFrm(S(i).form);
}
//通用生成iframe API
function CreatePanel(win, id, url, onloadEvent) {
	if (!id) return false;
	if (!S(id, win)) {
		InsertHTML(win.document.body, "afterBegin", 
			['<iframe frameborder="0" scrolling="no" id="', id, '" name="', id, '" class="menu_base_if', (url?' bd':''), 
			'" style="display:none;left:0;top:0;" src="'+(url?url:'about:blank'), '" ', 
			(onloadEvent?'onload="' + onloadEvent + '"':(url?'onload="this.className=\'menu_base_if\'"':'')), 
			'></iframe>'].join(""));
	}
	return true;
}
//对象位置计算API
function fCalcPos(obj) {
	var pos = [0, obj.offsetWidth, obj.offsetHeight, 0];
	for (; obj;obj = obj.offsetParent) {
		pos[3] += obj.offsetLeft;
		pos[0] += obj.offsetTop - ( obj.offsetParent ? obj.scrollTop : 0 );
	}
	pos[1] += pos[3];
	pos[2] += pos[0];
	return pos;
}
//menu API
function ShowPageMenu(obj, mid, iLeft, iTop, width, itemHeight, arrOpt, arrFun) {
	ShowWebMenu(window, obj, mid, iLeft, iTop, width, itemHeight, arrOpt, arrFun);
}
function ShowTopMenu(obj, mid, iLeft, iTop, width, itemHeight, arrOpt, arrFun) {
	ShowWebMenu(top, obj, mid, iLeft, iTop, width, itemHeight, arrOpt, arrFun);
}
function fWebMenuMouseOver(obj) {
	obj.className = "menu_item_high";
}
function fWebMenuMouseOut(obj) {
	obj.className = "menu_item";
}
function CreateWebMenu(obj, win, mid, width, itemHeight, arrOpt, arrFun) {
	if (!obj || !win) return false;
	var f =F(obj.id, win);
	var d = S(mid, f);
	if (!d && arrOpt != null) {
		if (!S("qqmail_menu", f)) {
			f.document.body.innerHTML = [
				"<body style='margin:0'><link rel='stylesheet' type='text/css' href='", GetPath("css", true), 
					"comm.css' /><link rel='stylesheet' type='text/css' href='", GetPath("css", true), "skin", GetPath("skin"), 
					".css' /><div id=qqmail_menu class=menu_base unselectable=on></div></body>"].join("");
		}
		fAddEvent(f.document.body, "contextmenu", fPreventDefault);
		fAddEvent(f.document.body, "dragstart", fPreventDefault);
		fAddEvent(f.document.body, "selectstart", fPreventDefault);
		d = f.document.createElement("div");
		d.id = mid;
		d.className = "menu_bd bd";
		d.unselectable = "on";
		for (var i = 0; i < arrOpt.length; i ++) {
			var item = f.document.createElement("div");
			item.className = arrFun[i] ? "menu_item" : "menu_item_nofun";
			if (gIsIE) item.style.width = parseInt(width);
			item.style.height = itemHeight;
			item.style.lineHeight = itemHeight;
			item.unselectable = "on";
			item.innerHTML = arrOpt[i];
			if (arrFun[i]) {
				item.onmouseover = function() {fWebMenuMouseOver(this);};
				item.onmouseout = function() {fWebMenuMouseOut(this);};
				fAddEvent(item, "click", arrFun[i]);
				fAddEvent(item, "click", function(){fWebMenuMouseOut(this);HideWebMenu();});
			}
			d.appendChild(item);
		}
		var b = S("qqmail_menu", f);
		b.innerHTML = "";
		b.appendChild(d);
		obj.style.width = parseInt(width) + 3;
		obj.style.height = arrOpt.length * parseInt(itemHeight) + 11;
	}
	return true;
}
function ShowWebMenu(win, obj, mid, iLeft, iTop, width, itemHeight, arrOpt, arrFun) {
	var baseObj = S("qqmail_menu", win);
	if (!baseObj) {
		CreatePanel(win, "qqmail_menu");
		return setTimeout(function() {ShowWebMenu(win, obj, mid, iLeft, iTop, width, itemHeight, arrOpt, arrFun)}, 0);
	}
	if (top.gCurrentMenuObj && top.gCurrentMenuObj == obj) return HideWebMenu();
	HideWebMenu();
	CreateWebMenu(baseObj, win, mid, width, itemHeight, arrOpt, arrFun);
	if (iLeft != null) baseObj.style.left = iLeft;
	if (iTop != null) baseObj.style.top = iTop + 2;
	Show(baseObj, 1);
	top.gCurrentMenuObj = obj;
	top.gCurrentMenuWin = win;
}
function HideWebMenu() {
	if (!top.gCurrentMenuWin) return;
	var m = S("qqmail_menu", top.gCurrentMenuWin);
	if (m) Show(m, 0);
	top.gCurrentMenuObj = null;
	top.gCurrentMenuWin = null;
}
function HideMenuEvent(e) {
	var obj = e.target ? e.target : e.srcElement;
	if (top.gCurrentMenuObj != obj && !fIsInObj(obj, top.gCurrentMenuObj)) HideWebMenu();
	try {top.QQPlusUI.HideMenuEvent(obj);}catch (e){}
}

//model dialog API
function ModelDialog(flag, title, content, focusId, arr_id, arr_fun, width, height, hideFunc)
{
	var mask = CreateMask(top);
	var baseObj = S("qqmail_dialog", top);
	if (!baseObj)
	{
		if (flag == 0)
		{
			return;
		}
		CreatePanel(top, "qqmail_dialog");
		return setTimeout(function() {ModelDialog(flag, title, content, focusId, arr_id, arr_fun, width, height, hideFunc);}, 0);
	}
	PushToDialogList("qqmail_dialog");
	if (flag != 0)
	{
		CreateWebDialog(baseObj, top, flag, title, content, focusId, arr_id, arr_fun);
		baseObj.style.width = width ? width : "400px";
		baseObj.style.height = height ? height : "163px";
		baseObj.allowTransparency = "true";
		var tb = top.document.body;
		baseObj.style.left = (tb.clientWidth - parseInt(baseObj.style.width)) / 2 + tb.scrollLeft;
		baseObj.style.top = (tb.clientHeight - parseInt(baseObj.style.height)) / 2 + tb.scrollTop - 25;
	}
	//make dlg move smoothly
	SetDialogEvent(mask, !flag, true);
	Show(baseObj, flag);
	Show(mask, flag);
	setTimeout(function(){top.HideWindowsElement(!flag);}, 0);
	setTimeout(function(){if(flag) {var f = F(baseObj.id, top);f.focus();f=S(focusId, f);if(f)f.focus();}}, 0);
	if (flag == 0)
	{
		try{top.HideModelDialogEvent();}	catch(e){}
	}
	SetHideModelDialogEvent(hideFunc);
}
function SetHideModelDialogEvent(func)
{
	top.HideModelDialogEvent = func;
}
function HideModelDialog()
{
	ModelDialog(0);
}

//non model dialog
function OpenDialog(id, url, bModel, width, height) {
	var mask = CreateMask(top);
	var baseObj = S(id, top);
	if (!baseObj) {
		CreatePanel(top, id, url);
		setTimeout(function() {OpenDialog(id, url, bModel, width, height, true);}, 0);
		return S(id, top);
	}
	PushToDialogList(id);

	if (IsNonModelDialogMinimize(id)) {
		MaximizeDialog(id);
		return baseObj;
	}

	if (baseObj.src != url) baseObj.src = url + "&r="+ Math.random();
	baseObj.style.width = width ? width : "403px";
	baseObj.style.height = height ? height : "390px";
	baseObj.allowTransparency = "true";
	var tb = top.document.body;
	baseObj.style.left = (tb.clientWidth - parseInt(baseObj.style.width)) / 2 + tb.scrollLeft;
	baseObj.style.top = (tb.clientHeight - parseInt(baseObj.style.height)) / 2 + tb.scrollTop - 30;

	top.gCurrentShowNonModelDialogId = id;

	SetDialogEvent(mask, false, bModel);
	Show(baseObj, 1);
	Show(mask, 1);

	setTimeout(function(){top.HideWindowsElement();}, 0);
	setTimeout(function(){F(id, top).focus();}, 0);

	return baseObj;
}
function CloseDialog() {
	if (window != top) top.CloseDialog();
	if (!top.gCurrentShowNonModelDialogId) return;
	var baseObj = S(top.gCurrentShowNonModelDialogId, top);
	if (!baseObj) return;
	baseObj.src = "";
	Show(baseObj, 0);
	var mask = S("qqmail_mask", top);
	Show(mask, 0);
	SetDialogEvent(mask, true);
	top.gCurrentShowNonModelDialogId = null;
	setTimeout(function(){top.HideWindowsElement(true);}, 0);
}
function IsNonModelDialogMinimize(id) {
	var o = S(id + "_min", GetTopWin());
	return o ? (o.style.display == "" ? true : false) : false;
}
function MaximizeDialog(id, bNoAnimation)
{
	if (!id) return;
	var baseObj = S(id, top);
	if (!baseObj) return;
	var minObj = S(id + "_min", GetTopWin());
	bNoAnimation = minObj ? bNoAnimation : true;

	if (!bNoAnimation)
	{
		var pos = fCalcPos(minObj);
		var params = {};
		params.descLeft = baseObj.style.left;
		params.descTop = baseObj.style.top;
		params.descWidth = baseObj.style.width;
		params.descHeight = baseObj.style.height;
		params.orgLeft = pos[1] - 60;
		params.orgTop = pos[0];
		params.orgWidth = 40;
		params.orgHeight = 18;
	}

	var mask = S("qqmail_mask", top);
	Show(mask, 1);
	SetDialogEvent(mask, false, false);

	top.gCurrentShowNonModelDialogId = id;
	if (minObj)
	{
		Show(minObj, false);
	}
	
	if (!bNoAnimation)
	{
		Animation(baseObj, params, 100, function()
		{
			Show(baseObj, true);
		});
	}
	else
	{
		Show(baseObj, 1);
	}
	setTimeout(function(){top.HideWindowsElement();}, 0);
}

function MinimizeDialog()
{
	var mc = S("minimize_container", GetTopWin());
	if (!top.gCurrentShowNonModelDialogId || !mc) return;
	var baseObj = S(top.gCurrentShowNonModelDialogId, top);
	if (!baseObj) return;

	var mask = S("qqmail_mask", top);
	Show(mask, 0);
	SetDialogEvent(mask, true);

	Show(baseObj, 0);
	top.gCurrentShowNonModelDialogId = null;

	var minId = baseObj.id + "_min";
	var min = S(minId, GetTopWin());
	if (!min)
	{
		InsertHTML(mc, "beforeEnd", 
		['<span id="', minId, '"><a onclick="top.MaximizeDialog(\'', baseObj.id, '\')">', 
				S("dialog_title", F(baseObj.id, top)).innerHTML, 
		'</a>&nbsp;&nbsp;|&nbsp;&nbsp;'].join(""));
		min = S(minId, GetTopWin());
	}
	Show(min, true);

	var pos = fCalcPos(min);
	var params = {
		orgLeft:		baseObj.style.left, 
		orgTop:		baseObj.style.top, 
		orgWidth:		baseObj.style.width, 
		orgHeight:	baseObj.style.height,
		descLeft:		pos[1] - 60,
		descTop:		pos[0],
		descWidth:	40,
		descHeight:	18
	};

	var objPos = [baseObj.style.left, baseObj.style.top, baseObj.style.width, baseObj.style.height];
	var pos = fCalcPos(mc);

	setTimeout(function(){top.HideWindowsElement(true);}, 0);

	return Animation(baseObj, params, 100);
}
//dialog public
function IsModelDialogShow(id)
{
	var baseObj = S("qqmail_dialog", top);
	if (baseObj && baseObj.style.display != "none") return id ? (S(id, F("qqmail_dialog", top)) ? true : false) : true;
	return false;
}
function IsDialogShow(id) {
	var baseObj = S(top.gCurrentShowNonModelDialogId ? top.gCurrentShowNonModelDialogId : "qqmail_dialog", top);
	if (baseObj && baseObj.style.display != "none") return id ? (S(id, F(baseObj.id, top)) ? true : false) : true;
	return false;
}
function GetDialogObj(id) {
	var baseObj = S(top.gCurrentShowNonModelDialogId ? top.gCurrentShowNonModelDialogId : "qqmail_dialog", top);
	return S(id, F(baseObj.id, top));
}
//dialog private
function PushToDialogList(id)
{
	if (!top.dialog_list) top.dialog_list = new top.Object;
	if (!id) return;
	top.dialog_list[id] = true;
}
function SetDialogEvent(mask, bRemove, bModel) {
	fAddEvent(top.document, "mousemove", top.fOnDialogMove, bRemove);
	fAddEvent(top.document, "mouseup", top.fOnDialogMouseUp, bRemove);
	if (mask) fAddEvent(mask, "mousedown", top.HighLightDialog, bRemove);
}
function HighLightDialog() {
	if (top.gCurrentDialogInterval) clearInterval(top.gCurrentDialogInterval);
	if (IsDialogShow()) {
		var times = 1;
		top.gCurrentDialogInterval = setInterval(function(){
			var t = GetDialogObj("editor_dialog_titlebar");
			var t1 = GetDialogObj("no_move");
			if (t) t.className = "editor_dialog_titlebar " + (times % 2 ? "toolbg" : "fdbody");
			if (t1) t1.className = times % 2 ? "" : "fdbody";
			if (times == 4 || !IsDialogShow()) return clearInterval(top.gCurrentDialogInterval);
			times ++;
		}, 50);
	}
}
function CreateMask(win) {
	win = win || top;
	var id = "qqmail_mask";
	var mask = S(id, win);
	if (!mask)
	{
		InsertHTML(win.document.body, "afterBegin", 
			['<div id="', id, '" class="editor_mask" style="display:none;"></div>'].join(""));
		mask = S(id, win);
	}
	return mask;
}
function CreateWebDialog(obj, win, flag, title, content, focusIn, arr_id, arr_fun) {
	if (!obj || !win) return false;
	var f = F(obj.id, win);
	if (!S("dialog_base", f)) {
		f.document.body.innerHTML = 
			["<body>",
				"<link rel='stylesheet' type='text/css' href='", GetPath("css", true), "comm.css' />",
				"<link rel='stylesheet' type='text/css' href='", GetPath("css", true), "skin", GetPath("skin"), ".css' />",
				"<div id=dialog_base class=editor_dialog unselectable='on'>",
					"<div id='opashow' class='opashow'>&nbsp;</div>",
					"<div class='bd_upload'>",
						"<div id='editor_dialog_titlebar' class='fdbody' style='height:28px;border:none;background-image:none;cursor:move;' unselectable='on' onselectstart='return false;'>",
							"<div class='fdbody' style='cursor:default;float:right;width:40px;border:none;background-image:none;' id='no_move'>",
								"<div id='editor_close' class='editor_close' onmouseover='this.className=\"editor_close_mover\";' onmouseout='this.className=\"editor_close\";'>",
									"<img src='", GetPath("image", true), "ico_closetip.gif' width='12' height='12' ondragstart='return false;'>",
								"</div>",
							"</div>",
							"<div class='editor_dialog_title' id='dialog_title' unselectable='on' ></div>",
						"</div>",
						"<div id='dialog_content' class='editor_dialog_content mailinfo' style='border:none;' unselectable='on' onselectstart='return false;'></div>",
					"</div>",
				"</div>",
			"</body>"].join("");
		fAddEvent(f.document.body, "contextmenu", fPreventDefault);
		fAddEvent(f.document.body, "dragstart", fPreventDefault);
		fAddEvent(f.document.body, "selectstart", fPreventDefault);
		f.document.body.className="tipbg";
		S("editor_close", f).onclick = win.HideModelDialog;
		fAddEvent(S("editor_dialog_titlebar", f), "mousedown", win.fOnDialogMouseDown);
		fAddEvent(S("editor_dialog_titlebar", f), "mouseup", win.fOnDialogMouseUp);
		fAddEvent(f.document, "mousemove", win.fOnDialogMove);
	}
	S("dialog_content", f).innerHTML = flag ? content : "";
	S("dialog_title", f).innerHTML = flag ? title : "";
	setTimeout(function(){
		var div = S("dialog_base", f).childNodes[1];
		S("opashow", f).style.width = parseInt(div.scrollWidth) + "px";
		S("opashow", f).style.height = parseInt(div.scrollHeight) + "px";
	}, 100);
	if (!arr_id || !arr_fun) return;
	for (var i = arr_id.length - 1; i >= 0; i--) {
		var o = S(arr_id[i], f);
		if (o && arr_fun[i]) o.onclick = arr_fun[i];
	}
}
function fOnDialogMouseDown(e) {
	if ((e.target ? e.target : e.srcElement).id == "no_move") return;
	top.gPageCursorOldX = e.screenX;
	top.gPageCursorOldY = e.screenY;
	top.gPageDialogMouseDown = true;
	return false;
}
function fOnDialogMouseUp(e) {
	top.gPageDialogMouseDown = false;
}
function fOnDialogMove(e) {
	if(top.gPageDialogMouseDown) {
		var o = S(top.gCurrentShowNonModelDialogId ? top.gCurrentShowNonModelDialogId : "qqmail_dialog", top);
		o.style.left = parseInt(o.style.left) + e.screenX - top.gPageCursorOldX;
		o.style.top = parseInt(o.style.top) + e.screenY - top.gPageCursorOldY;
		top.gPageCursorOldX = e.screenX;
		top.gPageCursorOldY = e.screenY;
	}
}

//animation api
function Animation(obj, params, time, callbackFun) {
	if (!obj)
	{
		return;
	}

	var curVal = [parseInt(params.orgLeft), parseInt(params.orgTop), parseInt(params.orgWidth), parseInt(params.orgHeight)];
	var range = ["left", "top", "width", "height"];
	var rangeLen = range.length;
	var interval = 10;

	try
	{
		var objDoc = obj.ownerDocument;
		var animationObj = objDoc.getElementById(obj.id + "_animation");
		if (!animationObj)
		{
			animationObj = objDoc.createElement("div");
			animationObj.id = obj.id + "_animation";
			animationObj.style.position = "absolute";
			obj.parentNode.appendChild(animationObj);
		}
		animationObj.className = "bd_upload";
		animationObj.style.borderWidth = "2px";
		animationObj.style.zIndex = obj.style.zIndex;
		animationObj.style.display = "block";
		for (var i = 0; i < rangeLen; i++)
		{
			animationObj.style[range[i]] = curVal[i] + "px";
		}
	}
	catch (e)
	{
		//不支持动画
		if (callbackFun)
		{
			try{callbackFun();}catch(e){}
		}
		return;
	}

	time = (time && time > 150 ? time : 150) / interval;
	var step = [
		  parseInt((params.descLeft != null ? parseInt(params.descLeft) - curVal[0] : 0) / time)
		, parseInt((params.descTop != null ? parseInt(params.descTop) - curVal[1] : 0) / time)
		, parseInt((params.descWidth != null ? parseInt(params.descWidth) - curVal[2] : 0) / time)
		, parseInt((params.descHeight != null ? parseInt(params.descHeight) - curVal[3] : 0) / time)
	];

	var t = 0;
	var func = function()
	{
		if (++t > time)
		{
			Show(animationObj, false);
			if (callbackFun)
			{
				try{callbackFun();}catch(e){}
			}
			return ;
		}
		try
		{
			for (var i = 0; i < 4; i++)
			{
				curVal[i] = PositiveNumber(curVal[i] + step[i]);
				animationObj.style[range[i]] = curVal[i] + "px";
			}
		}
		catch (e)
		{
		}
		setTimeout(func, interval);
	};
	setTimeout(func, interval);
}
function PositiveNumber(val) {
	return val >= 0 ? val : 0;
}

function OnError(msg, url, line)
{
	//alert("js error:\n" + "msg:" + msg + "\nline:" + line + "\nurl:" + url);
	RunUrlWithSid("/cgi-bin/getinvestigate?stat=js_run_err&msg=" + msg + "&line=" + line + "&url=" + encodeURIComponent(url));
	return true;
}

//onload ini
function InitPageEvent(win)
{
	win = win ? win : window;
	win.onerror = OnError;
	fAddEvent(win.document, "mousedown", HideMenuEvent);
	fAddEvent(win.document, "keydown", fIniAllKeyDow);
	fAddEvent(win, "load", function()
	{
		fObjectActive(win.document);
	});
	fAddEvent(win, "load", function()
	{
		fIniAllInput(win.document);
	});
	fAddEvent(win, "unload", function()
	{
		if (win == GetMainWin() && !top.bMessageBoxHide) HiddenMsg();
	});
	if (GetMainWin() == window)
	{
		try { top.QQTalkDlg.MaximizeDlg(2); } catch (e) {}
		var keyList = ["templatename=readmail", "templatename=note_first_page", 
			"/addr_listall?", "templatename=reader_list"];
		E(keyList, function(key)
		{
			if (key && win.location.href.indexOf(key) != -1)
			{
				return (function()
				{
					try
					{
						win.document.body.focus();
					}
					catch (e)
					{
						return setTimeout(arguments.callee, 100);
					}
				})();
			}
		});
	}
	if (win == top && top.location.href.indexOf("frame_html") != -1)
	{
		fAddEvent(win, "load", function(e)
		{
			fAddEvent(top.document.body, "mousewheel", function(e)
			{
				fPreventDefault(e);
			});
		});
	}
}

InitPageEvent();

function HideWindowsElement(bShow, win) {
	if (!gIsIE) return;
	if (!win) win = top;
	var swaps = ["select", "object", "embed"];
	var val = bShow ? "visible" : "hidden";
	for (var i = swaps.length - 1; i >= 0; i--) {
		var objs = GelTags(swaps[i], win.document);
		for (var j = objs.length - 1; j >= 0; j--) {
			if (objs[j].getAttribute("nohide") != "true")
			{
				objs[j].style.visibility  = val;
			}
		}
	}
	objs = GelTags("iframe", win.document);
	for (var i = objs.length - 1; i >= 0; i--) {
		try{top.HideWindowsElement(bShow, objs[i].contentWindow);}catch(e){}
	}
}

function FormatAddr(value)
{
	if(!value || value.length <=0) return "";

	var addrs = value.split(";");
	var map = {},result = [],mkey,key;
	for(var i=0,len=addrs.length; i<len; i++)
	{
		key = addrs[i].toLowerCase();
		mkey = key.replace(/ /ig, "");
		if(mkey !="" && map[mkey] == null)
		{
			key = key.replace(/\\\"/ig, "<Q>").split("\"");
			var keyLen = key.length;
			if (keyLen > 3)
			{
				key.splice(1, keyLen - 2, key.slice(1, keyLen - 1).join("\\\""));
			}
			result.push(key.join("\"").replace(/<Q>/g, "\\\""));
			map[mkey] = 1;
		}
	}
	if (result.length > 0)
	{
		result.push(" ");
	}

	return result.join(";");
}

function CheckPopMailShow(str)
{
	var a = ["@126.com","@163.com","@yahoo.com.cn","@sina.com","@gmail.com","@tom.com","@yeah.net"];
	var n = str.toLowerCase();
	for(var i=0;i<a.length;i++){if(n.indexOf(a[i])>=0) return true;}
	return false;
}

function SetBeforeUnloadCheck(win, msg, focusObj, exceptObjs, container)
{
	win = win ? win : window;
	container = container ? (typeof(container) == "string" ? S(container, win) : container) : win.document;
	win.IsBeforeUnloadCheck = true;
	var list = ["input", "select", "textarea"];
	for (var i = 0, len = list.length; i < len; i++)
	{
		var name = list[i] + "_save";
		win[name] = [];
		var tags = GelTags(list[i], container);
		for (var j = 0, jlen = tags.length; j < jlen; j++)
		{
			win[name].push(tags[j].value + tags[j].checked);
			tags[j].setAttribute("saveid", j);
		}
	}
	if (!win.onsetbeforeunloadcheck)
	{
		win.onsetbeforeunloadcheck = function()
		{
			if (win.IsBeforeUnloadCheck)
			{
				for (var i = 0, len = list.length; i < len; i++)
				{
					var name = list[i] + "_save";
					var tags = GelTags(list[i], container);
					for (var j = 0, jlen = tags.length; j < jlen; j++)
					{
						var saveid = tags[j].getAttribute("saveid");
						if (saveid != null && win[name][saveid] != (tags[j].value + tags[j].checked))
						{
							//try{(focusObj == null ? S("confirm", win) : (typeof(focusObj) == "string" ? S(focusObj, win) : focusObj)).focus();}catch(e){}
							return msg ? msg : "您修改的设置尚未保存，确定要离开吗？";
						}
					}
				}
			}
		};
		if (gIsIE)
		{
			win.document.body.onbeforeunload = function(){return win.onsetbeforeunloadcheck();};
		}
		else
		{
			win.document.body.setAttribute("onbeforeunload", "return onsetbeforeunloadcheck();");
		}
	}
	if (!exceptObjs)
	{
		exceptObjs = ["cancel"];
	}
	for (var i = 0, len = exceptObjs.length; i < len; i++)
	{
		var obj = exceptObjs[i];
		obj = typeof(obj) == "string" ? S(obj, win) : obj;
		fAddEvent(obj, "mousedown", function(){win.IsBeforeUnloadCheck = false;});
	}
	var f = GelTags("form", win.document);
	for (var i = 0, len = f.length; i < len; i++)
	{
		fAddEvent(f[i], "submit", function(){win.IsBeforeUnloadCheck = false;});
		if (!f[i]._submit)
		{
			f[i]._submit = f[i].submit;
			f[i].submit = function()
			{
				win.IsBeforeUnloadCheck = false;
				this._submit();
			};
		}
	}
}

