// 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 op(id, opcode) {
    f_client_call("S_MSG_OP", G_Parent.GLOBAL_Seq + "\r\n" + id + "|" + opcode);
}

//弹出消息中心
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 LoginAgain() {
    var data = f_client_call(
	"S_View_RELOGIN", "");
}

//回执
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 NewMail() {
    var data = f_client_call(
		"S_MSG_NEW");
    return data;
}

// 设置邮件属性
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;
}

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

// 转发邮件
function ForwardMail(seq) {
    var data = f_client_call(
		"S_MSG_FORWARD", seq);
    return data;
}

// 获取邮件(全局ID)
function GetMailex(seq) {
    var data = f_client_call(
		"G_MSG_GET_EX", seq);
    return data;
}

// 发送邮件
function SendMail(seq) {
    var data = f_client_call(
		"S_MSG_SEND", seq);
    return data;
}

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

//添加附件
function AddMailAttach(seq, ntype) {
    var data = f_client_call(
		"S_MSG_ADD_ATTACH", seq + "\r\n" + ntype);
    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;
}

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_TAB:
            var stype = $("#host input:focus").attr("type");
            if (typeof (stype) == "undefined") {
                stype = $("#host iframe:focus").attr("type");
                if (typeof (stype) == "undefined") {
                    return "0";
                }
                else {
                    ifrmwrEditor.execCommand('inserthtml', '&nbsp;&nbsp;&nbsp;&nbsp;');
                    return "1";
                }
            }
            else {
                return "0";
            }
            break;
   
        case KEYCODE_ENTER:

            if (typeof (window.insertstock) != "undefined") {
                //智能选股回车以免被拦截
                if (typeof ($($("#host :focus")[0]).attr("value")) != "undefined") {
                    if ($($("#host :focus")[0]).attr("value").length != "6") {
                        if ($($("#host :focus")[0]).attr("stockinputtype") == "stockinputtype") {
                            return "0";
                        }
                    }
                    else {
                        if ($($("#host :focus")[0]).attr("id") == "txtattstock") {
                            if (tas.TgList.style.display != "none") {
                                tas.Select("txtattstock");
                                //	return "0";
                            }
                            else {
                                switch (G_Parent.GLOBAL_CurrCtl) {
                                    case "txtattstock":
                                        insertstock();
                                        return "1";
                                        break;
                                }
                            }
                        }
                        else {
                            return "0";
                        }
                    }
                }
            }

            if ($($("#hostserch :focus")[0]).attr("id") == "CurPage" || $($("#hostserch :focus")[0]).attr("id") == "searchfilter") {
                switch (G_Parent.GLOBAL_CurrCtl) {
                    case "txtcurpage":
                        trunpage(); //跳转到如入页
                        return "1";
                        break;
                    case "txtsearch":
                        searchClick(); //查询
                        return "1";
                        break;
                }
            }



            var stype = $("#host input:focus").attr("type");
            if (typeof (stype) == "undefined") {
                stype = $("#host iframe:focus").attr("type");
                if (typeof (stype) == "undefined") {
                    return "1";
                }
                else {
                    //	ifrmwrEditor.execCommand('inserthtml','<br/>');//不再拦截，已修改为样式控制
                    return "0";
                }
            }
            else {
                return "1";
            }
            break;
        case KEYCODE_BACKSPACE:
            var ofocus = $("#host input:focus");
            var stype = ofocus.attr("type");
            if (typeof (stype) == "undefined") {
                stype = $("#host iframe:focus").attr("type");
                if (typeof (stype) == "undefined") {
                    if (typeof ($($(":focus")[0]).attr("type")) != "undefined") {
                        return "0";
                    } else {
                        return "1";
                    }
                } else {
                    stype = "html";
                }
            }
            stype = stype.toLowerCase();
            if (((stype == "text") || (stype == "textarea") || (stype == "html")) && typeof (ofocus.attr("readOnly")) == "undefined") {
                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_sendreturn(datas[1]);
            break;
        case "6":
            //log.info("增加附件通知的结果:" + datas[1]);
            if (itab == "0") {
                notice_attach(datas[1]);
            }
            break;
    }
}

