var Oparamter = "";
var NewEmailSeq = "";
var sourceSeq = "";
var sourcesrvSeq = "";
var sourceType = "";
var sourceFrom = "";
var brokersData;
var sendprocess;
var sendMailTimeState = "false"; //发送邮件计时是否启用
var g_content = ""; //回复的文本内容
var default_content = ""; //文本默认值
var g_sendlogtype = "";
var g_sendlogtxt = "";
var g_senders = [];
var g_gid = "";
var NeedLoadbrokers = true; //判断列表是否加载成功
var cachebrokers = null;
var cacheindex = 0;
var total_imgsize = 0;
var tgc; //黄金眼智能键盘对象
function hideDiv(div_id) {
    $("#" + div_id).hide();
    if (div_id == "dvWait") {
        $("#dvWait_bg").hide();
    }
}
//发送超时显示消息
function sendfail() {
    sendMailMessage("-2"); //发送失败（超时）
}
function getsenderinfostr() {
    var tmpresult = "<br\>-------------------------------<br\>";
    var senderinfo = loadCustomerBase("3", false);
    if (senderinfo == null) {

    } else {
        tmpresult += "客户姓名：" + senderinfo["info"].nm + "(帐号：" + senderinfo.id + ")" + "<br\>";
        if (senderinfo["info"].mobile == "") {
            tmpresult += "手机：无<br\>";
        } else {
            tmpresult += "手机：" + senderinfo["info"].mobile + "<br\>";
        }
        if (senderinfo["info"].mobile == "") {
            tmpresult += "固话：无<br\>";
        } else {
            tmpresult += "固话：" + senderinfo["info"].phone + "<br\>";
        }
    }
    return tmpresult;
}
function sendNormal() {
    var Action = "sender";
    var Senders = getSender();
    if (Senders == "") {
        alert("请选择客户经理");
        return;
    }
    if ($("#txtGoldCode").val() == "" || $("#txtGoldCode").val() == "请输入股票代码") {
        alert("请输入股票代码");
        return;
    }
    var tmpCodeName = ExistCode($("#txtGoldCode").val().substring(0, 2), $("#txtGoldCode").val().substring(2, 8));
    if (tmpCodeName == "-1") {
        alert("您输入的股票代码有误，请查看市场是否选择正确！");
        return;
    }

    var sTitle = "黄金眼短期权限的预约服务 代码 " + $("#txtGoldCode").val().substring(2, 8) + " " + tmpCodeName;
    if (sTitle == "") {
        alert("标题不能为空，请填写！");
        return;
    }
    var sMailbody = $("#msgcontent").val();
    if (sMailbody == "本处可以空白，也可以填写您的留言。如果您需要电话交流，请填写您的手机号码!") {
        sMailbody = "";
    }
    if (sMailbody.length > 500) {
        alert("邮件正文内容过多，请填写少于500个字符！");
        return;
    }
    sMailbody = sMailbody.replace(/\n/g, "<br />") + getsenderinfostr();
    CreateMailXML(Action, Senders.toLowerCase(), sTitle, sMailbody);
}

