
var m_MsgError = true;//当前发送消息是否成功（true，false）
var m_CusWechatName = "";

//msg: 消息内容, type：null 为聊天框消息，//1：历史消息
function MakeNewMsgHtml(msg, type) {
	var strContent = "";
	var strMsgBody = "";
	var strMsgCreatime = "";
	if (msg.createtime != null && msg.createtime != undefined) {
		var strdiff = parseInt((Date.parse(m_strNowDay) - Date.parse(msg.createtime.substring(0, 10))));
		strMsgCreatime = strdiff != 0 ? msg.createtime.replace("T", " ") : msg.createtime.substring(11, 16);
	}
	//历史好友消息与聊天对话框好有消息区分
	var talkmsgid = "";
	if (type == null) {
		talkmsgid = "divMsg" + msg.msgid;
	} else {
		talkmsgid = "divHisMsg" + msg.msgid;
	}

	//消息类型过滤
	if (msg.msgtype == "1") {
		if (msg.content.indexOf("/js/LREditor/Expression/") != -1) {
			//表情
			strMsgBody = msg.content;
		} else {
			//文本消息单独div
			var FontSize = "";
			if (type == null) {
				if (m_FontSize == "1") {
					FontSize = "talkdetailedduihua-m-xl";
				} else if (m_FontSize == "2") {
					FontSize = "talkdetailedduihua-m-xxl";
				}
			}
			strMsgBody = "<div class=\"MsgRigth " + FontSize + "\" id=\"MsgRight" + msg.msgid + "\">" + msg.content + "</div>";
		}
	}
	else if (msg.msgtype == "3" || msg.msgtype == "47") {
		if (msg.content.length == 0) {
			strMsgBody = "【微信表情】";
		} else {
			var strRandom = "";
			if (msg.msgsource != "0") {
				strRandom = "?t=" + talkObj.getguid();
			}
			var dowmload = "<div class=\"img-hover\"><a href=\"#\" class=\"pull-right\" style=\"color:#666; cursor:Pointer\"> <i class=\"icon iconfont icon-download\"  onclick=\"DowmImg('" + msg.uin + "','" + msg.msgid + "','" + msg.filename + "','" + msg.createtime + "');\"></i> </a></div>";
			//文件下载
			if (msg.msgtype == "47") {
				//收藏表情不可查看大图不可下载
				strMsgBody = "<img id=\"msgimg" + msg.msgid + "\" src=\"" + msg.content + strRandom + "\" style=\"width:100px;\"><i id=\"loadimg" + msg.msgid + "\" class=\"icon iconfont icon-jiazair imgloading fa-pulse fa-3x fa-fw\" style=\"display:none;\"></i><div class=\"imgzhezhao\" id=\"msgzhezhao" + msg.msgid + "\" style=\"display:none\"></div>";
			} else {
				//对话框还是历史记录框
				var strLoad = type != null ? "His" : "Now";

				strMsgBody = "<img id=\"msgimg" + msg.msgid + "\" src=\"" + msg.content + strRandom + "\" style=\"width:100px;\" onclick=\"DownMsgImg('" + msg.uin + "','" + msg.msgid + "','" + msg.filename + "','" + msg.createtime + "','" + strLoad + "');\"/><i id=\"loadimg" + strLoad + msg.msgid + "\" class=\"icon iconfont icon-jiazai imgloading fa-pulse fa-3x fa-fw\" style=\"display:none;\"></i><div class=\"imgzhezhao\" id=\"msgzhezhao" + strLoad + msg.msgid + "\" style=\"display:none\"></div>" + dowmload;
			}
		}
	}
	else if (msg.msgtype == "34") {
		//语音消息
		if (msg.msgsource == "0") {
			var VoiceIsRead = "";
			if (msg.issoundplay != null) {
				VoiceIsRead = msg.issoundplay ? "" : "<i style=\"border-radius:8px; background:#ec0000; width:8px; height:8px; display:inline-block; position:absolute; top:0px; right:-25px;\" id=\"Message" + msg.msgid + "\"></i>";
			}
			strMsgBody = "<button class=\"speech\" style=\"cursor：Pointer;\" onclick=\"StartPlayVoice('" + msg.uin + "','" + msg.msgid + "','" + msg.content + "', 0 );\" ></button>" + VoiceIsRead + "<span style=\"position:absolute; right:-30px; top:14px; font-size:12px; color:#999;\">"+msg.para+"''</span>";
		} else {
			strMsgBody = "<button class=\"speech speech01\" style=\"cursor：Pointer;\" onclick=\"StartPlayVoice('" + msg.uin + "','" + msg.msgid + "','" + msg.content + "', 0 );\" ></button><span style=\"position:absolute; left:-25px; top:14px; font-size:12px; color:#999;\">" + msg.para + "''</span>";
		}
	}
	else if (msg.msgtype == "10000") {
		if (msg.content.indexOf("开启了朋友验证") > 0 && msg.content.indexOf("请先发送朋友验证请求") && msg.content.indexOf("才能聊天")) {
			strContent = "<br /><div class=\"talktip\">【您不是对方的好友，请先添加好友】</div>";
		} else
			if (msg.content.indexOf("查看异常") > 0 && msg.content.indexOf("我要投诉") > 0) {
				strContent = "<br /><div class=\"talktip\">【与对方发生资金往来可能存在风险.请注意核实身份】</div>";
			} else {
				strContent = "<br /><div class=\"talktip\">【" + msg.content + "】</div>";
			}
		return strContent;
	}
	else if (msg.msgtype == "999") {
		//消息撤回(其他客服聊天过程中撤销)
		if ($("#" + talkmsgid + "").length > 1) {
			$("#" + talkmsgid + "").removeClass("conversation").addClass("talktip");
			$("#" + talkmsgid + "").html("【你撤回了一条消息】");
		} else {
			//手机端撤回
			if (msg.msgsource == "0") {
				//好友撤回的消息
				strContent = "<div id=\"" + talkmsgid + "\" class=\"talktip\">" + msg.content + "</div><div class=\"clearfix\"></div>";
			} else {
				//客服撤回的消息
				strContent = "<div id=\"" + talkmsgid + "\" class=\"talktip\">【你撤回了一条消息】</div><div class=\"clearfix\"></div>";
			}
			return strContent;
		}
	} else if (msg.msgtype == "49") {
		//文件
		var dowmload = "";
		var filenameshow = "";
		dowmload = "<a href=\"#\"  class=\"pull-right\" style=\"color:#666; cursor：Pointer\"  onclick=\"Dowmfile('" + msg.content + "' ,'" + msg.createtime + "');\"><i class=\"icon iconfont icon-download\"></i></a>";
		filenameshow = msg.filename.length > 40 ? msg.filename.substring(0, 40) + "..." : msg.filename;
		strMsgBody = "<div style=\"line-height:40px; padding:10px; background:#fff; overflow:hidden; border:1px solid #ddd; \"><span class=\"pull-left\" style=\"display:block;width:115px;line-height: 20px; color:#999\" >" + filenameshow + "</span><div class=\"pull-right talk-file\"><i class=\"icon iconfont icon-file\" style=\"font-size:20px; color:#fff;\"></i></div></div><div  style=\"padding:0 10px; background:#fff; overflow:hidden; border:1px solid #ddd; border-top:0 none;\">" + dowmload + "</div>";
	} else if (msg.msgtype == "50") {
		//大文件
		filenameshow = msg.filename.length > 40 ? msg.filename.substring(0, 40) + "..." : msg.filename;
		var CancleSengBigfile = "";
		if (msg.para != "100.00") {
			CancleSengBigfile = "<i class=\"glyphicon glyphicon-remove-circle\" style=\"color:#ff0000;\" onclick=\"DeleteBigfileSend('" + msg.msgid + "')\" id=\"SendingBigFile" + msg.msgid + "\"></i>";
		} else {
			CancleSengBigfile = "<i class=\"glyphicon glyphicon-ok-circle\" style=\"color:#09bb07;\"></i>";
		}
		strMsgBody = "<div style=\"line-height:40px; padding:10px; background:#fff; overflow:hidden; border:1px solid #ddd; \"><span class=\"pull-left\"  style=\"display:block;width:140px;\" >" + filenameshow + "</span><div class=\"pull-right talk-file\"><i class=\"icon iconfont icon-file\" style=\"font-size:20px; color:#fff;line-height: 20px;\"></i></div></div><div  style=\"padding:0 10px; background:#fff; overflow:hidden; border:1px solid #ddd; border-top:0 none;\"><div  class=\"msg-file\"><div class=\"msg-file-bg\" id=\"BigFile" + msg.msgid + "\" style=\"width:" + msg.para + "%\"></div></div>" + CancleSengBigfile + "</div>";
	} else if (msg.msgtype == "11") {
		//地图
		if (type != null) {
			strMsgBody = "<div  style=\"width:100%;height:200px;border:#ccc solid 1px;\" id=\"dituHisContent" + msg.msgid + "\"></div>";
		} else {
			strMsgBody = "<div  style=\"width:100%;height:200px;border:#ccc solid 1px;\" id=\"dituContent" + msg.msgid + "\"></div>";
		}

	} else if (msg.msgtype == "42") {
		//名片
		strMsgBody = GetCarteHtml(msg, type);
	} else if (msg.msgtype == "12") {
		//图文消息(分享文章)
		var strfilname = msg.filename;
		if (strfilname.indexOf("![CDATA[") != -1) {
    		strfilname = msg.filename.replace("![CDATA[", "");
		}
    	if (strfilname.indexOf("]]") != -1) {
    		strfilname = msg.filename.replace("]]", "");
		}
    	strMsgBody = "<div class=\"talk-link\" onclick=\"window.open('" + msg.para + "')\"; style=\"cursor：Pointer;\"><h2>" + msg.content + "</h2><div class=\"talk-link-text\"><p>" + strfilname + "</p></div></div>";
	} else if (msg.msgtype == "19") {
		//客服发红包可以设置金额（未设置红的的情况下）
		var strredpacage = type == null && Number(msg.para) < 0.01 ? "<p style=\"margin:3px 5px;\"><input placeholder=\"红包金额(0-200)\" maxlength=\"6\" type=\"text\" id=\"redpackage" + msg.msgid + "\" class=\"form-control\" style=\"width:140px; margin-right:4px; float:left; border-radius:2px; height:24px;\"><button class=\"btn btn-warning\" style=\"  height:24px; padding:2px 12px; border-radius:2px; \" onclick=\"SetRedPackage('" + msg.msgid + "','" + msg.uin + "')\">确定</button></p>" : "微信红包";
		var strpacagemonet = Number(msg.para) > 0 ? "<font style=\"font-size:16px;\">￥</font>" + msg.para + "   " : "";
		
		//红包
		strMsgBody = "<div class=\"talk-hongbao\"><div class=\"talk-hongbao-sign\"><img src=\"../img/hongbao.png\" width=\"40\"><div><h2>" + msg.content + "</h2><p>" + strpacagemonet + "请在手机查看</p></div><div class=\"clearfix\"></div></div><div class=\"talk-hongbao-text\">" + strredpacage + "</div></div>";
	} else if (msg.msgtype == "18") {
		//转账
		strMsgBody = "<div class=\"talk-hongbao\"><div class=\"talk-hongbao-sign\"><img src=\"../img/zhuanzhang.png\" width=\"40\"><div><h2>" + msg.content + "</h2><p>" + msg.para + "</p></div></div><div class=\"talk-hongbao-text\"><p>请在手机查看</p></div></div>";
	}
	if (msg.msgsource == "0") {
		//好友消息
		var friendmsgcopy = "";
		var strFiendRightlick = "";
		//好友文字消息可复制
		if (msg.msgtype == "1" && msg.content.indexOf("/js/LREditor/Expression/") == -1 && type == null) {
		    friendmsgcopy = "<i data-rel=\"popover\" data-trigger=\"hover\" data-placement=\"top\" data-content=\"复制\" class=\"icon iconfont icon-copy pull-left icon-talk1 icon-talk2\" onclick=\"CopyTextMsg('" + encodeURI(msg.content) + "')\"></i>";
		}
		var strShareMsg = "";
	    //右键分享
		if ((msg.msgtype == "1" || msg.msgtype == "11" || (msg.msgtype == "47" && msg.content.length != 0) || (msg.msgtype == "3" && msg.content.length != 0)) && type == null) {
		    strShareMsg = "<i data-rel=\"popover\" data-trigger=\"hover\" data-placement=\"top\" data-content=\"转发\" class=\"icon iconfont icon-transmit pull-left icon-talk1 icon-talk2\" onclick=\"MsgForwardFriend('" + msg.msgid + "','" + encodeURI(msg.content) + "','" + msg.msgtype + "','" + encodeURI(msg.filename) + "','" + msg.para + "')\"></i>";
		}

		//右键收藏,文件删除
		strFiendRightlick = FriendRightMenu(msg.msgtype, msg.msgid, msg.content, msg.msgsource, msg.uin, msg.para, encodeURI(msg.filename), msg.wxmsgid);

		strContent += "<div id=\"" + talkmsgid + "\" class=\"conversation\">"
                + "<div class=\"pull-left nickname-m\">"
                + "<span><img src=\"" + msg.friendheadimgurl + "\" width=\"34\" height=\"34\"></span>"
                + "</div>"
                + "<div class=\"pull-left talkshow-m\"><div class=\"talk-date\">" + strMsgCreatime + "</div><div class=\"talkdetailed-m talkdetailedduihua-m\">"
                + "<img src=\"../img/talksign.png\" class=\"talksign-m\">"
                + "<p>" + strMsgBody + "</p>"
                + "</div>" + friendmsgcopy + strFiendRightlick + strShareMsg + "</div>"
                + "<div class=\"clearfix\"></div>"
                + "</div>";
	} else {
		//客服消息
		strContent += "<div id=\"" + talkmsgid + "\" class=\"conversation\">"
            + "<div class=\"pull-right nickname-m\">"
            + "<span><img src=\"" + msg.wechatheadimgurl + "\" width=\"34\" height=\"34\"></span>"
            + "</div>"
            + "<div class=\"pull-right talkshow-m\" ><div class=\"talk-date\" style=\"text-align:right;\">" + strMsgCreatime + "</div><div class=\"talkdetailed-m  talkdetailedduihua-m talkdetailedduihua1-m pull-right\">"
            + "<p id=\"MsgRight" + msg.msgid + "\">" + strMsgBody + "</p>"
            + "<img src=\"../img/talksign2.png\" class=\"talksign-m\">"
            + "</div>"
		//正在发送的消息
		if (msg.iswait != null && msg.iswait != 'underfined' && msg.iswait == true) {
			strContent += "<i class=\"icon iconfont icon-jiazai fa-pulse fa-3x fa-fw pull-right sendsuccess icon-talk\" style=\"margin-right:10px;\"></i>"
		}
		//左键事件（复制，撤回，收藏，文件删除）
		if (type == null) {
			var strwxmsgid = msg.wxmsgid == null ? "" : msg.wxmsgid;
			strContent += ChangeClickMenu(msg.msgtype, strwxmsgid, msg.msgid, msg.createtime, encodeURI(msg.content), msg.uin, msg.para, encodeURI(msg.filename));
		}
	    //右键分享
		if ((msg.msgtype == "1" || msg.msgtype == "11" || (msg.msgtype == "47" && msg.content.length != 0)) && type == null) {//(msg.msgtype == "3" && msg.content.length != 0)
		    strContent += "<i data-rel=\"popover\" data-trigger=\"hover\"data-placement=\"top\" data-content=\"转发\" data-original-title title onclick=\"MsgForwardFriend('" + msg.msgid + "','" + encodeURI(msg.content) + "','" + msg.msgtype + "','" + encodeURI(msg.filename) + "','" + msg.para + "');\" class=\"icon iconfont icon-transmit pull-right icon-talk1 icon-talk2\" \"></i>";
		}
		//发送失败的消息
		if (msg.isok == "0") {
		    strContent += "<i class=\"icon iconfont icon-xiazaishibai pull-right\" id=\"ErrorSend" + msg.msgid + "\" style=\"font-size:18px; margin:6px 10px; color:#ff0000; cursor：Pointer;\" onclick=\"SendErrorMsg('" + msg.msgid + "','" + msg.msgtype + "')\"></i>";
		}
		//机器人自动回复
		if (msg.para == "1" && msg.msgtype == "1") {
		    strContent += "<i class=\"fa fa-android pull-right\" style=\"font-size:18px; margin:6px 10px;\"  ></i>";
		}
		strContent += "</div>"
		strContent += "</div><div class=\"clearfix\"></div>"
		strContent += "</div>";
	}
	return strContent;
}

