//var Oparamter = "";
//var sourceFrom = "";
//var sourceSeq = "";
//var sSeq = "";
//var srvseq = ""; //服务器源邮件编号
//var sName = ""; //发件人姓名
//var tsattr = ""; //收件箱还是发件箱
//var procuids = "";
//var Senders = ""; //当前发送邮件收件人
//var SendersNames = ""; //当前发送邮件收件人姓名
//var itab = "1"; // 当前邮件发送类型 
//var staskid = ""; //代办事项id
//var sproductid = ""; //产品id
//var maileids = ""; //邮件ids
var sendprocess; //公共邮件定时器
var NewEmailSeq = "";
var sourcesrvSeq = "";
var sourceType = "";
var sendMailTimeState = "false"; //发送邮件计时是否启用
var g_sendlogtype = "";
var g_sendlogtxt = "";
var g_senders = [];
var g_gid = "";
var tmpmk = "";
var tmpcode = "";
var tmpcodename = "";
var sproductname = ""; //产品名称
var Mdata; //邮件数组数据
var tmpMdata; //邮件数组数据
var tmpsendingNum = 0; //当前发送邮件索引
var tmpMailtoIds = ""; //  用户ids  权限验证用
var fromSenderId = ""; //发件人id
var fromSenderName = ""; //发件人姓名
var sendCG = 0; //发送邮件成功个数
var sendSB = 0; //发送邮件失败个数
var otherTaskIds = ""; //合并后多余的待办事项

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

//弹出发送邮件等待提示信息
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": //发送邮件成功
            sendCG = sendCG + 1;
            $("#sendCG").text(sendCG);
            var rtn = setRightShort(g_senders, "01008", g_gid,Mdata[tmpsendingNum]["sc"]).replace(/\r\n/g, "");
            rtn = updateTask(Mdata[tmpsendingNum]["taskId"], "1", "", "", "").replace(/\r\n/g, "");
            rtn = batchupdateTask_mail(Mdata[tmpsendingNum]["taskId"], g_gid).replace(/\r\n/g, "");
            if (g_sendlogtype == "A4") {
                write_log("A4", g_gid + "," + g_senders + ",4");
            } else {
                write_log(g_sendlogtype, g_gid + g_sendlogtxt);
            }
            Mdata[tmpsendingNum]["sendState"] = "1"; //邮件发送状态  0:失败 1:成功      
            tmpsendingNum = tmpsendingNum + 1;
            sendingMail();
            break;

        case "3": //邮件发送完成   
            var tmptaskids = "";
            //批量更新合并后多余的待办事项
            var rtn = batchupdateTask(otherTaskIds, "1", "", "", "").replace(/\r\n/g, "");
            sendMailTimeState = "false";
            //  alert("批量发送短期黄金眼已经完成，请手工刷新待办事项列表！");
            RefreshTask(); //待办事项页面刷新
            closetimer = setTimeout("closeMe()", 300);
            break;
        default: //发送邮件失败
            sendSB = sendSB + 1;
            $("#sendSB").text(sendSB);
            Mdata[tmpsendingNum]["sendState"] = "0"; //邮件发送状态  0 ：失败 1成功   
            tmpsendingNum = tmpsendingNum + 1;
            sendingMail();
            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;
    load_AllBrokerRight("2", false);
    if (tmpkey != undefined || tmpkey != "") {
        var tmpdata = client_data_load(tmpkey, "0");
        if (tmpdata != null) {
            odata = eval('(' + tmpdata.dValue + ')');
            ReadLoadData(odata);
        }
    }
    //  initpastesetting(1); //设置客户端邮件复制模拟ctr+v
}
function myunload() {
    //  initpastesetting(0); //设置客户端邮件复制不模拟ctr+v
}


