var m_BatchIsFirstLoad = true;
var m_BatchSelectPoint = "";
var m_BatchIsNoRead = "";
var m_NowSelectBatchWechatKey = "";
var m_NowSelectBatchKey = "";
var m_Owner = "";//当前人员在群里身份，1位群主，其他为普通成员
var m_BatchFriends = [];//群成员好友缓存

//新版
function BindBatchs() {
	var objtxtBatchQueryFriendsPoint = $("#txtBatchQueryFriendsPoint");

	//是否有未读消息
	var bIsChecked = false;
	if ($("#cbxQueryBatchNoRead").attr("class") == "serch-active") {
		bIsChecked = true;
	}
	//if ($("#cbxQueryBatchNoRead").prop("checked") == true) {
    //	bIsChecked = true;
    //}
    if (!m_BatchIsFirstLoad) {
    	if (bIsChecked == m_BatchIsNoRead && m_BatchSelectPoint == objtxtBatchQueryFriendsPoint.val()
            && m_IsChangeWechat == false) {
            return;
        }
    }
    var strParaJson = $.toJSON({
        wechatkey: m_SelectWechatKey,
        point: objtxtBatchQueryFriendsPoint.val(),
        isnoread: bIsChecked,
        pageindex: 0,
        pagesize: 100
    });
    talkObj.querybatchs(strParaJson);

    m_BatchSelectPoint = objtxtBatchQueryFriendsPoint.val();
    m_BatchIsNoRead = bIsChecked;
    m_BatchIsFirstLoad = false;
}

//筛选好友数据回调方法



function AsyncQueryBatchsResult(jsonResult) {
    if (jsonResult.success) {
        $("#ulBatchHeadList").empty();
        for (var i = 0; i < jsonResult.list.length; i++) {
        	var item = jsonResult.list[i];
        	//未读消息数量
        	var strNoReadHtml = "";
        	//未读消息数
        	var noreadcount = "";
        	if (m_NowSelectBatchKey != item.username && Number(item.noreadcount) > 0) {
        		noreadcount = item.noreadcount > 99 ? "..." : item.noreadcount;
        		strNoReadHtml = "<span class=\"talk-tips\" id=\"fontNRC" + item.headimgkey + "\">" + noreadcount + "</span>";
        	}
        	//选中样式
        	var strSelectHeadActive = "";
        	if (m_NowSelectBatchKey == item.username) {
        		strSelectHeadActive = "list-active";
        	}
        	
        	
        	var strmenu = "";
        	//群置顶
        	var strTopClass = item.order > 0 ? "top-active" : "";
			//置顶优先显示
        	var strTopClass = strTopClass.length > 0 ? strTopClass : strSelectHeadActive;

        	var strFdRightKey = SetBatchRigthKey(strTopClass, item.contactflag, item.wechatkey, item.username, item.remarkname);

        	
        	var strnknorkn = item.nickname.length > 0 || item.nickname != "0" ? item.nickname : "";
        	strnknorkn = strnknorkn.length > 0 ? strnknorkn : item.remarkname

        	var strSendError = "";
        	if (item.lastmsgcontent.indexOf("E1001发送失败！") != -1) {
        		item.lastmsgcontent = item.lastmsgcontent.replace("E1001发送失败！", "");
        		strSendError = "<span style=\"color:red;\">发送失败！</span>";
        	}

        	var strContent = "";
        	strContent += "<li id=\"liBatchHead" + item.headimgkey + "\" class=\"" + strTopClass + "\" onclick=\"SelectBatch('" + item.wechatkey + "','" + item.username + "','" + item.headimgkey + "');\">";
        	strContent += "<div class=\"group-header\">";
        	strContent += "<img src=\"" + item.headimgurl + "\"  onerror=\"nogroupfind();\" />";

        	strContent += "</div>";
        	strContent += "<div class=\"talk-mes\">";
        	strContent += "<span class=\"talk-name\" style=\"width:100px\">" + strnknorkn + "</span>";
        	strContent += "<span class=\"pull-right color-gry\">" + item.lastmsgsorttime + "</span>";
        	strContent += "<p class=\"pre-mess\">" + strSendError + item.lastmsgcontent + "</p>";
        	strContent += strNoReadHtml;

        	strContent += "</div>";
        	strContent += "<div class=\"hover-btn hover-group-btn\">";
        	strContent += "<dl>";
        	strContent += strFdRightKey;
        	strContent += " </dl>";
            strContent += "</div>";

        	strContent += "</li>";
        	$("#ulBatchHeadList").append(strContent);
        	$('#ulBatchHeadList i[data-rel=popover]').popover();
        }
    }
}

