// JavaScript Document
// mail需要调用到系统的核心代码

//套组名（钱龙免费资讯）
var G_STR_SUITNAME = "QLFREE";


//得到操作的控件
function client_external() {
    return window.external.qlC;
}

function client_core_interface() {
    return G_Parent.client_external();
}


function _trace(s) {
    try {
        var obj = client_core_interface();
        f_client_call("S_Debug_Print", s);
    }
    catch (e)
    { }
}

//9.5	提取某个已经寄存的数据项(S_Etc_LoadData)
//keyName 参数名称
//regionType 数据存放的位置 0-存放于永久数据区 1-存放于可替换数据区
function client_data_load(keyName, regionType) {
    try {
        var obj = client_core_interface();
        var stkData = f_client_call("S_Etc_LoadData", keyName + "\r\n" + regionType);
        if (stkData == null || stkData.length == 0)
            return null;
        var iPos = stkData.indexOf("\r\n"); //查看附带的时间戳
        if (iPos <= 0)
            return null;
        var timeStamp = stkData.substring(0, iPos);
        var pData = stkData.substring(iPos + 2, stkData.length);
        //时间戳的格式 YYYYMMDD HH:MM:SS
        if (timeStamp.length != 17)
            return null;

        var rltObj = {};
        //特别注意，javascript中，mm月份的定义为(0-11)，所以这里必须做 -1 操作
        rltObj.TimeStamp = new Date(timeStamp.substring(0, 4), timeStamp.substring(4, 6) - 1, timeStamp.substring(6, 8),
      															timeStamp.substring(9, 11), timeStamp.substring(12, 14), timeStamp.substring(15, 17));
        rltObj.dValue = pData.replace(/\n\n/g, "\r\n");
        return rltObj;
    }
    catch (e) {
        _trace("出错(client_data_load()):" + e.message);
        return null;
    }
}

//----------------------------------------------------------------------------------------------------------
// 数据保存、载入相关                                              -------------
//----------------------------------------------------------------------------------------------------------
function client_data_save(keyName, opType, dataValue, regionType) {
    try {
        var obj = client_core_interface();
        var stkData = f_client_call("S_Etc_SaveData", keyName + "\r\n" + opType + "\r\n" + dataValue.replace(/\r\n/g, "\n\n") + "\r\n" + regionType);
        return stkData;
    }
    catch (e) {
        _trace("出错(client_data_save()):" + e.message);
        return "0" + e.message;
    }
}

//记录行为统计日志
function write_log(id, text) {
    try {
        var obj = client_core_interface();
        f_client_call("S_WriteOPLog", id + "\r\n" + text);
    }
    catch (e) {
        return;
    }
}

//公共调用客户端函数
function f_client_call(name, params) {
    var today = new Date();
    var isd = today.getMinutes() * 60 * 1000 + today.getSeconds() * 1000 + today.getMilliseconds();

    var callobj = client_core_interface();
    if (callobj == null) return null;

    var data = callobj.r(name, params);

    today = new Date();
    var new_isd = today.getMinutes() * 60 * 1000 + today.getSeconds() * 1000 + today.getMilliseconds();
    var difftime = new_isd - isd;
    //log.info(difftime.toString() + " name=" + name + "    params=" + params);
    return data;

}

//公共调用客户端回调函数
function f_client_callback(name, params, callback, callbackparams) {
    //log.info("name=" + name + "    params=" + params + "    callback=" + callback + "   callbackparams=" + callbackparams);
    var callobj = client_core_interface();
    if (callobj == null) return null;
    return callobj.c(name, params, callback, callbackparams);
}

jQuery.createXMLDocument = function (string) {
    var browserName = navigator.appName;
    var doc;

    if (browserName == 'Microsoft Internet Explorer') {
        doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.async = 'false'
        doc.loadXML(string);
    } else {
        doc = (new DOMParser()).parseFromString(string, 'text/xml');
    }

    return doc;
}

//打开消息中心
function OpenMailCenter(param) {
    var data = f_client_call(
	"S_MSG_OPENMAINWND", param);
}

//弹出消息中心
function OpenPOPMail(param) {
    var data = f_client_call(
	"S_MSG_OPEN", param);
}

//打开邮件回执列表
function OpenReturnList(param) {
    var data = f_client_call(
	"S_MSG_OPENRETURNLISTWND", param);
}


//回执
function WriteReceipt(param) {
    var data = f_client_call(
	"S_MSG_RECEIPT", param);
}