//清空界面数据
function clearMail() {
    $("#txtSender").text("");
    $("#msgcontent").attr("value", "");
}
/*
*读取缓存信息
*
*{ "pid": "产品id", "pname": "产品名称", "info":[{"mid":"邮件编号","mfi":"发件人id","mfn":"发件人姓名","taskid":"待办事项编号","gmk":"市场","gcode":"代码","gname":"股票名称"},{"mid":"邮件编号","mfi":"发件人id","mfn":"发件人姓名","taskid":"待办事项编号","gmk":"市场","gcode":"代码","gname":"股票名称"}]}
*/
function ReadLoadData(odata) {
    sproductname = odata.pname; //产品名称
    if (sproductname == undefined) {
        sproductname = "******";
    }
    tmpMdata = odata.info; //邮件详情

    //初始化数据	
    Mdata = [];
    var tmpcusTitle = ";";
    var yesno = -1;
    tmpMailtoIds = "";
    for (var i = tmpMdata.length - 1; i >= 0; i--) {
        if (tmpMdata[i].mid != undefined && tmpMdata[i].mid != "") {
            var name = $.trim(tmpMdata[i].mfn + "(" + tmpMdata[i].gmk + tmpMdata[i].gcode + ")");
            yesno = tmpcusTitle.indexOf(name);
            if (yesno < 0) {
                tmpcusTitle += name + ";";
                tmpMailtoIds += tmpMdata[i].mfi + ",";
                getMailDetail(tmpMdata[i]);
            }
            else {
                otherTaskIds += tmpMdata[i].taskid + ";";
            }
        }
    }
    if (tmpcusTitle.length > 1 && tmpcusTitle.substring(tmpcusTitle.length - 1) == ";") {
        tmpcusTitle = tmpcusTitle.substring(1, tmpcusTitle.length - 1);
        tmpMailtoIds = tmpMailtoIds.substring(0, tmpMailtoIds.length - 1);
        otherTaskIds = otherTaskIds.substring(0, otherTaskIds.length - 1);
    }

    $("#txtSender").text(tmpcusTitle);
    $("#txtSender").attr("title", tmpcusTitle);
    $("#txttitle").text("您的" + sproductname + "已经处理，十分感谢！");
}

//解析单封邮件内容到数组中
function getMailDetail(cData) {
    var ctmpMdata = {};
    tmpmk = cData.gmk;
    tmpcode = cData.gcode;
    tmpcodename = cData.gname;

    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>";

    var sfrom = cData.mfi;
    var tmpsfromName = cData.mfn;
    var sfromName = sfrom;
    if (tmpsfromName != undefined && tmpsfromName != "") {
        sfromName = tmpsfromName;
    }

    var tmpstaskid = cData.taskid;
    if (tmpstaskid == undefined) {
        tmpstaskid = "";
    }

    ctmpMdata["mailSourceId"] = cData.mid; //原邮件服务器id
    ctmpMdata["mailSourceType"] = "7"; //原邮件类型
    ctmpMdata["mk"] = tmpmk; 		//股票市场
    ctmpMdata["code"] = tmpcode; 		//股票代码
    ctmpMdata["codename"] = tmpcodename; 	//股票名称
   	ctmpMdata["sc"] = tmpcodename + "(" + tmpmk + tmpcode + ")"; 	//产品中心用股票格式   浦发银行(SH600000) 
    ctmpMdata["mailTitle"] = "黄金眼主力数据赋权 代码：" + tmpcode + " " + tmpcodename; 	//邮件标题
    ctmpMdata["mailContentHtml"] = tmphtml; //邮件正文
    ctmpMdata["mailtoId"] = sfrom; 	//收件人id
    ctmpMdata["mailtoName"] = sfromName; //收件人name
    ctmpMdata["taskId"] = tmpstaskid; 	//待办事项id
    ctmpMdata["sendState"] = "0"; 	//邮件发送状态 0 ：失败 1成功   

    Mdata.push(ctmpMdata);
}