//选择群，绑定基本信息及消息列表
function SelectBatch(wechatkey, username, headimgkey) {
    $("#imgDocHead").attr("onclick", "BindGroup();");
    ClearNRC(username, wechatkey, headimgkey);
    //样式处理
    SetBatchShow();
    //当前选择的好友
    m_NowSelectBatchKey = username;
    m_NowSelectPid = headimgkey;
    m_NowSelectBatchWechatKey = wechatkey;
    m_IsBatch = true;

    var strParaJson = $.toJSON({
        wechatkey: wechatkey,
        username: username
    });
    talkObj.getbatchsdoc(strParaJson);

    var objNoReadCountTag = $("#fontNRC" + headimgkey);
    if (objNoReadCountTag.length > 0) {
        objNoReadCountTag.remove();
    }
    $("#ulBatchHeadList .list-active").removeClass("list-active");
    var objSelectHeadLi = $("#liBatchHead" + headimgkey);
    if (objSelectHeadLi.length > 0) {
    	objSelectHeadLi.addClass("list-active");
    }
    m_EditorControl.setFocusIn();
}

//获取群信息回执
function AsyncGetBatchsDocResult(jsonResult) {
    if (jsonResult.success) {
        $("#divWelcome").hide();
        var fInfo = jsonResult.info;
        m_Owner = fInfo.isowner;//判断当前微信是否为该群群主
        $("#hidDocWechatKey").val(fInfo.wechatkey);
        $("#hidDocUserName").val(fInfo.username);
        $("#hidDocPid").val(fInfo.headimgkey);
        $("#spDocWechatPidMark").val(fInfo.wechatnickname);
        $("#hidDocUin").val(fInfo.uin);

        //基本资料
        $("#imgDocHead").attr("src", fInfo.headimgurl);
        $("#TalkingfrdName").html(fInfo.nickname);
        $("#TalkingfrdRemarkName").hide();
        
        //追加消息
        AppendBatchMsg(jsonResult.msgs);
        $("#NoSelFdZheZhao").css("display", "none");
    }
}

//未读消息处理
function ClearNRC(name, wechatkey, headimgkey) {
    if ($("#fontNRC" + headimgkey + "").parents("#liBatchHead" + headimgkey + "").length > 0) {
        //设置好友消息为已读状态
        var strParaJson = $.toJSON({
            wechatkey: wechatkey,
            uname: name
        });
        talkObj.sendgroupmsgread(strParaJson);
    }
}
//未读消息处理回调
function AsyncSendGroupMsgReadResult(jsonResult){
    if (jsonResult.success) {
    }
}

//【已发送】向下插一条消息(群聊)
function AppendBatchMsg(msgList) {
    for (var i = 0; i < msgList.length; i++) {
        if ($("#divMsg" + msgList[i].msgid).length > 0) {
            $("#divMsg" + msgList[i].msgid).remove();
        }
        $("#divTalkContent").append(MakeNewBatchMsgHtml(msgList[i]));
        if (msgList[i].msgtype == "11") {
        	initbaidumap(msgList[i], "width:260px;height:200px;", "Now");
        }
        //tick reset min value
        if (Number(msgList[i].tick) < m_MinTick) {
            m_MinTick = Number(msgList[i].tick);
        }
    }
    document.getElementById("divTalkContentOutside").scrollTop = document.getElementById("divTalkContentOutside").scrollHeight;
    $("#divTalkContent i[data-rel=popover]").popover();
}