function CreateMailXML(Action, Senders, sTitle, sMailbody) {
    $.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_producttype = $($(xml).find("producttype")[0]);
            var nd_from = $($(xml).find("from")[0]);
            var nd_to = $($(xml).find("to")[0]);
            var extra = "";
            var rtn = "";           
            rtn = createTask(getAccountid(),"01008","").replace(/\r\n/g, ""); 
            if (rtn < 0) {
                alert("新增代办事项失败！");
                return;
            }
            nd_mail.attr("seq", NewEmailSeq);
            nd_mail.attr("timestamp", ql_date_yyyymmddhhss(new Date()));


            extra = "type=7";
            nd_type.attr("no", "7");
            $($(xml).find("goldcode")[0]).text($("#txtGoldCode").attr("mk") + "," + $("#txtGoldCode").val().substring(2, 8) + "|01008|短期黄金眼");
            nd_producttype.attr("no", "2");
            nd_producttype.text("01008|短期黄金眼");


            nd_from.text(getAccountid());
            var ofrom = loadCustomerBase("3", false);
            nd_from.attr("name", ofrom["info"].nm);
            if (Senders == "") {
                alert("请输入收件人！");
                //$('#txtTo').focus();
                return;
            }
            else {
                nd_to.text(Senders);
            }
            nd_to.attr("name", $("#txtSender").text());
            $($(xml).find("title")[0]).text(encodeString(sTitle));
            $($(xml).find("content")[0]).text("<![CDATA[" + sMailbody + "]]>"); 
            var smail = ql_xml_xmltostring(xml);
            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 == "0" || mySeq == "") {
                alert("意外失败！");
                return;
            }
            SetAttrib(mySeq + "\r\n65536");
            if (NewEmailSeq == mySeq) {
                if (sourceSeq != "" && sourceSeq != undefined) {
                    g_sendlogtype = "A3";
                    g_sendlogtxt = "," + sourceSeq + "," + sourceType + "," + sourceFrom;
                }
                else {
                    var tmpSenders = Senders.split(";");
                    g_sendlogtype = "A4";
                    g_sendlogtxt = "," + sourceSeq + "," + sourceType + "," + sourceFrom;
                    g_senders = tmpSenders;
                }
                if (NewEmailSeq == SendMail(NewEmailSeq)) {
                    sendprocess = setTimeout("sendfail()", 15000);
                    popupDiv("dvWait");
                }
                else {
                    popupDiv("dvWait");
                    sendMailMessage("-3"); //发送失败

                }
            }
            else {
                popupDiv("dvWait");
                sendMailMessage("-3"); //发送失败
            }
        }
    })
}









function getSender() {
    var sender = "";
    var yesno = -1;
    var text = $("#txtSender").text();
    if ($.trim(text) == "") {
        return sender;
    }
    if (brokersData.length > 0) {
        var textTmp = text.split(";");
        $.each(textTmp, function (i, txt) {
            var flag = false;
            for (var i = 0; i < brokersData.length; i++) {
                var broker = this.split(",");
                var id = brokersData[i].id;
                if (txt == brokersData[i].nm) {
                    yesno = sender.indexOf(id);
                    if (yesno < 0) {
                        sender += id + ";";
                    }
                    flag = true;
                    break;
                }
            }
            if (flag == false) {
                yesno = sender.indexOf(txt);
                if (yesno < 0) {
                    sender += txt + ";";
                }
            }
        });
        sender = sender.substring(0, sender.length - 1);
        return sender;
    }
    else {
        return text;
    }
}


//进度条
function popupDiv(div_id) {
    $("#" + div_id).css({
        position: "absolute",
        left: ($(window).width() - $("#" + div_id).outerWidth()) / 2,
        top: ($(window).height() - $("#" + div_id).outerHeight()) / 2
    });
    $("#" + div_id).show();
    if (div_id == "dvWait") {
        $("#dvWait_bg").show();
        sendMailMessage("1");
        setTimeout("showtime(1)", 1000);
    }
}