//播放语音
function StartPlayVoice(uin, msgid, filepathh, type) {
    $("#Message"+msgid).remove();
    var strParaJson = $.toJSON({
        uin: uin,
        msgid: msgid,
        filename: filepathh,
        type:type
    });
    talkObj.startplayvoice(strParaJson);
}

//播放语音回调
function AsyncStartPlayVoiceResult(jsonResult) {
    if (jsonResult.success) {
    }
    else {
        ShowError("myPageAlert", "语音播放异常！");
    }
    if (jsonResult.type == "0") {
        var strParaJson = $.toJSON({
            msgid: jsonResult.msgid,
            pid: m_NowSelectPid
        });
        talkObj.setonemessageisread(strParaJson);
    } else {
        var batchusername = $("#hidDocUserName");
        //群消息设为已读
          var strParaJson = $.toJSON({
              msgid: jsonResult.msgid,
              user: batchusername.val()
        });
        talkObj.setonemessagebatchisread(strParaJson);
    }
}

//播放发送语音
function StartPlaySendVoice(uin, filepathh) {
    var strParaJson = $.toJSON({
        uin: uin,
        filename: decodeURIComponent(filepathh)
    });
    talkObj.startplaysendvoice(strParaJson);
}
//播放发送语音回调
function AsyncStartPlaySendVoiceResult(jsonResult) {
}