//【发送中】向下插一条消息
function AsyncSendBatchMsgResult(jsonResult) {
	if (jsonResult.success) {
		if ($("#divMsg" + jsonResult.msg.msgid).length > 0) {
			$("#divMsg" + jsonResult.msg.msgid).html(MakeNewBatchMsgHtml(jsonResult.msg));
		} else {
			$("#divTalkContent").append(MakeNewBatchMsgHtml(jsonResult.msg));
		}
		document.getElementById("divTalkContentOutside").scrollTop = document.getElementById("divTalkContentOutside").scrollHeight;
	}else {
		ShowError("myPageAlert",jsonResult.error);
	}
}
//群聊
function MakeNewBatchMsgHtml(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);
    }
    //消息类型过滤
    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 = "";
            //文件下载
            var filenameshow = "";
            //if (msg.msgsource == "0") {
            	dowmload = "<a href=\"#\"  class=\"pull-right\" style=\"color:#666;cursor：Pointer\"  onclick=\"DowmImg('" + msg.uin + "','" + msg.msgid + "','" + msg.filename + "','" + msg.createtime + "');\"><i class=\"icon iconfont icon-download \"></i></a>";
            //}
            filenameshow = msg.filename.length > 40 ? msg.filename.substring(0, 40) + "..." : msg.filename;
            if (msg.msgtype == "47") {
				//收藏表情不可查看大图，不可下载
            	strMsgBody = "<img id=\"msgimg" + msg.msgid + "\" src=\"" + msg.content + strRandom + "\" style=\"width:100px;\"><i id=\"loadimg" + msg.msgid + "\" class=\"fa fa-spinner imgloading fa-pulse fa-3x fa-fw\" style=\"display:none;\"></i><div class=\"imgzhezhao\" id=\"msgzhezhao" + msg.msgid + "\" style=\"display:none\"></div>";
            } else {
            	strMsgBody = "<img id=\"msgimg" + msg.msgid + "\" src=\"" + msg.content + strRandom + "\" style=\"width:100px;\" onclick=\"DownMsgImg('" + msg.uin + "','" + msg.msgid + "','" + filenameshow + "','" + msg.createtime + "');\"/><i id=\"loadimg" + msg.msgid + "\" class=\"fa fa-spinner imgloading fa-pulse fa-3x fa-fw\" style=\"display:none;\"></i><div class=\"imgzhezhao\" id=\"msgzhezhao" + 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 + "', 1 );\" ></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 + "', 1 );\" ></button><span style=\"position:absolute; left:-25px; top:14px; font-size:12px; color:#999;\">" + msg.para + "''</span>";
        }
    }
    else if (msg.msgtype == "10000") {
        strContent = "<br /><div class=\"talktip\">【" + msg.content + "】</div>";
        return strContent;
    }
    else if (msg.msgtype == "999") {
        //消息撤回(其他客服聊天过程中撤销)
        if ($("#divMsg" + msg.msgid + "").length > 1) {
            $("#divMsg" + msg.msgid + "").removeClass("conversation").addClass("talktip");
            $("#divMsg" + msg.msgid + "").html("【你撤回了一条消息】");
        } else {
            //手机端撤回
            if (msg.msgsource == "0") {
                //好友撤回的消息
                strContent = "<div id=\"divMsg" + msg.msgid + "\" class=\"talktip\">" + msg.content + "</div><div class=\"clearfix\"></div>";
            } else {
                //客服撤回的消息
                strContent = "<div id=\"divMsg" + msg.msgid + "\" class=\"talktip\">【你撤回了一条消息】</div><div class=\"clearfix\"></div>";
            }
            return strContent;
        }
    } else if (msg.msgtype == "49") {
    	var dowmload = "";
    	//发送文件可下载

    	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; width:210px; \"><span class=\"pull-left\" style=\"display:block;width:140px;line-height: 20px;\" >" + 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=\"line-height:20px; padding:10px; background:#fff; overflow:hidden; border:1px solid #ddd; border-top:0 none; width:210px;\">" + dowmload + "</div>";
    } else if (msg.msgtype == "50") {
    	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>";
    	}
    	//大文件
    	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; width:210px; \"><span class=\"pull-left\" >" + 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=\"line-height:20px; padding:10px; background:#fff; overflow:hidden; border:1px solid #ddd; border-top:0 none; width:210px;\"><div class=\"msg-file\" ><div class=\"msg-file-bg\" id=\"BigFile" + msg.msgid + "\"></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);
    } 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><img src=\"../img/bigtouxiang.png\" class=\"pull-left\"/><div class=\"talk-link-text\"><p>" + strfilname + "</p></div></div>";

    } else if (msg.msgtype == "19") {
    	//红包
    	strMsgBody = "<div class=\"talk-hongbao\"><div class=\"talk-hongbao-sign\"><img src=\"../img/hongbao.png\" width=\"40\"><div><h2>" + msg.content + "</h2><p>请在手机查看</p></div></div><div class=\"talk-hongbao-text\"><p>微信红包</p></div></div>";
    }
    if (msg.msgsource == "0") {
        var Batchfriendmsgcopy = "";
        var strFiendRightlick = "";
        //好友文字消息可复制
        if (msg.msgtype == "1" && msg.content.indexOf("/js/LREditor/Expression/") == -1 && type == null) {
            Batchfriendmsgcopy = "<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)) {
            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=\"ShareMsgToBatch('" + 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);
        //群成员昵称
        var nickname = msg.nickname.length > 0 ? msg.nickname : "";
        strContent += "<div id=\"divMsg" + msg.msgid + "\" class=\"conversation\">"
                + "<div class=\"pull-left nickname-m\">"
                + "<span style=\"cursor:pointer;\" onclick=\"Detailed('" + nickname + "' ,'" + msg.friendheadimgurl + "' , '" + msg.username + "');\"><img src=\"../img/user.png\" width=\"34\" height=\"34\"></span>"
                + "</div>"
                + "<div style=\"float:left; width:90%;\"><font style=\"font-size:10px; color:#999; float:left; margin-left:10px;\">" + nickname + "&nbsp;" + strMsgCreatime + "</font><div class=\"clearfix\"></div><div class=\"talkdetailed-m talkdetailedduihua-m\">"
                + "<img src=\"../img/talksign.png\" class=\"talksign-m\">"
                + "<p>" + strMsgBody + "</p>"
                + "</div>" + Batchfriendmsgcopy + strFiendRightlick + strShareMsg + "</div>"
                + "<div class=\"clearfix\"></div>"
                + "</div>";
    } else {
        //客服消息
        strContent += "<div id=\"divMsg" + msg.msgid + "\" class=\"conversation\">"
            + "<div class=\"pull-right nickname-m\">"
            + "<span><img src=\"" + msg.wechatheadimgurl + "\" width=\"34\" height=\"34\"></span>"
            + "</div>"
            + "<div style=\"float:right; width:90%;\"><font style=\"font-size:10px; color:#999; float:right; margin-right:12px;\">" + "" + strMsgCreatime + "</font><div class=\"clearfix\"></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=\"fa fa-spinner fa-pulse fa-3x fa-fw pull-right sendsuccess\" style=\"width:15px;height:15px; font-size:14px; margin-top:8px;\"  ></i>"
        }
    	//左键事件（复制，撤回，收藏）
        if (type == null) {
        	strContent += ChangeClickMenu(msg.msgtype, msg.wxmsgid, 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)) {//(msg.msgtype == "3" && msg.content.length != 0)这个是图片的情况
            strContent += "<i  data-rel=\"popover\" data-trigger=\"hover\" data-placement=\"top\" data-content=\"转发\" class=\"icon iconfont icon-transmit pull-right icon-talk1 icon-talk2\" onclick=\"ShareMsgToBatch('" + msg.msgid + "','" + encodeURI(msg.content) + "','" + msg.msgtype + "','" + encodeURI(msg.filename) + "','" + msg.para + "')\"></i>";
        }
        //发送失败的消息
        if (msg.isok == "0") {
            strContent += "<i class=\"icon iconfont icon-xiazaishibai pull-right\" id=\"ErrorSend" + msg.msgid + "\" style=\"width:15px;height:15px; font-size:17px; margin-top:8px; 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=\"width:15px;height:15px; font-size:14px; margin-top:8px;\"  ></i>";
        }
        strContent += "</div>"
        strContent += "<div class=\"clearfix\"></div></div>"
        strContent += "</div>";
    }
    return strContent;
}
//右键群置顶
function SetGroupTop(topnum, wechatkey, username, remarkname) {
	event.cancelBubble = true;//禁止触发父级div事件
    var strParaJson = $.toJSON({
        wechatkey: wechatkey,
        username: username,
        type: topnum,
        remarkname: remarkname
    });
    talkObj.setgrouptop(strParaJson);
}
//群消息置顶回调
function AsyncSetGroupTopResult(jsonResult) {
    if (jsonResult.success) {
        var objselectBatchQueryFriendsWechats = $("#selectBatchQueryFriendsWechats");
        var objtxtBatchQueryFriendsPoint = $("#txtBatchQueryFriendsPoint");

        //是否仅未读消息
        var bIsChecked = false;
        if ($("#cbxBatchQueryFriendsNoRead").prop("checked") == true) {
            bIsChecked = true;
        }
        BindBatchs();
    } else {
        ShowError("myPageAlert", "群置顶失败！");
    }
}
//群消息免打扰
function SetBatchRemain(wechatkey, type, username, remarkname) {
	event.cancelBubble = true;//禁止触发父级div事件
    var strParaJson = $.toJSON({
        wechatkey: wechatkey,
        type: type,
        username: username,
        remarkname: remarkname
    });
    talkObj.setbatchremain(strParaJson);
}
//好友置顶回调
function AsyncSetBatchRemainReadResult(jsonResult) {
    
}