function notice_sendreturn(data) {
    if (data.indexOf("1|0") == 0) {
        clearTimeout(sendprocess);
        datas = data.split("|");
        if (datas.length >= 3) {
            g_gid = datas[2];
        }
        else {
            g_gid = "";
        }
        sendMailMessage("2"); //发送成功	
    }
    else {
        clearTimeout(sendprocess);
        sendMailMessage("-1"); //发送失败		
    }
}

function notice_attach(data) {
    var datas = data.split(",");
    G_Parent.GLOBAL_Seq = datas[0];
    getAttach(datas[0]);
    G_Parent.GLOBAL_CurrWin.AddAttach();
}

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 getDrawlinestocklist() {
    var data = f_client_call(
	"G_MSG_COMM_DRAWLINE", "");
    return data;
}

//初始化用户数据
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 closeWindow() {
    var data = f_client_call("S_Window_Close", "");
}

//获取当前查看的股票代码
function getCurrStock() {
    var data = f_client_call("G_View_PrevNextStock", "O");
    return data;
}


//字符串编码接口
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 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 OpenShortMail(seq, mk, code) {
    var data = f_client_call(
		"S_MSG_OPENGOLDWND", seq + "|" + mk + "," + code);
    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 GetSearchList(names) {
    var data = f_client_call(
		"G_SYS_SEARCH", 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 getFileSize(param) {
    var data = f_client_call("S_SYS_GETFILESIZE", param);
    return data;
}
/*
*图片放大和缩小
*/
function changimg(obj) {
    if ($(obj).attr("imgtype") == "min") {
        $(obj).attr("class", 'imgmin');
        var tmpwidth = $(obj).attr("maxwidth");
        var tmpheigth = $(obj).attr("maxheight");
        $(obj).css("width", tmpwidth);
        $(obj).attr("imgtype", "max");
        $(obj).attr("title", "点击缩小");
    } else {
        $(obj).attr("class", 'imgmax');
        var tmpwidth = $(obj).attr("minwidth");
        var tmpheigth = $(obj).attr("minheight");
        $(obj).css("width", tmpwidth);
        $(obj).attr("imgtype", "min");
        $(obj).attr("title", "点击放大");
    }
}

function str2asc(str) {
    return str.charCodeAt(0).toString(16);
}

function asc2str(str) {
    return String.fromCharCode(str);
}

function UrlEncode(str) {
    var ret = "";
    var strSpecial = "!\"#$%&'()*+,/:;<=>?[]^`{|}~%";
    var tt = "";
    for (var i = 0; i < str.length; i++) {
        var chr = str.charAt(i);
        var c = str2asc(chr);
        tt += chr + ":" + c + "n";
        if (parseInt("0x" + c) > 0x7f) {
            ret += "%" + c.slice(0, 2) + "%" + c.slice(-2);
        } else {
            if (chr == " ")
                ret += "+";
            else if (strSpecial.indexOf(chr) != -1)
                ret += "%" + c.toString(16);
            else
                ret += chr;
        }
    }
    return ret;
}

function UrlDecode(str) {
    var ret = "";
    for (var i = 0; i < str.length; i++) {
        var chr = str.charAt(i);
        if (chr == "+") {
            ret += " ";
        } else if (chr == "%") {
            var asc = str.substring(i + 1, i + 3);
            if (parseInt("0x" + asc) > 0x7f) {
                ret += asc2str(parseInt("0x" + asc + str.substring(i + 4, i + 6)));
                i += 5;
            } else {
                ret += asc2str(parseInt("0x" + asc));
                i += 2;
            }
        } else {
            ret += chr;
        }
    }
    return ret;
}
/*
*设置是否使用右键复制模拟ctr+v
*1模拟，0不模拟
*/
function initpastesetting(state) {
    data = f_client_call("S_SYS_IEHOOK", "PASTE|" + state);
    data = null;
}

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

    //	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=780|675\r\nd=0\r\ne=" + Windows_ID_HisMailList);
    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 OpenServiceModeMail(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=531|351\r\nd=0\r\ne=" + winid + "\r\nf=0");
    data = null;
}
/*
*刷新待办事项、已办事项等注册为 prodcenter 的窗口
*参数 ：Web控件名称\r\njs函数名 js参数列表(空格分割)
*/
function  RefreshTask()
{
 	data = f_client_call("S_SYS_SENDINFO", "prodcenter\r\nreflashTask");
    data = null;

}