//查看大图
function DownMsgImg(uin, msgid, filename, creattime, type) {
	if (filename == "sendmsgimg") {
		ShowMsg("myPageAlert", "转发的消息不支持查看大图！");
		return;
	}
    //将原图片置为加载状态，并且不可再继续点击下载
    if ($("#msgimg" + msgid).length > 0) {
        //所点击放大图片加loading
    	$("#loadimg" + type + msgid).show();
    	$("#msgzhezhao" + type + msgid).show();
    }

    var strParaJson = $.toJSON({
        uin: uin,
        msgid: msgid,
        filename: filename,
        creattime: creattime,
        type: type

    });
    talkObj.downmsgimg(strParaJson);
}

//下载原图片回调方法
function AsyncDownMsgImgResult(jsonResult) {
	var strMsgId = jsonResult.result.msgid;
	var strtype = jsonResult.result.type;
	if (jsonResult.success) {
		if (strMsgId.length > 0) {
			//下载后的图片路径，显示放大效果
			//show_big_img(jsonResult.result.newurl);
			homeObj.showbigform(jsonResult.result.fileurl);
		}
	} else {
		ShowError("myPageAlert", "打开图片失败！" + jsonResult.error);
	}
    //所点击放大图片取消loading
    //$("#loadimg" + strMsgId).removeClass("icon iconfont icon-jiazai fa-pulse fa-3x fa-fw imgloading");
    $("#loadimg" + strtype + strMsgId).hide();
    $("#msgzhezhao" + strtype + strMsgId).hide();
}
//二维码放大
function QrCodeShow(url) {
    $("#BigMessageUrl").modal("show");
    $("#BigImg").attr('src', url);
}
//客服发送消息右键撤回
function MsgReghtClick(strwxmsgid, msgid, time) {
    var wekey = $("#hidDocWechatKey").val();
    var uname = $("#hidDocUserName").val();
    var strParaJson = $.toJSON({
        wechatkey: wekey,
        username: uname,
        wxmsgid: strwxmsgid,
        createtime: time,
        msgid: msgid

    });
    homeObj.sendmessagewithdraw(strParaJson);
}
//删除消息回调
function AsyncSendMessageWithdrawResult(jsonResult) {
    if (jsonResult.success) {
        $("#divMsg" + jsonResult.result.msgid + "").removeClass("conversation").addClass("talktip");
        $("#divMsg" + jsonResult.result.msgid + "").html("【你撤回了一条消息】");
    } else {
        if (jsonResult.error == 1) {
            ShowMsg("myPageAlert", "请稍后尝试撤回消息！");
        } else if (jsonResult.error == "time out") {
            ShowMsg("myPageAlert", "消息发送已超过两分钟！");
        } else {
            ShowError("myPageAlert", "消息撤回异常！" + jsonResult.error);
        }
    }
}