// ************************************************群操作（添加删除成员）************************************************
var m_Img;//全局存图片
var m_Name;//全局存name
var m_Number = 1;//用于判断是否应该显示删除按钮，显示1，不显示0
var m_Username = [];//添加好友时,得到选中好友的username缓存
var m_Friend = [];//得到该微信全部好友缓存，用于筛选
//群好友显示
function BindGroup() {
    $(".loading").show();
    $(".loadingcover").show();
    var group = $.toJSON({
        username: m_NowSelectBatchKey,
    });
    talkObj.getbatchallfriend(group);
}

//群好友显示回调
function AsyncGetBatchAllFriendResult(jsonResult) {

    if (jsonResult.success) {
        m_BatchFriends = jsonResult.list;
        $("#BatchFriendsText").val("");
        BatchFriends();
        
    } else {
        ShowError("myPageAlert", "获取群成员失败:" + jsonResult.error);
    }
    $(".loading").hide();
    $(".loadingcover").hide();
    $("#groupfriend").modal("show");//显示模态层
}

//群成员好友遍历（支持昵称备注检索）
function BatchFriends() { 
    var strCount = "";
    //strCount += "<li style=\"cursor:pointer\" onclick =\"AddFriend();\">";
    //strCount += "<img src=\"../img/add.png\"/>"
    //strCount += "<p>添加</p>"
    //strCount += "</li>";
    //if (m_Owner == "1") {
    //    strCount += "<li style=\"cursor:pointer\" onclick =\"DeleteFriend();\">";
    //    strCount += "<img src=\"../img/minus.png\"/>";
    //    strCount += "<p>移除</p>";
    //    strCount += "</li>";
    //}
    var BatchFriendsText = $.trim($("#BatchFriendsText").val());
    for (i in m_BatchFriends) {
        if (m_BatchFriends[i].nickname.indexOf(BatchFriendsText) != -1) {
            var straddress = m_BatchFriends[i].city == "" ? m_BatchFriends[i].province : m_BatchFriends[i].province + "-" + m_BatchFriends[i].city;
            strCount += "<li style=\"cursor:pointer; width:80px;height:85px\" onclick = \"Detailed('" + m_BatchFriends[i].nickname + "' ,'" + m_BatchFriends[i].headimgurl + "' , '" + m_BatchFriends[i].usernmane + "');\">";
            strCount += "<img src=\"../img/kefutouxiang.png\" />";
            strCount += "<p>" + m_BatchFriends[i].nickname + "</p>";
            if (m_BatchFriends[i].nickname != $("#spDocWechatPidMark").val()) {
                strCount += "<span style=\"display:none\" class=\"ShowDelBatchFriend glyphicon glyphicon-minus-sign color-red\" onclick=\"KickOutGroup('" + m_BatchFriends[i].usernmane + "',event);\"></span>";
            }
            strCount += "</li>";
        }
    }
    $("#groupmembers").html(strCount);
}
//单击好友显示详细信息
function Detailed(name, headimgurl, username) {
    $("#GroupMemberszhezhao").show();
    $("#GroupMembersTurn").show();
    var strFriendInformation = name.length > 10 ? name.substring(0, 9) + "..." : name;
    $("#friendname").html(strFriendInformation);
    m_Img = headimgurl;
    m_Name = name;
    var json = $.toJSON({
        uin: $("#hidDocUin").val(),
        username: username,
        bathusername: $("#hidDocUserName").val()
    });
    talkObj.downloadonewechatgroupfriendhead(json);
}