//关闭窗体写应用回执
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();
    }
}
/*
*批量发送短期黄金眼权限邮件
*/
function sendMoreNormal() {

    //校验邮件正文内容
    var sMailbody = $("#msgcontent").val();
    if (sMailbody.length > 500) {
        alert("邮件正文内容过多，请填写少于500个字符！"); //130
        return;
    }
    tmpsendingNum = 0;

    //短期权限扣点验证
    var tmpcids

    var crtn = checkRightShort(tmpMailtoIds, "01008").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;
    }

    fromSenderId = getAccountid(); //发件人id
    fromSenderName = G_broker["info"].nm; //发件人姓名
    popupDiv("dvWait");
    sendCG = 0;
    sendSB = 0;
    $("#sendCount").text(Mdata.length);
    $("#sendCG").text(sendCG);
    $("#sendSB").text(sendSB);
    sendingMail();


}
//具体发送邮件函数
function sendingMail() {
    if (tmpsendingNum > Mdata.length - 1) {
        sendMailMessage("3");
    } else {
        NewEmailSeq = NewMail();
        var sTitle = ""; //邮件标题	
        var sMailbody = ""; //邮件正文  
        var toSenders = Mdata[tmpsendingNum]["mailtoId"]
        var toSendersNames = Mdata[tmpsendingNum]["mailtoName"]
        tmpmk = Mdata[tmpsendingNum]["mk"];
        tmpcode = Mdata[tmpsendingNum]["code"];
        sTitle = Mdata[tmpsendingNum]["mailTitle"];
        sMailbody = $("#msgcontent").val();
        sMailbody = sMailbody.replace(/\n/g, "<br />") + Mdata[tmpsendingNum]["mailContentHtml"];
        sourcesrvSeq = Mdata[tmpsendingNum]["mailSourceId"];
        sourceType = Mdata[tmpsendingNum]["mailSourceType"];


        //邮件日志用
        // var tmpSenders = toSenders.split(";");
        g_senders = toSenders.toLowerCase();
        g_sendlogtype = "A3";
        g_sendlogtxt = "," + Mdata[tmpsendingNum]["mailSourceId"] + "," + Mdata[tmpsendingNum]["mailSourceType"] + "," + toSenders;

        CreateMailXML(toSenders.toLowerCase(), toSendersNames, sTitle, sMailbody, "01008")
    }
}

function CreateMailXML(toSenders, toSendersNames, sTitle, sMailbody, sprocuids) {
    $.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 (sprocuids != "") {
                nd_type.attr("subno", sprocuids);
            }
            if(sourceprodmodetype !=""){
           	 	nd_type.attr("prodtype", sourceprodmodetype);
            }
            	
            extra = "type=4&source=" + sourcesrvSeq + "&sourcetype=" + sourceType;
            nd_type.text(sourcesrvSeq + "," + sourceType);
            nd_type.attr("no", "4");
            $($(xml).find("goldcode")[0]).text(tmpmk + "," + tmpcode + "|01008|短期黄金眼");

            nd_from.text(fromSenderId);                             //发件人id
            nd_from.attr("name", fromSenderName);                   //发件人姓名
            nd_to.text(toSenders);                                  //收件人id
            nd_to.attr("name", toSendersNames);                     //收件人姓名

            $($(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>");
            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) {
                    sendMailMessage("-4"); //发送失败
                    return;
                }
            }
            mySeq = mySeqs[0];
            if (mySeq == "-1") {
                // popupDiv("dvWait");
                sendMailMessage("-4"); //发送失败                
                return;
            }
            if (mySeq == "0" || mySeq == "") {
                sendMailMessage("-3"); //发送失败              
                return;
            }
            SetAttrib(mySeq + "\r\n65536");
            if (NewEmailSeq == mySeq) {

                if (NewEmailSeq == SendMail(NewEmailSeq)) {
                }
                else {
                    sendMailMessage("-3"); //发送失败
                }
            }
            else {
                sendMailMessage("-3"); //发送失败
            }
        }
    })
}
function closeMe() {
    clearTimeout(closetimer);
    closeWindow();
}