//重新发送失败消息
function SendErrorMsg(msgid, msgtype) {
    if (m_MsgError) {
        m_MsgError = false;
        if (msgid.length > 0) {
        	if ($("#divMsg" + msgid + "  .sendsuccess").length > 0) {
        		$("#divMsg" + msgid + " .sendsuccess").removeClass("icon iconfont icon-xiazaishibai pull-right").addClass("icon iconfont icon-jiazai fa-pulse fa-3x fa-fw pull-right");
        		$("#divMsg" + msgid + " .sendsuccess").attr("style", "font-size:18px; margin:6px 10px;");
        	}

        	if ($("#ErrorSend" + msgid).length > 0) {
        		$("#ErrorSend" + msgid).removeClass("icon iconfont icon-xiazaishibai pull-right").addClass("icon iconfont icon-jiazai fa-pulse fa-3x fa-fw pull-right");
        		$("#ErrorSend" + msgid).attr("style", "font-size:18px; margin:6px 10px;");
        	}
            var strParaJson = $.toJSON({
                msgid: msgid,
                msgtype: msgtype
            });
            talkObj.senderrormsg(strParaJson);
        } else {
            return;
        }
    }
}
//重新发送失败消息回调
function AsyncSendErrorMsgResult(jsonResult) {
    if (jsonResult.success) {
    } else {
    	if ($("#divMsg" + jsonResult.joresult.msgid + "  .sendsuccess").length > 0) {
    		$("#divMsg" + jsonResult.joresult.msgid + "  .sendsuccess").removeClass("icon iconfont icon-jiazai fa-pulse fa-3x fa-fw pull-right").addClass("icon iconfont icon-xiazaishibai pull-right");
    		$("#divMsg" + jsonResult.joresult.msgid + "  .sendsuccess").attr("style", "font-size:18px; margin:6px 10px;color:#ff0000;");
    	}
    	if ($("#ErrorSend" + jsonResult.joresult.msgid).length > 0) {
    		$("#ErrorSend" + jsonResult.joresult.msgid).removeClass("icon iconfont icon-jiazai fa-pulse fa-3x fa-fw pull-right").addClass("icon iconfont icon-xiazaishibai pull-right");
    		$("#ErrorSend" + jsonResult.joresult.msgid).attr("style", "font-size:18px; margin:6px 10px;color:#ff0000;");
    	}
		
      
		
        if (jsonResult.error == "无法重新发送该消息！") {
            ShowMsg("myPageAlert", jsonResult.error);
        } else {
            ShowError("myPageAlert", "重新发送消息失败！" + jsonResult.error);
        }
    }
    m_MsgError = true;
}
///文件下载
function Dowmfile(fileurl, creattime) {
    var strParaJson = $.toJSON({
        fileurl: fileurl,
        creattime: creattime
    });
    talkObj.dowmfile(strParaJson);
}
//文件下载回调
function AsyncDowmfileResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "下载成功！");
    } else {
        if (jsonResult.error == "只允许下载24小时之内的文件！") {
            ShowMsg("myPageAlert", jsonResult.error);
        } else if (jsonResult.error == "文件下载失败！") {
            ShowMsg("myPageAlert", jsonResult.error + "只支持下载本次登录接收的文件或未知原因！");
        } else {
            ShowError("myPageAlert", "下载失败！" + jsonResult.error);
        }
    }
}
//图片下载到本地（申请大图）
function DowmImg(uin, msgid, filename, creattime) {
    var strParaJson = $.toJSON({
        uin: uin,
        msgid: msgid,
        filename: filename,
        creattime: creattime
    });
    talkObj.downmsgimglocal(strParaJson);
}
//申请大图回调
function AsyncDownMsgImgLocalResult(jsonResult) {
    if (jsonResult.success) {
        //文件下载到本地
        Dowmfile(jsonResult.result.newurl, jsonResult.result.creattime);
    } else {
        ShowMsg("myPageAlert", "当前只支持下载本次登录后接收的图片！");
    }
}
//当前发送消息是否发送成功s
function AsyncPageSendResult(msgid, wxmsgids, isresult, msgtype) {
    $("#MsgRight" + msgid).attr("data-wxmsgid", wxmsgids);
    if (isresult == "True") {
        //发送成功清除消息加载中（转圈）
        $("#divMsg" + msgid + " .sendsuccess").remove();
        //重新绑定右键
        //$('.talkdetailedduihua1-m p').contextify(options);
        //$('.talkdetailedduihua1-m .MsgRigth').contextify(msgoptions);
        //$('.talkdetailedduihua-m .MsgRigth').contextify(msgfriendsoptions);
    } else {
    	//发清失败，清除发送中class，改为发送失败class
        $("#divMsg" + msgid + " .sendsuccess").removeClass("icon iconfont icon-jiazai fa-pulse fa-3x fa-fw pull-right").addClass("icon iconfont icon-xiazaishibai pull-right");
        $("#divMsg" + msgid + " .sendsuccess").attr("style", "font-size:18px; margin:6px 10px; color:#ff0000; cursor:Pointer;");
        $("#divMsg" + msgid + " .sendsuccess").attr("onclick", "SendErrorMsg('" + msgid + "','" + msgtype + "')");
    }

}
//语音消息设为已读回调
function AsyncSetOneMessageIsReadResult(jsonResult) {
}
//群语音消息设为已读回调
function AsyncSetOneMessageBatchIsReadResult(jsonResults) {
}
//聊天文本复制
function CopyTextMsg(content) {
    var strParaJson = $.toJSON({
        content: decodeURI(content.replace(/%3Cbr%3E|%3Cbr\/%3E/g, '\n'))
    });
    var resultjson = talkObj.copytextmsg(strParaJson);
  
  if (resultjson == true) {
       ShowMsg("myPageAlert", "复制成功！");
   } else {
       ShowError("myPageAlert", "复制失败！");
   }
}
//对话编辑框右键粘贴文字或者图片
function TalkPaste() {
    var resultpaste = $.trim(talkObj.pasteittext());
    if (resultpaste.length > 0 && resultpaste != "PasteText") {
        //向鼠标焦点位置添加复制内容
        insertHtmlAtCaret(resultpaste);
        //光标定位在最后
        keyAction();
    } else {
        //缓存中存在图片
        talkObj.pasteimgtext();
    }
};
//向鼠标焦点位置添加复制内容
function insertHtmlAtCaret(html) {
    if (window.getSelection) {
        if (Sel.getRangeAt && Sel.rangeCount) {
            Range.deleteContents();
            var el = document.createElement("Content");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            Range.insertNode(frag);
            if (lastNode) {
                Range = Range.cloneRange();
                Range.setStartAfter(lastNode);
                Range.collapse(true);
                Sel.removeAllRanges();
                Sel.addRange(Range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        document.selection.createRange().pasteHTML(html);
    }
}
//替换消息右键功能
function ChangeClickMenu(type, wxmsgid, msgid, creattime, msgcontent, uin, para, filename) {
	var msgtype = "";
        
	var strclickContent = "";
	if (type == "3") {
		msgtype = "2";
	} else if (type == "47") {
		msgtype = "1";
	} else if (type == "11") {
		msgtype = "3";
	} else if (type == "49") {
		msgtype = "4";
	}
    //消息撤回
	var chehui = "<i data-rel=\"popover\" data-trigger=\"hover\"data-placement=\"top\" data-content=\"撤回\" class=\"icon iconfont icon-recall  pull-right icon-talk1\" onclick=\"MsgReghtClick('" + wxmsgid + "','" + msgid + "','" + creattime + "')\"></i>";
    //消息复制
	var fuzhi = "<i data-rel=\"popover\" data-trigger=\"hover\"data-placement=\"top\" data-content=\"复制\" class=\"icon iconfont icon-copy pull-right icon-talk1 icon-talk2\" onclick=\"CopyTextMsg('" + msgcontent + "')\"></i>";
	//收藏
	var shoucang = "<i data-rel=\"popover\" data-trigger=\"hover\"data-placement=\"top\" data-content=\"收藏\" class=\"icon iconfont icon-collect pull-right icon-talk1 icon-talk2\" onclick=\"CollectionMsg('" + msgtype + "','" + wxmsgid + "','" + msgcontent + "','" + uin + "','" + para + "','" + filename + "','" + msgid + "')\"></i>";
    
    if (type == "1") {
    	//无wxmsgid之前无撤回
    	if (msgcontent.indexOf("/js/LREditor/Expression/") == -1) {
    		strclickContent = fuzhi;
    	}
    	if (wxmsgid.length > 1) {
    		strclickContent = chehui + strclickContent;
    	}
    } else if (type == "3" || type == "47") {
        //表情/图片
    	strclickContent = wxmsgid.length < 1 ? "" : chehui + shoucang;
    } else if (type == "49") {
        //文件
    	strclickContent = wxmsgid.length < 1 ? "" : chehui + shoucang;
    } else if (type == "34") {
        //语音
    	strclickContent = wxmsgid.length < 1 ? "" : chehui;
    } else if (type == "11") {
		//地图
    	strclickContent = wxmsgid.length < 1 ? "" : chehui + shoucang;
    }
	//文件删除
    if (wxmsgid.length > 1) {
    	if (type == "3" || type == "49") {
    		var delfilename = "";
    		if (type == "3") {
    			delfilename = msgcontent;
    		} else {
    			delfilename = filename
    		}
    		var delfile = "<i data-rel=\"popover\" data-trigger=\"hover\"data-placement=\"top\" data-content=\"删除\" class=\"icon iconfont icon-delete-hover pull-right icon-talk1 icon-talk2\" onclick=\"Delfile('" + uin + "','" + msgid + "','" + delfilename + "')\"></i>";
    		strclickContent += delfile;
    	}
    }
    return strclickContent; 
}

//好友发送消息替换右键（收藏）
 function FriendRightMenu(type, msgid, content, source, uin, para, filename, wxmsgid) {
	var strcontent = "";
	var msgtype = "";
	if (wxmsgid != null) {
		if (wxmsgid.length > 0) {
			if (type == "3") {
				msgtype = "2";
			} else if (type == "47") {
				msgtype = "1";
			} else if (type == "11") {
				msgtype = "3";
			} else if (type == "49") {
				msgtype = "4";
			}
			var shoucang = "<i class=\"icon iconfont icon-collect pull-left icon-talk1 icon-talk2\" onclick=\"CollectionMsg('" + msgtype + "','" + wxmsgid + "','" + content + "','" + uin + "','" + para + "','" + filename + "','" + msgid + "')\"></i>";
			if (source == "0") {
				if (wxmsgid.length > 0 && type == "3" || type == "47" || type == "11" || type == "49") {
					//图片,表情，地理位置
					strcontent = shoucang;
				}
			}
			if (type == "3" || type == "49") {
				var delfilename = "";
				if (type == "3") {
					delfilename = content;
				} else {
					delfilename = filename
				}
				var delfile = "<i class=\"icon iconfont icon-delete-hover pull-left icon-talk1 icon-talk2\" onclick=\"Delfile('" + uin + "','" + msgid + "','" + delfilename + "')\"></i>";
				strcontent += delfile;
			}

		}
	}
	
	return strcontent;
}
//名片Html
function GetCarteHtml(Cartemsgitem,type) {
	var strContent = "";
	var MsgContent = $.parseJSON(Cartemsgitem.content);
	var CarteSex = "";
	if (MsgContent.Sex == "1") {
		CarteSex = "男"
	} else if (MsgContent.Sex == "2") {
		CarteSex = "女"
	} else {
		CarteSex = "未知";
	}

	var AddPersonContent = "";
	var NowOrHis = "MsgRigth MsgRigthHis1";
	if (type == null && Cartemsgitem.msgsource == "0") {
		AddPersonContent = "<div class=\"form-group\"><input type=\"text\" class=\"form-control\" id=\"AddFriendMsg\" maxlength=\"10\">"
                   + "<button class=\"btn btn-success\" onclick=\"CarteAddFriend('" + MsgContent.UserName + "','" + MsgContent.Ticket + "')\">"
                   + "  添加"
                   + "</button></div>";
		NowOrHis = "MsgRigth MsgRigth1";
	}
	strContent = "<div class=\"" + NowOrHis + "\">"
                   + "<h2 class=\"visiting-cardtit\">个人名片</h2>"
                   + "<div class=\"visiting-card\">"
                   + "<img src=\"" + MsgContent.bigheadimgurl + "\" class=\"pull-left\" width=\"48\" onclick=\"CarteHeadShowBig('" + Cartemsgitem.msgid + "','" + MsgContent.bigheadimgurl + "','" + Cartemsgitem.uin + "')\" style=\"cursor:pointer\" />"
                   + "<div class=\"pull-left visiting-cardtext\"><h2><p>" + MsgContent.NickName + "</p><span style=\"color:#46b6ef; font-size:12px;\">(" + CarteSex + ")</span></h2>"
                   + "<p class=\"card-city\">" + MsgContent.City + "-" + MsgContent.Province + "</p></div>"
                   + "<div class=\"clearfix\"></div>"
                   + AddPersonContent
                   + " </div>"
                   + "</div>"
	return strContent;
}
//名片点击头像显示大图
function CarteHeadShowBig(msgid,bigheadurl,uin) {
    //homeObj.showbigform(bigheadurl);
    var json = $.toJSON({
        uin: uin,
        msgid: msgid,
        url: bigheadurl
    });
    talkObj.downpic(json);
}
function AsyncDownPicResult(jsonResult) {
    if(jsonResult.success){
        homeObj.showbigform(jsonResult.result.url)
    } else {
        ShowError("myPageAlert", "操作失败:" + jsonResult.error);
    }
}
//同步好友大头像
function imgfriendClickShowBig() {
    $("#iFriendImgHeadTurn").show();
    var wekey = $("#hidDocWechatKey");
    var objhidDocPid = $("#hidDocPid");
    if (wekey.val.length < 1 || objhidDocPid.val().len < 1) {
        return;
    }
    var strParaJson = $.toJSON({
        wechatkey: wekey.val(),
        pid: objhidDocPid.val()
       
    });
    talkObj.getfriendbigheadimg(strParaJson);
}
//同步好友大头像回调
function AsyncGetFriendBigHeadImgResult(jsonResult) {
    if (jsonResult.success) { 
        homeObj.showbigform(jsonResult.imgurl);
    }
    $("#iFriendImgHeadTurn").hide();
}
//大文件发送结果
function SyncPageSendBigFileResult(msgid, readcount) {
	if ($("#BigFile" + msgid).length > 0) {
		$("#BigFile" + msgid).css("width", readcount + "%");
	}
}
//发文件发送完成
function SyncPageSendBigFileResultOk(msgid) {
	if ($("#BigFile" + msgid).length > 0) {
		$("#BigFile" + msgid).css("width", "100%");
	}
	if ($("#SendingBigFile" + msgid).length > 0) {
		$("#SendingBigFile" + msgid).removeClass("glyphicon-remove-circle").addClass("glyphicon-ok-circle");
		$("#SendingBigFile" + msgid).css("color", "#09bb07");
		$("#SendingBigFile" + msgid).removeAttr("onclick");
	}
}
//删除正在发送的大文件（未发送完成的）
function DeleteBigfileSend(msgid) {
	var wekey = $("#hidDocWechatKey");
	var objhidDocPid = $("#hidDocPid");
	var strParaJson = $.toJSON({
		wechatkey: wekey.val(),
		pid: objhidDocPid.val(),
		msgid: msgid
	});
	talkObj.removebigmediamsg(strParaJson);

	if ($("#divMsg" + msgid).length > 0) {
		$("#divMsg" + msgid).remove();
	}
}
//发送文件消息失败
function SyncPageSendBigFileResultError(msgid) {
	ShowError("myPageAlert", "文件发送失败！");
}

//************************************导出对话聊天记录**********************************************************
//编辑器导出聊天记录选项Show
function ExportRecordShow() {
	$("#ulExportWechatSpecifyMenuShow").show();
}

//导出当前聊天记录（Html 客户端缓存）
function ExportChatRecordToHtml()
{
	var objhidDocPid = $("#hidDocPid");
	var objnickname = $("#spDocNickName");
	var wechatName = $("#wechatname");

	var strParaJson = $.toJSON({
		wechatkey: m_SelectWechatKey,
		pid: objhidDocPid.val(),
		cnickname: m_CusWechatName,
		fnickname: objnickname.html()
	});

	talkObj.exportnowchatrecordtohtml(strParaJson);
}
//导出当前聊天记录（Html）回调
function AsyncExportNowChatRecordToHtmlResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "导出成功！");
	} else {
		ShowError("myPageAlert", "导出异常！" + jsonResult.error);
	}
}
//导出聊天记录到剪贴板（客户端缓存）
function ExportChatRecordToClipper() {
    var objhidDocPid = $("#hidDocPid");
    var objnickname = $("#spDocNickName");
    var wechatName = $("#wechatname");
    var NickNameMark = $("#ulLoadAllWechats li.active a p").html();

    var strParaJson = $.toJSON({
        wechatkey: m_SelectWechatKey,
        pid: objhidDocPid.val(),
        cnickname: NickNameMark,
        fnickname: objnickname.html()
    });
    talkObj.exportnowchatrecordtoclipper(strParaJson);
}