//好友详细信息下载图片回调
function AsyncDownLoadOneWechatGroupFriendHeadResult(jsonResult) {
    $("#detailedInformation").modal("show");
    var strcontent = "";
    strcontent += "<div class=\"wechat-header-box text-center\">";
    strcontent += "<img onerror=\"nofind()\" src=" + m_Img + " />";
    strcontent += "</div>";
    strcontent += "<div class=\"wechat-mess-box\">";
    strcontent += "<div class=\"row\">";
    strcontent += "<div class=\"col-xs-4\">";
    strcontent += "<p class=\"p2 color-gry\">备注/昵称：</p>";
    strcontent += "<p class=\"p2 color-gry\">地区：</p>";
    strcontent += "</div>";
    strcontent += "<div class=\"col-xs-8\">";
    var strName = m_Name.length > 8 ? m_Name.substring(0, 7) + "..." : m_Name;
    strcontent += "<p class=\"p2\">" + strName + "</p>";
    var m_Address = jsonResult.result.city == "" ? jsonResult.result.province : jsonResult.result.province + "-" + jsonResult.result.city;
    strcontent += "<p class=\"p2\">" + m_Address + "</p>";
    strcontent += "</div>";
    strcontent += "</div>";
    strcontent += "</div>";

    ////if (m_Address != "") {
    //    strcontent += "<p>地区：" + m_Address + " </p>";
    ////}
    //strcontent += "</div>";
    $("#detailednessFriend").html(strcontent);

    $("#GroupMemberszhezhao").hide();
    $("#GroupMembersTurn").hide();
}