//初始化
function mailjs() {
    if (G_Parent == null)
        G_Parent = getParent(window);

    // 页面加载时清空注册回调
    {
        try {
            var obj = client_core_interface();
            f_client_call('G_Frame_CancleAllReq', '')
        }
        catch (e) {
        }
    }

    var rtnType = GetVersion();
    if (rtnType == "0") {
        G_Parent.GLOBAL_Write = "writemail.htm";
    }
    else {
        G_Parent.GLOBAL_Write = "businesscard.htm";
    }
}

// 获取账户
function getAccountid() {
    var data = f_client_call(
		"G_SYS_UserName");
    if (data != null) {
        var datas = data.split("\r\n");
        return datas[0];
    }
    else {
        return "";
    }
}

// 设置邮件属性
function SetAttrib(attrib) {
    var data = f_client_call(
		"S_MSG_SETATTRIB", attrib);
    return data;
}

// 保存邮件
function SaveMail(xml) {
    var data = f_client_call(
		"S_MSG_SAVE", xml);
    return data;
}

// 获取邮件
function GetMail(seq) {
    var data = f_client_call(
		"G_MSG_GET", seq);
    return data;
}

// 删除附件
function DeleteAttach(seq, nid) {
    var data = f_client_call(
		"S_MSG_DEL_ATTACH", seq + "\r\n" + nid);
    return data;
}

// 获取消息中心版本
function GetVersion() {
    var data = f_client_call(
		"G_MSG_VERSION", "");
    return data;
}

//获取附件
function getAttach(sSeq) {
    var data = f_client_call(
		"G_MSG_ATTACH", sSeq);
    var iFirstAttach = data.indexOf("<attach");
    var iLastAttach = data.lastIndexOf("</attach>");
    var sAttach = ""
    if (iFirstAttach != -1 && iLastAttach != -1) {
        var sAttach = data.substring(iFirstAttach, iLastAttach + 9);
    }
    G_Parent.GLOBAL_Attach = sAttach;
}

function ReceiveMail() {
    var data = f_client_call("S_MSG_RECV");
    if (data == "-1") {
        hidLoading();
    }
}

function getMailLists() {
    var data = f_client_call("G_MSG_LIST");
    var datas = data.split("\r\n");
    datas = datas.reverse();
    var OReturn = {};
    OReturn["iSent"] = 0;
    OReturn["iTrashUnRead"] = 0;
    OReturn["iindexUnRead"] = 0;
    OReturn["iInbox"] = 0;
    OReturn["iTrash"] = 0;
    OReturn["iDrafts"] = 0;
    OReturn["aInbox"] = new Array;
    OReturn["aDrafts"] = new Array;
    OReturn["aSent"] = new Array;
    OReturn["aTrash"] = new Array;
    for (i = 0; datas != null && i < datas.length; i++) {
        if (datas[i] == "") {
            continue;
        }
        var mail = datas[i].split("|");
        var object = {};
        object["seq"] = mail[0];
        object["time"] = mail[1];
        object["attrib"] = "000000" + parseFloat(mail[2]).toString(16);
        object["mailsource"] == "";
        object["unread"] = 0; //已读
        var sattr = object["attrib"].substring(object["attrib"].length - 6, object["attrib"].length);
        object["from"] = mail[3];
        var s2 = parseFloat(sattr.substring(1, 2)).toString(2);
        if (s2.substring(s2.length - 2, s2.length - 1) == "1") {
            OReturn["iTrash"] = OReturn["iTrash"] + 1;
            if (s2.substring(s2.length - 1) == "0") {
                OReturn["iTrashUnRead"] = OReturn["iTrashUnRead"] + 1;
                object["unread"] = 1; //未读
            }
            OReturn["aTrash"].push(object);
            continue;
        }
        switch (sattr.substring(3, 6)) {
            case "001":
                OReturn["iSent"] = OReturn["iSent"] + 1;
                OReturn["aSent"].push(object);
                break;
            case "002":
            	G_MailList_hash_index[object["seq"]]=OReturn["iInbox"];
                OReturn["iInbox"] = OReturn["iInbox"] + 1;
                if (s2.substring(s2.length - 1) == "0") {
                    OReturn["iindexUnRead"] = OReturn["iindexUnRead"] + 1;
                    object["unread"] = 1; //未读
                }
                OReturn["aInbox"].push(object);
                break;
            case "000":
                OReturn["iDrafts"] = OReturn["iDrafts"] + 1;
                OReturn["aDrafts"].push(object);
                break;
        }
    }
    return OReturn;
}