function AsyncExportNowChatRecordToClipperResult(jsonResult) {
    if (jsonResult.success) {
        CopyTextMsg(encodeURI(jsonResult.result));
        ShowMsg("myPageAlert", "导出成功！");
    } else {
        ShowError("myPageAlert", "导出异常！" + jsonResult.error);
    }
}
//导出聊天记录到HTML（页面缓存）
function ExportHisMsgToHtml() {
    //var objhidDocUin = $("#hidDocUin");
    var objhidDocPid = $("#hidDocPid");
    var objhidDocPidval = "";
    if (objhidDocPid == null || typeof(objhidDocPid.val()) == "undefined") {
        objhidDocPidval = m_NowSelectPid; //历史记录模块的聊天记录
    } else {
        objhidDocPidval = objhidDocPid.val();//对话模块的聊天记录
    }
    var objnickname = $("#spDocNickName");

    var strParaJson = $.toJSON({
        pid: objhidDocPidval,
        hislist: m_HisMsgList,
        cnickname: m_CusWechatName,
        fnickname: objnickname.html(),
        nickname: objnickname.html(),
    });
    talkObj.exporthisrecordtohtml(strParaJson);
}

function AsyncExportHisRecordToHtmlResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "导出成功！");
	} else {
		ShowError("myPageAlert", "导出异常！" + jsonResult.error);
	}
}

	function AsyncExportHisRecordToHtmlResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "导出成功！");
	} else {
		ShowError("myPageAlert", "导出异常！" + jsonResult.error);
	}
}
	//导出聊天记录到剪贴板（客户端缓存）