//添加按钮，得到该微信所有好友
function AddFriend() {
    $("#GroupMemberszhezhao").show();
    $("#GroupMembersTurn").show();
    $("#GroupFriendScreen").val("");
    m_Username = [];//点击加号拉去好友时，将好友username缓存清空
    var strGroupName = $("#TalkingfrdName").text().length > 10 ? $("#TalkingfrdName").text().substring(0, 9) + "..." : $("#spDocNickName").text();
    $("#flockname").html("请选择向【" + strGroupName + "】中添加的好友");
    $("#Selfriendflock").empty();
    var json = $.toJSON({
        username: $("#hidDocUserName").val(),
        wechatkey: $("#hidDocWechatKey").val()
    });
    talkObj.getonewechatinviteallfriends(json);
}

//添加按钮，得到该微信所有好友回调
function AsyncGetOneWechatInviteAllFriendsResult(jsonresult) {
    if (jsonresult.success) {
        m_Friend = jsonresult.list;//得到当前微信所有好友，并放入缓存中
        CommonTraverse("");//调用公共遍历方法
    } else {
        ShowError("myPageAlert", "未成功得到群好友:" + jsonresult.error);
    }
    $("#flockfriend").modal("show");
    $("#GroupMembersTurn").hide();
    $("#GroupMemberszhezhao").hide();
}
//向群中添加好友事件
function AddBatchFriend() {
    CommonTraverse($("#AddBatchFriend").val());
}
//当前微信好友公共遍历方法
function CommonTraverse(name) {
    var strselval = $.trim(name);
    //查询按钮
    var strcontent = "";
    for (var i = 0; i < m_Friend.length; i++) {
        if (m_Friend[i].remarkname.indexOf(strselval) != -1 || m_Friend[i].nickname.indexOf(strselval) != -1) {
            var strName = m_Friend[i].remarkname == "" ? m_Friend[i].nickname : m_Friend[i].remarkname + "(" + m_Friend[i].nickname + ")";
            var strnickoremarkname = strName.length > 19 ? strName.substring(0, 18) + ".." : strName;
            if (m_Friend[i].exist == "1") {
                strcontent += "<li id='Choice" + i + "' class=\"list-checked\" style=\"cursor:pointer\" onclick=\"Choice('" + m_Friend[i].username + "','" + i + "','" + strnickoremarkname + "','" + m_Friend[i].headimg + "')\">";
            } else {
                var stralrdeyselect = "";
                for (var j = 0; j < m_Username.length; j++) {
                    if (m_Username[j].username == m_Friend[i].username) {
                        stralrdeyselect = "list-checked";
                        break;
                    }
                }
                strcontent += "<li id='Choice" + i + "' class=" + stralrdeyselect + " style=\"cursor:pointer\" onclick=\"Choice('" + m_Friend[i].username + "','" + i + "','" + strnickoremarkname + "','" + encodeURI(m_Friend[i].headimg) + "')\">";
            }
            strcontent += "<img src=" + m_Friend[i].headimg + " />";
            strcontent += "<div class=\"invate-number\">" + strnickoremarkname + "</div></li>";
        }
    }
    $("#friendflock").html(strcontent);
}