var KEYCODE_TAB = "9"; //TAB的键值
var KEYCODE_DEL = "46"; //DEL的键值
var KEYCODE_ENTER = "13"; //ENTER的键值
var KEYCODE_BACKSPACE = "8"; //BACKSPACE的键值

//客户端主动调用接口
function OnCltKeyPress(KeyCode) {
    switch (KeyCode) {
        case KEYCODE_ENTER:
            if (typeof (window.searchTXT) != "undefined") {
                switch (G_Parent.GLOBAL_CurrCtl) {
                    case "Inbox_search":
                        searchTXT("Inbox");
                        break;
                    case "Sent_search":
                        searchTXT("Sent");
                        break;
                }
            };
            return "1";
            break;
        case KEYCODE_BACKSPACE:
            var stype = $("input:focus").attr("type");
            if (typeof (stype) == "undefined") {
                stype = $("iframe:focus").attr("type");
                if (typeof (stype) == "undefined") {
                    return "1";
                }
                else {
                    stype = "html";
                }
            }
            stype = stype.toLowerCase();
            if ((stype == "text") || (stype == "textarea") || (stype == "html")) {
                return "0";
            }
            else {
                return "1";
            }
            break;
    }
    return "0";
}


function notice(params) {
    var datas = params.split("\r\n");
    switch (datas[0]) {
        case "1":
            //	log.info("发送邮件通知的结果:" + datas[1]);
            notice_receive(datas[1]);
            return;
            break;
        case "2":
            //	log.info("接收邮件通知的结果:" + datas[1]);
            notice_receive(datas[1]);
            return;
            break;
        case "3":
            //	log.info("删除邮件通知的结果:" + datas[1]);
            return;
            break;
        case "4":
            //		log.info("转到邮件列表的结果:" + datas[1]);
            notice_receive(datas[1]);
            break;
        case "5":
            //		log.info("转到指定邮件的结果:" + datas[1]);
            ChangeNewMailStates(datas[1]);
            notice_read(datas[1]);
            return;
            break;
        case "7":
            //		log.info("邮件列表变化通知:" + datas[1]);
            break;
        case "8":
            //		log.info("邮件属性变化通知:" + datas[1]);
            break;
        case "9":
            notice_MailDetail(datas[1]);
            break;
    }
}

function notice_receive(data) {
    if (G_Parent.GLOBAL_Loading == "True") {
        G_Parent.GLOBAL_CurrWin.hidLoading();
    }
    if ((data != "0")) {
        G_Parent.GLOBAL_CurrWin.showReceiveMail();
    }
}

function notice_read(data) {
    try {
        var text = GetMail(data);
        var xml = ql_xml_stringtoxml(text.replace(/\r/g, ""));
        var type = $($(xml).find("type")[0]).attr("no");
        switch (type) {
            case "4":
                var mkcode = $($(xml).find("goldcode")[0]).text();
                OpenShortMail(data, mkcode);
                break;
            case "7":
                gotoenduegoldmail(data); //投顾打开索取黄金眼窗口
                break;
            default:
                var tmpproducttype = $($(xml).find("producttype")[0]).attr("no");
                if (typeof (tmpproducttype) != "undefined" && tmpproducttype != "") {
                    if (tmpproducttype == "3") {
                        gototrialmail(data);  //14天产品试用快速开通
                    } else if (tmpproducttype == "2") {
                        gotoenduegoldmail(data); //短期黄金眼快速开通
                    } else {
                        gotoproductmail(data); //产品中心阅读窗口
                    }
                } else {
                    OpenPOPMail("page=qlmail.htm?seq=" + data);
                }
                break;
        }
    }
    catch (e) {
        alert("本地邮件未收到或已删除！");
    }


}
//消息通知 更新邮件发件数组
function notice_MailDetail(seq) {
    if ((seq != "0")) {
        G_Parent.GLOBAL_CurrWin.changeMailDetail(seq);
    }
}
function stopBubble(e) {
    var e = e ? e : window.event;
    if (window.event) { // IE
        e.cancelBubble = true;
    } else { // FF
        // e.preventDefault();
        e.stopPropagation();
    }
}

function getparamter(sStr, sName) {
    var p = new Poly9.URLParser("1.htm?" + sStr);
    return p.getParameter(sName);
}