function ExportHisMsgToClipper() {
		//var objhidDocUin = $("#hidDocUin");
    var objhidDocPid = $("#hidDocPid");
    var objhidDocPidval = "";
    if (objhidDocPid == null || typeof (objhidDocPid.val()) == "undefined") {
        objhidDocPidval = m_NowSelectPid; //历史记录模块的聊天记录
    } else {
        objhidDocPidval = objhidDocPid.val();//对话模块的聊天记录
	}
    var objnickname = $("#spDocNickName");

    var strWechatNickName = $("#hidDocWechatNickName").val();
    var strParaJson = $.toJSON({
    		pid: objhidDocPidval,
    		hislist: m_HisMsgList,
    		cnickname: m_CusWechatName,
    		fnickname: objnickname.html(),
    		nickname: objnickname.html(),
    });
    talkObj.exporthisrecordtoclipper(strParaJson);
}

function AsyncExportHisRecordToClipperResult(jsonResult) {
    if (jsonResult.success) {
        CopyTextMsg(encodeURI(jsonResult.result));
        ShowMsg("myPageAlert", "导出成功！");
    } else {
        ShowError("myPageAlert", "导出异常！" + jsonResult.error);
	}
}
	//导出当前聊天记录(客户端缓存)
	function ExportRecord() {
	var objhidDocPid = $("#hidDocPid");
	var objnickname = $("#spDocNickName");
	var wechatName = $("#wechatname");

	var strParaJson = $.toJSON({
			wechatkey: m_SelectWechatKey,
			pid: objhidDocPid.val(),
			cnickname: m_CusWechatName,
			fnickname: objnickname.html()
	});
	talkObj.exportnowrecord(strParaJson);

}
	//导出当前聊天记录回调
	function AsyncExportNowRecordResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "导出成功！");
	} else {
		ShowError("myPageAlert", "导出失败：" + jsonResult.error);
	}
}
	//导出历史记录（页面缓存）