//选中好友时得到username
function Choice(username, type, name, img) {
    if ($("#Choice" + type).attr("class") == "list-checked") {
        return;
    } else {
        $("#Choice" + type).attr("class", "list-checked");
        m_Username.push({ "username": username, "name": name, "img": img });
    }
    SelectFriendInvitationButh();
}
//邀请入群选中好友遍历
function SelectFriendInvitationButh() {
    var strcontent = "";
    for (var i = 0; i < m_Username.length; i++) {
        strcontent += "<li>";
        strcontent += "<img src=" + decodeURI(m_Username[i].img) + " />";
        strcontent += "<div class=\"invate-number\">" + m_Username[i].name + "</div>";
        strcontent += "<i onclick=\"DelSelFriend('" + m_Username[i].username + "')\" class=\"glyphicon glyphicon-remove-sign pull-right\" aria-hidden=\"true\"></i>";
        strcontent += "</li>";
    }
    $("#Selfriendflock").html(strcontent);
}
//删除选中邀请入群的好友
function DelSelFriend(username) {
    for (var i = 0; i < m_Username.length; i++) {
        if (m_Username[i].username == username) {
            m_Username.splice(i, 1);
        }
    }
    SelectFriendInvitationButh();
    CommonTraverse("");
}
//删除按钮显示隐藏
function DeleteFriend() {
    if (m_Number == 1) {
        $(".ShowDelBatchFriend").show();
        m_Number = 0;
    } else {
        $(".ShowDelBatchFriend").hide();
        m_Number = 1;
    }
}

//移出好友
function KickOutGroup(username, event) {
    $("#GroupMembersTurn").show();
    $("#GroupMemberszhezhao").show();
    event.stopPropagation();
    var json = $.toJSON({
        wechatkey: $("#hidDocWechatKey").val(),
        username: username,
        fromusername: m_NowSelectBatchKey
    });
    talkObj.delgruopmember(json);
}

//移出群成员回调
function AsyncDelGruopMemberResult(jsonResult) {
    if (jsonResult.success) {
        $("#flockfriend").modal("hide");
        BindGroup();//删除成功后重新加载群成员
        DeleteFriend();//重新将删除按钮显示出来
        ShowMsg("myPageAlert", "操作成功!");
    } else {
    	ShowError("myPageAlert", "操作失败:" + jsonResult.error);
    }
    $("#GroupMembersTurn").hide();
    $("#GroupMemberszhezhao").hide();
}
//邀请好友确认按钮
function InvitingFriends() {
    var friendusername = "";
    for (i in m_Username) {
        friendusername += m_Username[i].username + ","
    }
    if (friendusername == "") {
        ShowError("myPageAlert", "请选择好友！");
        return;
    }
    $("#SubmitFriendTurn").show();
    $("#SubmitFriend").show();
    friendusername = friendusername.substring(0, friendusername.length - 1);
    var json = $.toJSON({
        wechatkey: $("#hidDocWechatKey").val(),
        username: friendusername,
        fromusername: m_NowSelectBatchKey
    });
    talkObj.invitefriendtogroup(json);
}
//邀请好友入群回调
function AsyncInviteFriendToGroupResult(josnResult) {
    if (josnResult.success) {
        $("#flockfriend").modal("hide");
        //BindGroup();
        ShowMsg("myPageAlert", "操作成功!");
    } else {
        ShowError("myPageAlert", "操作失败:" + josnResult.error);
    }
    $("#SubmitFriendTurn").hide();
    $("#SubmitFriend").hide();
}

//添加好友时按条件筛选
function ConditionScreen() {
    var active = $("#FriendForwardFriendLi").attr("class");
    if (active == "active" || active == "class active") {
        AllFriendCommon($("#FriendScreen").val());
    } else {
        CommonBatch($.trim($("#FriendScreen").val()));//调用公共遍历方法
    }
}