//初始化用户数据
function initUsersData() {
    //log.info("initUsersData2");
    load_groups();
    load_AllUsers();
    //log.info("G_users:" + G_users.length);
    load_AllBrokerRight("2", false);
    //log.info("G_broker:" +typeof(G_broker));
    load_Base();
    load_AllBrokers(); //加载投顾数组
    load_AllManagers(); //加载营销人员数组
    //	load_AllGroupsLable();//加载分组数组
}

//字符串编码接口
function encodeString(str) {
    var data = f_client_call(
	"S_SYS_Encode", "0\n0\n" + str);
    return data;
}

//字符串解码接口
function decodeString(str) {
    var data = f_client_call(
	"S_SYS_Encode", "0\n1\n" + str);
    return data;
}

//打开邮件列表窗口
function openMailList(url) {
    //openwindow('../mail/listmail.htm?aaa=test','debug','692px','358px');
    f_client_call("S_MSG_OPENMSGLISTWND", url);
}

function openwindow(url, name, iWidth, iHeight) {
    var url;                                  //转向网页的地址;
    var name;                            //网页名称，可为空;
    var iWidth;                           //弹出窗口的宽度;
    var iHeight;                        //弹出窗口的高度;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;        //获得窗口的垂直位置;
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;           //获得窗口的水平位置;
    window.open(url, name, 'height=' + iHeight + ',,innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
}

function html_encode(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    s = s.replace(/\n/g, "<br>");
    return s;
}

function html_decode(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/<br>/g, "\n");
    return s;
}
// 彻底删除邮件
function DeleteMail(seqs) {
    var data = f_client_call(
		"S_MSG_DELETE", seqs);
    return data;
}

// 打开黄金眼邮件
function OpenShortMail(seq, mkcode) {
    var data = f_client_call(
		"S_MSG_OPENGOLDWND", seq + "|" + mkcode);
    return data;
}

// 查询某一商品代码是否存在
function ExistCode(mk, code) {
    var data = f_client_call(
		"G_Dyn_Exist", mk + "," + code);
    return data;

}
//	获取客户邮件操作日志
function GetReturnMailState(seq) {
    var data = f_client_call(
		"G_SYS_MAILSTATE", seq);
    return data;
}
//返回中文名字排序
function GetOrderList(names) {
    var data = f_client_call(
		"G_SYS_CHARINFO", names);
    return data;
}

//切换到主页
function openMain(param) {
    var data = f_client_call("S_View_Goto", "WEBCOMM\r\n" + "URL=(" + param + ")");
    data = null;
}

function initattachsetting() {
    //注册附件上传URL
    //	client_data_save("UPLOADURL","1",G_FILESERVICE(),"2");
    var data = f_client_call("S_SYS_CONFIG", "UPLOADURL\r\n" + G_FILESERVICE());
    //注册图片大小限制
    //	client_data_save("UPLOADSIZE","1",G_FILESIZE(),"2");
    data = f_client_call("S_SYS_CONFIG", "UPLOADSIZE\r\n" + G_IMGSIZE());
    data = null;
}

/*
*注册智能键盘
*/
function MSG_SYS_REGSMARTKB(cinfo) {
    var tmpdata = "kbtype=contactlist,color=(150,0,150),pre=(,),sort=4,match_value=2,keywidth=15,cmd=(S_VIEW_GOTO WEBCOMM url=(.\\Web\\JJR\\index.htm?page=grxw&id=[M:KEY]))\r\n";
    tmpdata += cinfo;
    var data = f_client_call("S_SYS_REGSMARTKB", tmpdata);
    data = null;
}

/*
*在客户端打开新窗口
*参数：tmptitle：标题  tmpurl:页面地址  a:最大化(1)最小化（2）全部（3）  b:拖动（1）不拖动（0）  c:窗口尺寸（|分隔）  d: 模态（1）非模态（0）  e:窗口ID f:窗口位置（0居中 1左上2右上3左下4右下）
*/
function OpenShowEnduGoldMail(tmptitle, tmpurl, winid) {

    //	data =f_client_call("S_Info_NavUrl",tmpurl);	
    data = f_client_call("S_Info_ShowUrl", tmptitle + "\r\n" + tmpurl + "\r\na=0\r\nb=1\r\nc=447|310\r\nd=0\r\ne=" + Windows_ID_EndueGoldMail + "\r\nf=4");
    data = null;
}