//发送邮件成功失败提示
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();
            if (g_sendlogtype == "A4") {
                $.each(g_senders, function (i, txt) {
                    write_log("A4", g_gid + "," + txt + ",0");
                });
            }
            else {
                write_log(g_sendlogtype, g_gid + g_sendlogtxt);
            }
            setTimeout("closeWindow()", 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;
    }
}
//邮件提示计时
function showtime(time) {
    if (sendMailTimeState == "true") {
        $("#dvWait_time").text(time);
        time = time + 1;
        setTimeout("showtime(" + time + ")", 1000);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////
/*
*首次加载
*/
function myload() {
    var p = new Poly9.URLParser((window.location.href).replace(/%26/g, "&"));
    clearMail();
    hideDiv('dvWait');
    showbrokerlist(); //加载经纪人列表
    Oparamter = p.getQuerystring().toLowerCase();
    var mkcode = p.getParameter("mkcode");
    if (mkcode != "") {
        $("#txtGoldCode").val(mkcode.substring(0, 8));
        $("#txtGoldCode").attr("mk", mkcode.substring(0, 2))
    }
    NewEmailSeq = NewMail();
    initpastesetting(1); //设置客户端邮件复制模拟ctr+v
    $("#goldattstock").focus();
    //建立实例，第一个参数是实例对象的名称，第二个是最多显示的数量 
    tgc = new mSift('tgc', 6); ;
    //指定文本框对象建立 
    tgc.Create("txtGoldCode");
}
function myunload() {
    initpastesetting(0); //设置客户端邮件复制不模拟ctr+v
    tgc = null;
}

/*
*数组排序
*/
function sortbrokers(tmpbrokersData) {
    for (var i = tmpbrokersData.length - 1; i >= 0; i--) {
        var tmpqp = "";
        var reString = GetOrderList(tmpbrokersData[i].nm);
        var tmp1 = reString.split("|");
        for (var jj = 0; jj < tmp1.length; jj++) {
            var tmp2 = tmp1[jj].split(",");
            tmpqp += padLeft(tmp2[1], 5);
        }
        tmpbrokersData[i].qp = tmpqp;
    }

    var l_brokersData = brokersData.sort(function (a, b) {
        if (a.qp > b.qp) {
            if (a.ol > b.ol) {
                return -1;
            } else if (a.ol < b.ol) {
                return 1;
            }
            return 1;
        }
        if (a.qp < b.qp) {
            if (a.ol > b.ol) {
                return -1;
            } else if (a.ol < b.ol) {
                return 1;
            }
            return -1;
        }
        return 0;
    })
    //	l_brokersData = brokersData.sort(function(a,b) {
    //		if(a.ol > b.ol) {
    //
    //			return -1;
    //		}else if(a.ol < b.ol) {
    //			return 1;
    //		}
    //		return 0;	
    //	})
    return l_brokersData;
}

//显示经纪人列表
function showbrokerlist() {
    var qsid = getSysUser()[2];
    var strBrokers = [];
    var strmanagers = [];
    var istrue = true;
    var managersonlinestate = "false";
    var brokersonlinestate = "false";
    brokersData = load_BrokerData("2");
    brokersData = sortbrokers(brokersData);
    if (brokersData.length > 0) {
        cachebrokers = brokersData;
        var m = 0, n = 0, mm = 0, nn = 0;
        for (var j = 0; j < cachebrokers.length; j++) {
            if (cachebrokers[j].role == 2) {
                m++;
            } else if (cachebrokers[j].role == 1) {
                n++;
            }
        }
        for (var i = 0; i < brokersData.length; i++) {
            var bimg = "img/pro_people_off.gif";
            if (brokersData[i].ol == 1) {
                bimg = "img/pro_people.gif";
            }
            istrue = false;
            if (cachebrokers[i].role == 2) {		//营销	
                if (mm % 2 == 0) {
                    strmanagers.push("		<tr style=\"background:#e8f3fd;\">");
                } else {
                    strmanagers.push("		<tr >");
                }
                strmanagers.push("			<td width=\"17%\">");
                if (mm == 0) {
                    strmanagers.push("<input  type=\"radio\" name=\"strmanagers\" onfocus=\"this.blur();\" checked=\"true\"  onclick=\"chgSender(this)\" username=\"");
                    $("#txtSender").text(cachebrokers[i].nm);
                    if (cachebrokers[i].ol == 1) {
                        managersonlinestate = "true";
                    } else {
                        managersonlinestate = "false";
                    }
                } else {
                    strmanagers.push("<input  type=\"radio\" name=\"strmanagers\" onfocus=\"this.blur();\" onclick=\"chgSender(this)\" username=\"");
                }
                strmanagers.push(cachebrokers[i].nm);
                strmanagers.push("\"  userid=\"");
                strmanagers.push(cachebrokers[i].id);
                strmanagers.push("\"></input>");
                strmanagers.push("	</td>");
                strmanagers.push("	<td width=\"19%\"><img src=\"" + bimg + "\" /></td>");
                strmanagers.push("	<td width=\"64%\"><font class=\"pro_name\">" + cachebrokers[i].nm + "</font></td>");
                strmanagers.push("	</tr>");
                mm++;
            } else if (cachebrokers[i].role == 1) {//投顾
                if (nn % 2 == 0) {
                    strBrokers.push("	<tr style=\"background:#e8f3fd;\">");
                } else {
                    strBrokers.push("	<tr >");
                }
                strBrokers.push("	<td width=\"17%\">");
                if (m > 0) {
                    strBrokers.push("  <input  type=\"radio\"  onclick=\"return false;\" name=\"strBrokers\" onfocus=\"this.blur();\" username=\"");
                } else {
                    if (nn == 0) {
                        strBrokers.push("  <input  type=\"radio\" checked=\"true\"  onclick=\"chgSender(this)\" name=\"strBrokers\" onfocus=\"this.blur();\" username=\"");
                        $("#txtSender").text(cachebrokers[i].nm);
                        if (cachebrokers[i].ol == 1) {
                            brokersonlinestate = "true";
                        } else {
                            brokersonlinestate = "false";
                        }
                    } else {
                        strBrokers.push("  <input  type=\"radio\"  onclick=\"chgSender(this)\" name=\"strBrokers\" onfocus=\"this.blur();\" username=\"");
                    }
                }
                strBrokers.push(cachebrokers[i].nm);
                strBrokers.push("\"  userid=\">");
                strBrokers.push(cachebrokers[i].id);
                strBrokers.push("\"></input> ");
                strBrokers.push("	</td>");
                strBrokers.push("	<td width=\"19%\"><img src=\"" + bimg + "\" /></td>");
                if (m > 0) {
                    strBrokers.push("	<td width=\"64%\"><font class=\"pro_name_gray\">" + cachebrokers[i].nm + "</font></td>");
                } else {
                    strBrokers.push("	<td width=\"64%\"><font class=\"pro_name\">" + cachebrokers[i].nm + "</font></td>");
                }
                strBrokers.push("	</tr>");
                nn++;
            }
        }
        if (m > 0) {
            $("#managerslist").html(strmanagers.join(""));
            if (managersonlinestate == "false") {
                $("#hint").html("提示：您的客户经理不在线，可能无法及时回复您！");
            }
        } else {
            $("#managerslist").html("<tr ><td >当前无关联服务人员</td></tr>");
            $("#hint").html("提示：未找到您的客户经理，请选择其他服务人员!");
        }
        if (n > 0) {
            $("#brokerlist").html(strBrokers.join(""));
        } else {
            $("#brokerlist").html("<tr ><td >当前无关联服务人员</td></tr>");
        }

        if (cacheindex < cachebrokers.length) {
            NeedLoadbrokers = true;
            $(".mail_broker_item").each(function (i, div) {
                if (i % 2 == 0) {
                    $(this).css("background", "#e8f3fd");
                }
                if (i == 0) {
                    $(this).find("img:eq(0)").attr("src", "img/ss_mail_icon4.gif");
                    $(div).find(".mail_broker_item_open").show();
                    $(div).height(201);
                }
            });
        }
        else {
            NeedLoadbrokers = false;
            $("#txtCheckAll").attr("style", "");

        }
    } else {
        $("#managerslist").html("<tr ><td >当前无关联服务人员</td></tr>");
        $("#hint").html("提示：游客或无服务者不能申请，请联系营业部解决！");
        $("#brokerlist").html("<tr ><td >当前无关联服务人员</td></tr>");
    }

}
//清空界面数据
function clearMail() {
    $("#txtSender").text("");
    $("#txtGoldCode").val("请输入股票代码");
    $("#msgcontent").attr("value", "本处可以空白，也可以填写您的留言。如果您需要电话交流，请填写您的手机号码!");
    $("#hint").text("");
    $("#managerslist").find("input").each(function () {
        this.checked = false;
    })
    $("#brokerlist").find("input").each(function () {
        this.checked = false;
    })
}
function chgSender(value) {
    var txtsenderid = "#txtSender";
    var sendername = $.trim($(txtsenderid).text()).split(";");
    var sname = $(value).attr("username");
    //	if (sendername != null)
    //	{
    //		if (value.checked)
    //		{
    //			if ($.inArray(sname,sendername) < 0)
    //			{
    //				sendername.push(sname);
    //			}
    //		}
    //		else
    //		{
    //			sendername = $.grep(sendername,function(val,key){			
    //			return val != sname;});			
    //		}
    //		sendername = $.grep(sendername,function(val,key){return val != "";});		
    //		$(txtsenderid).val(sendername.join(";"));
    //	}
    //	else
    //	{
    $(txtsenderid).text(sname);
    //	}
}