//var Oparamter = "";
var NewEmailSeq = "";
var sourceSeq = "";
var sourcesrvSeq = "";
var sourceType = "";
var sourceFrom = "";
var sendprocess;
var sendMailTimeState = "false"; //发送邮件计时是否启用
var g_sendlogtype = "";
var g_sendlogtxt = "";
var g_senders = [];
var g_gid = "";
var sSeq = "";
var srvseq = ""; //服务器源邮件编号
var sName = ""; //发件人姓名
var tsattr = ""; //收件箱还是发件箱
var tmpmk = "";
var tmpcode = "";
var tmpcodename = "";
var procuids = "";
var Senders = ""; //当前发送邮件收件人
var SendersNames = ""; //当前发送邮件收件人姓名
var itab = "1"; // 当前邮件发送类型 
var staskid = ""; //代办事项id
var sproductid = ""; //产品id
var sproductname = ""; //产品名称
var batchmail = "false"; //标识是否是批量邮件 true:批量 false:单独；

var sourceprodmodetype ="2";//当前发送邮件类别： 模板类型  2：黄金眼短期产品 3：14天试用产品  60:办公类产品 61：投顾服务类产品  62：咨询类产品  63：理财类产品 

//发送超时显示消息
function sendfail() {
    clearTimeout(sendprocess);
    sendMailMessage("-2"); //发送失败（超时）
}
//弹出发送邮件等待提示信息
function popupDiv(div_id) {
    $("#" + div_id).css({
        position: "absolute",
        left: ($(window).width() - $("#" + div_id).outerWidth()) / 2,
        top: ($(window).height() - $("#" + div_id).outerHeight()) / 2
    });
    $("#dvWait").hide();
    $("#" + div_id).show();
    if (div_id == "dvWait") {
        $("#dvWait_bg").show();
        sendMailMessage("1");
        mytimer = setTimeout("showtime(1)", 500);
    }
}