//***************************************************************转发群消息**************************************************************
var m_AllBach = [];//当前微信所有的群（除当前转发的消息所在的群）
var m_BachUserName = [];//群username 唯一标识
//分享消息到其他群单击事件(拉取当前微信的所有群)
var m_BatchContent;//发送内容
var m_MsgType;//类型
var m_Para;//地图坐标
function ShareMsgToBatch(msgid, content, msgtype, filename, para) {//'" + msg.msgid + "','" + msg.content + "','" + msg.msgtype + "','" + encodeURI(msg.filename) + "'
    //是群发，设置按钮初始样式
    $("#FriendForwardFriendBtn").attr("class", "btn btn-default");
    $("#FriendForwardBatchBtn").attr("class", "btn btn-success");
    $("#ConfirmForwarding").attr("onclick", "ConfirmForward()");
    $("#ForwardTitle").text("转发消息到群");
    m_Para = para;
    m_BachUserName = [];
    m_Usernames = [];
    m_BatchContent = decodeURI(content);
    m_MsgType = msgtype;

    var json = $.toJSON({
    	wechatkey: m_NowSelectBatchWechatKey,
        batchusername: m_NowSelectBatchKey
    });
    talkObj.getonewechatallbatch(json);
}
function AsyncGetOneWechatAllBatchResult(jsonResult) {
    if (jsonResult.success) {
        m_AllBach = jsonResult.grouplist;
        CommonBatch("");
    } else {
        ShowError("myPageAlert", "操作失败:" + josnResult.error);
    }
    $("#MsgForward").hide(); 
    $("#MsgForwardMask").hide();
}

//向选中的群中添加username
function BatchSelect(username,num) {
    for (var i = 0; i < m_BachUserName.length; i++) {
        if (m_BachUserName[i] == username) {
        	m_BachUserName.splice(i, 1);
        	$("#batch" + num).removeClass("select");
            return;
        }
    }
    m_BachUserName.push(username);
    $("#batch" + num).addClass("select");
}

//公共遍历当前微信的群(检索群按钮单击事件)
function CommonBatch(name) {
    
	var contentFriend = "";
	for (var i = 0; i < m_AllBach.length; i++) {
	    if (m_AllBach[i].remarkname.indexOf(name) > -1 || m_AllBach[i].nickname.indexOf(name) > -1) {
			var SelectBatch = "";
			for (var j = 0 ; j < m_BachUserName.length; j++) {
				if (m_BachUserName[i] == m_AllBach[i].username) {
					SelectBatch = " select";
					break;
				}
			}
			//备注名不为空显示
			var strremark = m_AllBach[i].remarkname.length > 7 ? m_AllBach[i].remarkname.substring(0, 7) + "..." : m_AllBach[i].remarkname;
			var strcontent = m_AllBach[i].remarkname == "" ? m_AllBach[i].nickname : m_AllBach[i].nickname + "(" + strremark + ")";
			strcontent = strcontent.length > 20 ? strcontent.substring(0, 20) + ".." : strcontent;

			contentFriend += "<li class=\"col-md-4 " + SelectBatch + "\" onclick=\"BatchSelect('" + m_AllBach[i].username + "','" + i + "')\"  id=\"batch" + i + "\" >";
			contentFriend += "<div class=\"col-md-12 friends-card\">";
			contentFriend += "<img src=\"" + m_AllBach[i].headimgurl + "\" class=\"img-circle\" />";

			contentFriend += "<span class=\"transform-name\">" + strcontent + "</span>";
			contentFriend += "</div>";
			contentFriend += "</li>";
		}
	}
	$("#FriendForwardBatchLi").attr("class", "active");
	$("#FriendForwardFriendLi").attr("class", "class");
	$("#AllFriendsCurrent").html(contentFriend);
	$("#AllFriends").modal("show");
}

//确认转发
function ConfirmForward() {
    if (m_BachUserName.length == 0) {
        ShowMsg("myPageAlert", "请选择转发的群!");
        return;
    }
    var strUsername = "";
    for (var i = 0; i < m_BachUserName.length; i++) {
        strUsername += m_BachUserName[i] + ",";
    }
    strUsername = strUsername.substring(0, strUsername.length - 1);
    var strParaJson = $.toJSON({
        wechatkey: $("#hidDocWechatKey").val(),
        uin: $("#hidDocUin").val(),
        username: strUsername,
        pid: "",
        msgtype: m_MsgType,
        isbatch: true,
        content: m_BatchContent,
        para: m_Para,
        url: m_BatchContent
    });
    talkObj.batchorfriendturnsendmsg(strParaJson);
}
//群转发消息回调
function AsyncBatchOrFriendTurnSendMsgResult(jsonResult) {
    $("#AllFriends").modal("hide");
    if(!jsonResult.success){
        ShowError("myPageAlert", "操作失败:" + jsonResult.error);
    }
}