function ErportHisMsg() {
	var objhidDocPid = $("#hidDocPid");
	var objhidDocPidval = "";
	if (objhidDocPid == null || typeof (objhidDocPid.val()) == "undefined") {
		objhidDocPidval = m_NowSelectPid; //历史记录模块的聊天记录
	} else {
		objhidDocPidval = objhidDocPid.val();//对话模块的聊天记录
	}
	var objnickname = $("#spDocNickName");

	var strParaJson = $.toJSON({
			pid: objhidDocPidval,
			hislist: m_HisMsgList,
			cnickname: m_CusWechatName,
			fnickname: objnickname.html(),
			nickname: objnickname.html()
	});
	talkObj.exporthisrecord(strParaJson);
}
	function AsyncExportHisRecordResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "导出成功！");
	} else {
		ShowError("myPageAlert", "导出失败：" + jsonResult.error);
	}
}

	//*********************************************************聊天记录导出End******************************************************


	//通过名片添加好友
function CarteAddFriend(carteuname, carteticket) {
	var ObjAddFriendMsg = $("#AddFriendMsg").val();//请求好友验证信息
	var strParaJson = $.toJSON({
			wechatkey: m_SelectWechatKey,
			username: carteuname,
			ticket: carteticket,
			content: ObjAddFriendMsg
	});
	talkObj.addnewfriend(strParaJson);
}
	//通过名片添加好友回调
function AsyncAddNewFriendResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "请求好友验证发送成功！");
	} else {
		ShowError("myPageAlert", "好友验证发送失败！" + jsonResult.error);
	}
	$("#AddFriendMsg").val("");
}

//设置红包金额
function SetRedPackage(msgid, uin) {
    //红金额
    var strpackagemoney = $.trim($("#redpackage" + msgid).val());
    //判断红包金额是否为空
    if (strpackagemoney == "") {
        ShowError("myPageAlert", "请输入红包金额!");
        $("#redpackage" + msgid).focus();
        return;
    }
    //判断是否为数字
    if (isNaN(Number(strpackagemoney))) {
        ShowError("myPageAlert", "红包金额只能为数字，请重新输入!");
        $("#redpackage" + msgid).focus();
        return;
    }
    //判断数字是否超出范围
    if (Number(strpackagemoney) > 200) {
        ShowError("myPageAlert", "红包金额不能超出200!");
        $("#redpackage" + msgid).focus();
        return;
    }
    //判断数字是否超小于等于0
    if (Number(strpackagemoney) <= 0) {
        ShowError("myPageAlert", "红包金额不能小于或等于0");
        $("#redpackage" + msgid).focus();
        return;
    }
    //判断小数点后面的位数
    if (strpackagemoney.indexOf(".") != -1) {
        var position = strpackagemoney.indexOf(".");
        if (Number(strpackagemoney).toString().substring(position + 1, strpackagemoney.length).length > 2) {
            ShowError("myPageAlert", "有效小数不允许超出两位!");
            $("#redpackage" + msgid).focus();
            return;
        }
    }
    var strParaJson = $.toJSON({
        money: Number(strpackagemoney).toString(),
        msgid: msgid,
        pid: m_NowSelectPid,
        uin: uin
    });
    talkObj.setredpackagemoney(strParaJson);
}

//设置红包金额回调
function AsyncSetRedPackageMoneyResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "操作成功!");
    } else {
        ShowError("myPageAlert", "操作失败!" + jsonResult.error);
    }
}

//聊天页面打开快捷回复本地路径
function OpenCustomQuick() {
    talkObj.opencustomquick();
}
//聊天页面快捷回复本地路径打开回调
function AsyncOpenCustomQuickResult(jsonResult) {
    if(!jsonResult.success){
        ShowError("myPageAlert", "操作失败!" + jsonResult.error);
    }
}