//发送邮件成功失败提示
function sendMailMessage(msgType) {
    switch (msgType) {
        case "1": //发送邮件开始
            sendMailTimeState = "true";
            $("#dvWait_1").show();
            $("#dvWait_2").hide();
            $("#dvWait_3").hide();
            $("#dvWait_ok").hide();
            break;
        case "2": //发送邮件成功		
            sendMailTimeState = "false";
            $("#dvWait_1").hide();
            $("#dvWait_2").show();
            $("#dvWait_3").hide();
            $("#dvWait_ok").hide();
            {
            	proc_mkcode_str = tmpcodename + "(" + tmpmk + tmpcode + ")";
                var rtn = setRightShort(g_senders.join(","), "01008", g_gid,proc_mkcode_str).replace(/\r\n/g, "");
                if (rtn != "1") {
                    alert("邮件发送成功,但短期权限分配操作失败!(" + rtn + ")");
                }
                rtn = batchupdateTask_mail(staskid, g_gid).replace(/\r\n/g, "");
//                if (rtn < 0) {
//                    alert("更新待办事项邮件ID失败！");
//                    return;
//                }
            }
            if (g_sendlogtype == "A4") {
                $.each(g_senders, function (i, txt) {
                    write_log("A4", g_gid + "," + txt + ",4");
                });
            }
            else {
                write_log(g_sendlogtype, g_gid + g_sendlogtxt);
            }
            
			RefreshTask(); //待办事项页面刷新
            closetimer = setTimeout("closeMe()", 300);
            break;
        case "-1": //发送邮件失败
            sendMailTimeState = "false";
            $("#dvWait_1").hide();
            $("#dvWait_2").hide();
            $("#dvWait_3").show();
            $("#dvWait_errMsg").text("邮件发送失败!");
            $("#dvWait_ok").show();
            break;
        case "-2": //发送邮件失败
            sendMailTimeState = "false";
            $("#dvWait_1").hide();
            $("#dvWait_2").hide();
            $("#dvWait_3").show();
            $("#dvWait_errMsg").text("连接超时，邮件发送失败!");
            $("#dvWait_ok").show();
            break;
        case "-3": //发送邮件失败
            sendMailTimeState = "false";
            $("#dvWait_1").hide();
            $("#dvWait_2").hide();
            $("#dvWait_3").show();
            $("#dvWait_errMsg").text("系统错误，邮件发送失败!");
            $("#dvWait_ok").show();
            break;
        case "-4": //发送邮件超过8K
            sendMailTimeState = "false";
            $("#dvWait_1").hide();
            $("#dvWait_2").hide();
            $("#dvWait_3").show();
            $("#dvWait_errMsg").text("邮件正文或附件太大!");
            $("#dvWait_ok").show();
            break;
    }
}
//邮件提示计时
function showtime(time) {
    if (sendMailTimeState == "true") {
        $("#dvWait_time").text(time);
        time = time + 1;
        setTimeout("showtime(" + time + ")", 1000);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////
/*
*首次加载
*/
$(function () {
    myload();
});
function myload() {
    mailjs();
    clearMail();
    hideDiv('dvWait');
    var p = new Poly9.URLParser((window.location.href).replace(/%26/g, "&"));
    var ps = p.getQuerystring().toLowerCase();
    var tmpkey = p.getParameter("skey");
    var odata = { "pid": "", "pname": "", "taskId": "", "customerId": "", "customerName": "" };
    //initUsersData();
    load_AllBrokerRight("2", false);
    if (tmpkey == undefined || tmpkey == "") {
        batchmail = "false";
        sSeq = p.getParameter("seq");
        GLOBAL_Seq = sSeq;
        ReadMailex(sSeq);
    } else {
        batchmail = "true";
        var tmpdata = client_data_load(tmpkey, "0");
        if (tmpdata != null) {
            odata = eval('(' + tmpdata.dValue + ')');
        }
        ReadLoadData(odata);
    }

    NewEmailSeq = NewMail();
    initpastesetting(1); //设置客户端邮件复制模拟ctr+v
}
function myunload() {
    initpastesetting(0); //设置客户端邮件复制不模拟ctr+v
}


//清空界面数据
function clearMail() {
    $("#txtSender").text("");
    $("#msgcontent").attr("value", "");
}
/*
*读取缓存信息
*/
function ReadLoadData(odata) {
    Senders = odata.customerId; //当前发送邮件收件人
    if (Senders == undefined) {
        Senders = "";
    }
    Senders = getsender(Senders);


    SendersNames = odata.customerName; //当前发送邮件收件人姓名
    if (SendersNames == undefined) {
        SendersNames = "";
    }
    SendersNames = getsender(SendersNames);

    sourceType = "";
    sourcesrvSeq = ""; //	取源邮件编号

    staskid = odata.taskId; //代办事项id
    if (staskid == undefined) {
        staskid = "";
    }

    sproductid = odata.pid; //产品id
    if (sproductid == undefined) {
        sproductid = "";
    }
    procuids = sproductid; //产品id

    sproductname = odata.pname; //产品名称
    if (sproductname == undefined) {
        sproductname = "******";
    }

    $("#txtSender").text(SendersNames);
    $("#txtSender").attr("title", SendersNames);
    $("#txttitle").text("您的" + sproductname + "已经处理，十分感谢！");
}
/*
*获取用户或id重复值
*/
function getsender(senddata) {
    var Senders = ";";
    var yesno = -1;
    var sendername = $.trim(senddata).split(";");
    $(sendername).each(function (index) {
        var name = $.trim(sendername[index]);
        yesno = Senders.indexOf(name);
        if (yesno < 0) {
            Senders += name + ";";
        }
    });
    if (Senders.length > 1 && Senders.substring(Senders.length - 1) == ";") {
        Senders = Senders.substring(1, Senders.length - 1);
    }
    return Senders;
}

/*
*读取服务器邮件
*/
function ReadMailex(seq) {
    var text = GetMailex(seq);
    var iFirstContent = text.indexOf("<content><![CDATA[");
    var iLastContent = text.lastIndexOf("]]></content>");
    if ((iFirstContent < 0) || (iLastContent < 0)) {

        alert("本地邮件未收到或已删除！");
        closeWindow();
        return;
    }
    var sbody = text.substring(iFirstContent + 18, iLastContent);
    text = text.substring(0, iFirstContent) + "<content></content>" + text.substring(iLastContent + 13, text.length);
    var xml = ql_xml_stringtoxml(text.replace(/\r/g, ""));

    var sattr = "000000" + parseFloat($($(xml).find("mail")[0]).attr("attrib")).toString(16);
    sattr = sattr.substring(sattr.length - 6, sattr.length);
    tsattr = sattr.substring(5, 6);
    sattr = parseFloat(sattr.substring(1, 2)).toString(2);
    if (sattr.substring(sattr.length - 2, sattr.length - 1) != "1") {
        SetAttrib(seq + "\r\n65536");
    }
    else {
        SetAttrib(seq + "\r\n196608");
    }
    var sfrom = $($(xml).find("from")[0]).text();
    GLOBAL_from = sfrom;
    sName = sfrom;
    var tmpsfromName = $($(xml).find("from")[0]).attr("name");
    var sfromName = sfrom;

    if (tmpsfromName != undefined && tmpsfromName != "") {
        sfromName = tmpsfromName;
    }
    Senders = sfrom; //当前发送邮件收件人
    SendersNames = sfromName; //当前发送邮件收件人姓名
    //	var sto = $($(xml).find("to")[0]).text();
    //	var Tos = sto.split(";");
    //	var toName = sto;
    //	var tmpstoName=$($(xml).find("to")[0]).attr("name");	
    //	if(tmpstoName != undefined && tmpstoName != "")
    //	{
    //		toName=tmpstoName;
    //	}
    var stimestamp = $($(xml).find("mail")[0]).attr("timestamp");
    var sattrib = "";
    if ($(xml).find("attrib").length != 0)
        sattrib = $($(xml).find("attrib")[0]).text();
    var stitle = decodeString($($(xml).find("title")[0]).text());
    sourceType = $($(xml).find("type")[0]).attr("no");
    sourcesrvSeq = $($(xml).find("mail")[0]).attr("srvseq"); //	取源邮件编号
    if (sourcesrvSeq == undefined) {
        sourcesrvSeq = "";
    }
    //	var tmpgoldstr=	$($(xml).find("goldcode")[0]).text().split("|")[0];
    staskid = $($(xml).find("producttype")[0]).attr("taskid");
    if (staskid == undefined) {
        staskid = "";
    }
    var tmpproducts = $($(xml).find("producttype")[0]).text();
    sproductid = tmpproducts.split("|")[0]; //产品id
    if (sproductid == undefined) {
        sproductid = "";
    }
    procuids = sproductid;
    sproductname = tmpproducts.split("|")[1]; //产品名称
    if (sproductname == undefined) {
        sproductname = "******";
    }
    
    var tmpgoldstr = $($(xml).find("goldcode")[0]).text().split("|")[0];

    tmpmk = tmpgoldstr.split(",")[0];
    tmpcode = tmpgoldstr.split(",")[1];

    tmpcodename = ExistCode(tmpmk, tmpcode);
    $("#txtSender").text(sfromName);
    $("#txtCode").text("代码：" + tmpcode + " " + tmpcodename);
    $("#txttitle").text("您的" + sproductname + "申请已批准，十分感谢！！");
}



//关闭窗体写应用回执
function preclose() {

}
//+---------------------------------------------------
//| cookie相关的方法
//+---------------------------------------------------
function setCookie(c_name, value) {
    document.cookie = c_name + '=' + escape(value) + ";path=/";
    return;
}



//隐藏弹出层
function hideDiv(div_id) {
    $("#" + div_id).hide();

    if (div_id == "dvWait") {
        $("#dvWait_bg").hide();
    }
}

/*
*itab:1 快速回复，2 带说明回复 3 拒绝回复
*/
function sendNormal() {
    var Action = "sender";
    var userinfo = getSysUser();
    var scid = userinfo[0];
    var sTitle = ""; //邮件标题	
    var sMailbody = ""; //邮件正文
    var procuidates = "";
    var cids = "";

    sTitle = "黄金眼主力数据赋权 " + $("#txtCode").text();
    sMailbody = $("#msgcontent").val();
    if (sMailbody.length > 500) {
        alert("邮件正文内容过多，请填写少于500个字符！"); //130
        return;
    }
    var tmphtml = "<div style=\"border-style:solid;border-width:1px;margin-top:25px;line-height:14px; padding:8px;\">您好！</br>&nbsp;&nbsp;&nbsp;&nbsp;您的服务人员为您发送了" + tmpcodename + "(" + tmpcode + ")的钱龙黄金眼功能，请使用您的电脑金融终端查看该股票的黄金眼主力数据！</br></div>";
    sMailbody = sMailbody.replace(/\n/g, "<br />") + tmphtml;





    sMailbody = sMailbody.replace(/\n/g, "<br />");
    if (sTitle == "") {
        alert("标题不能为空，请填写！");
        return;
    }
    if (sTitle.length > 200) {
        alert("标题内容过多，请填写少于200个字符！");
        return;
    }
    cids = Senders.replace(/;/g, ",");
    CreateMailXML(Action, Senders.toLowerCase(), sTitle, sMailbody, cids, procuids, procuidates, SendersNames);
}

function CreateMailXML(Action, Senders, sTitle, sMailbody, cids, procuids, procuidates, SendersNames) {
    $.ajax({
        url: "mailtemplate.xml",
        dataType: "text",
        success: function (text) {
            var ltext = "";
            ltext = text.replace(" attrib=\"\"", "");
            var xml = ql_xml_stringtoxml(ltext.replace(/\r/g, ""));
            var nd_mail = $($(xml).find("mail")[0]);
            var nd_type = $($(xml).find("type")[0]);
            var nd_from = $($(xml).find("from")[0]);
            var nd_to = $($(xml).find("to")[0]);
            var extra = "";
            nd_mail.attr("seq", NewEmailSeq);
            nd_mail.attr("timestamp", ql_date_yyyymmddhhss(new Date()));
            {
                if (batchmail == "false") {
                    extra = "type=4&source=" + sourcesrvSeq + "&sourcetype=" + sourceType;
                    nd_type.text(sourcesrvSeq + "," + sourceType);
                } else {
                    extra = "type=4";
                }
                nd_type.attr("no", "4");
                if (procuids != "") {
                    nd_type.attr("subno", procuids);
                }
                if(sourceprodmodetype !=""){
                	nd_type.attr("prodtype", sourceprodmodetype);
                }
                $($(xml).find("goldcode")[0]).text(tmpmk + "," + tmpcode + "|01008|短期黄金眼");
                nd_to.attr("name", SendersNames);
                $($(xml).find("to")[0]).attr("name", SendersNames);
            }
            nd_from.text(getAccountid());
            nd_from.attr("name", G_broker["info"].nm);
            if (Senders == "") {
                alert("请输入收件人！");
                return;
            }
            else {
                nd_to.text(Senders);
            }
            $($(xml).find("title")[0]).text(encodeString(sTitle));
            $($(xml).find("content")[0]).text("<![CDATA[" + sMailbody + "]]>");
            var smail = ql_xml_xmltostring(xml).replace("</mail>", G_Parent.GLOBAL_Attach + "</mail>");

            //短期权限扣点
            var crtn = checkRightShort(cids, procuids).replace(/\r\n/g, "");
            switch (crtn) {
                case "1":
                    break;
                case "-1":
                    alert("缺少参数！");
                    return;
                    break;
                case "-2":
                    alert("无效参数！");
                    return;
                    break;
                case "-3":
                    alert("服务包过期！");
                    return;
                    break;
                case "-4":
                    alert("服务包重叠！");
                    return;
                    break;
                case "-5":
                    alert("用户不存在！");
                    return;
                    break;
                case "-6":
                    alert("缺少点数！");
                    return;
                    break;
                case "-8":
                    alert("操作失败！");
                    return;
                    break;
                case "-9":
                    alert("系统错误！");
                    return;
                    break;
                case "-11":
                    alert("权限类邮件仅限于发送给股民，您的收件人中包含了服务人员，请重新输入！");
                    return;
                    break;
                default:
                    alert("分配权限失败！");
                    return;
                    break;
            }
            
                        //更新待办事项
            if (batchmail == "false") {
                var rtn = updateTask(staskid, "1", "", "", "").replace(/\r\n/g, "");

                if (rtn < 0) {
                    alert("更新待办事项失败！");
                    return;
                } else if (rtn == 0) {
                    alert("待办事项已删除！");
                    return;
                }
            } else {
                var rtn = batchupdateTask(staskid, "1", "", "", "").replace(/\r\n/g, "");

                if (rtn < 0) {
                    alert("批量更新待办事项失败！");
                    return;
                }else if (rtn == 0) {
                    alert("待办事项已删除！");
                    return;
                }
            }
            smail = smail.replace("</extra>", (extra == "" ? "title=" + encodeURIComponent(sTitle) : extra + "&title=" + encodeURIComponent(sTitle)) + "</extra>");

            var mySeq = SaveMail(smail); /*返回格式（邮件编号|邮件大小）*/

            var mySeqs = mySeq.split("|");
            if (mySeqs.length > 1) {
                if (Number(mySeqs[1]) > 65535) {
                    alert("邮件总大小超出系统限制,建议尽量通过附件方式发送大型文档！");
                    return;
                }
            }
            mySeq = mySeqs[0];
            if (mySeq == "-1") {
                popupDiv("dvWait");
                sendMailMessage("-4"); //发送失败
                return;
            }
            if (mySeq == "0" || mySeq == "") {
                alert("意外失败！");
                return;
            }
            SetAttrib(mySeq + "\r\n65536");
            if (NewEmailSeq == mySeq) {
                var tmpSenders = Senders.split(";");
                g_senders = tmpSenders;
                if (sourceSeq != "" && sourceSeq != undefined && batchmail == "false") {
                    g_sendlogtype = "A3";
                    g_sendlogtxt = "," + sourceSeq + "," + sourceType + "," + sourceFrom;
                }
                else {
                    g_sendlogtype = "A4";
                    g_sendlogtxt = "," + sourceSeq + "," + sourceType + "," + sourceFrom;
                }
                if (NewEmailSeq == SendMail(NewEmailSeq)) {

                    //NewEmailSeq = NewMail();
                    //G_Parent.GLOBAL_Seq = NewEmailSeq;

                    sendprocess = setTimeout("sendfail()", 15000);
                    popupDiv("dvWait");
                }
                else {
                    popupDiv("dvWait");
                    sendMailMessage("-3"); //发送失败
                }
            }
            else {
                popupDiv("dvWait");
                sendMailMessage("-3"); //发送失败
            }
        }
    })
}

function closeMe() {
    clearTimeout(closetimer);
    closeWindow();
}