"use strict";
var imServer = getParameter("imserver");
var groupid = getParameter("groupid");
var lvid = getParameter("lvid");
var tag = getParameter("tag");
var sign = getParameter("sign");
var editFlag = getParameter("edit");
var tolvid = getParameter("tolvid");
imServer = getImServer(imServer);
var creatorid, myuserid, ismember;
var noticeClient = false;
var groupOut = {};
var closeWindowHook = false; //关闭窗口hook
var initStatus = false;
var repName, closeInfonotice;
var groupMainid;
var setGroupinfo = [];
var entGroup = false;
//回车 
document.onkeydown = function(event) {
	//网页内按下回车触发
	var e = event || window.event || arguments.callee.caller.arguments[0];
	if(e && e.keyCode == 13) { // enter 键  要做的事情
		if($('li:first-child').hasClass('tab_on')) {
			if($('#editBut').is(':hidden')) {
				$(".keepBut").click();
			}
		}
		$(".PopupQueding").hide();
	}
	if((e.ctrlKey) && (e.keyCode == 65)) {
		e.returnValue = false;
	}
}
document.ondragstart = function() {
	return false;
};

$(document).ready(function() {
	if(!groupid) {
		return;
	}
	var params = {
		'lvid': lvid,
		'groupid': groupid,
		'sign': sign
	};
	$.getJSON(requestUrlMap['cloudGroupInfo']['url'], params, searchGroupCallBack);
});

//提交的云组资料的回调函数
function searchGroupCallBack(data) {
	$("#editBut,.loading-popup").hide();
	if(data.errorid != 0) {
		$("#groupmess").html("非法请求");
		return;
	}
	myuserid = data.myuserid;
	ismember = data.ismember;
	groupOut = data.groupinfo;
	groupOut.msgtype = data['msgtype'];
	var creatorInfo = data['creatorinfo'];
	creatorid = groupOut.creatorid;
	if(data.admininfos.length == 0) {
		$('#leadImgDiv i').hide();
	}
	if(groupOut.grouptype == 3) {
		entGroup = true;
		$('.titinvitation').hide();
	}
	repName = groupOut.cloudgroupname.replaceAll('&lt', '<').replaceAll('&gt', '>');
	$("#groupCall").val(repName);
	$("#gongGaoSpan").text(groupOut.noticedata ? groupOut.noticedata : '组长很懒，什么都没有留下');
	closeInfonotice = groupOut.noticedata;
	$("#gongGaoText").val(groupOut.noticedata);
	var creatorHeadUrl;
	if(!creatorInfo['headurl']) {
		creatorHeadUrl = creatorInfo['sex'] == 0 ? '../images/classic/HEAD-gg-48.png' : '../images/classic/HEAD-mm-48.png';
	} else {
		creatorHeadUrl = transferHeadSize(creatorInfo['headurl'], 48);
	}
	$("#creatorHeadImg").attr({
		"src": creatorHeadUrl,
		'creatId': creatorInfo.lvid,
		'title': creatorInfo.nickname
	});
	var defaultHeadUrl, params, resultS, headUrl, adminUrl = '';
	for(var i = 0; i < data.admininfos.length; i++) {
		setGroupinfo.push(data.admininfos[i].lvid);
		defaultHeadUrl = data.admininfos[i].sex == 0 ? '../images/classic/HEAD-gg-48.png' : '../images/classic/HEAD-mm-48.png';
		params = "{command:1016,params:{lvid:" + data.admininfos[i].lvid + ", size:48}}";
		resultS = $.parseJSON(sendCommand(params));
		if(resultS.errorid == 0) {
			headUrl = resultS['url'] || defaultHeadUrl;
		}
		adminUrl += '<img src="' + headUrl + '" title=' + data.admininfos[i].nickname + ' creatId=' + data.admininfos[i].lvid + '>';
		$('.Administrators').html(adminUrl);
	}
	$("#creatorName").text(creatorInfo['nickname']);
	$("#leadImgDiv img").click(function() {
		var toId = $(this).attr('creatId');
		sendCommand("{command:1003,params:{userid:" + creatorid + ",lvid:" + toId + "}}");
	});
	////////////////根据用户身份显示tab菜单//////////////////////
	$("#tabCart li").each(function(i, liObj) {
		if(ismember || i == 0) {
			$(liObj).show();
		} else {
			$(liObj).remove();
		}
	});
	for(var i = 0; i < setGroupinfo.length; i++) {
		if(lvid == setGroupinfo[i]) {
			$("#editBut").show();
			$("#addHover").show();
			break;
		} else {
			$("#editBut").hide();
			$("#addHover").show();
		}
	}
	if(myuserid == creatorid) {
		$("#editBut").show();
		$("#addHover").show();
	}
	if(noticeClient) {
		var params = "{command:1013, groupid:" + groupOut['groupid'] + "}";
		sendCommand(params);
	}
	if(1 == tag) { //用户列表
		$(".chengyuan-tit").click();
		if(editFlag) {
			$(".chengyuan-tit").click();
		}
	} else if(2 == tag) { //设置
		$(".set-tit").click();
	}
	setInterval(function() {
		var notince = $("#gongGaoText").val();
		var name = $("#groupCall").val();
		if(notince != groupOut.noticedata || name != groupOut.cloudgroupname) {
			$('.zindeximg').hide();
		} else {
			$('.zindeximg').show();
		}
	}, 100)
	initStatus = true;
}
//加云组
function addMyGroup() {
	var params = "{command:1005,params:{groupid:" + groupOut['groupid'] + ",myuserid:" + myuserid + "}}";
	var resultS = sendCommand(params);
}

//发起会话
function privateChat() {
	var params = "{command:3009,params:{groupid:" + groupid + "}}"
	var resultS = sendCommand(params);
}

//申请加入该组
function applyGroup() {
	var groupStr = jQuery.toJSON(groupOut);
	var params = "{command:1002,params:" + groupStr + "}";
	var resultS = sendCommand(params);
}
//组组身份验证
//0,不允许任何人加组
//1，允许任何人加组
//2，需要身份认证
function shenfen(obj) {
	groupOut.verifytype = obj.value;
	var params = {
		'lvid': lvid,
		'groupid': groupid,
		'rtype': obj.value,
		'sign': sign
	};
	$.getJSON(requestUrlMap['groupVerify']['url'], params, setGroupCallBack);
}

function setGroupCallBack(obj) {}

//设置消息接受模式
function message(obj) {
	groupOut.msgtype = obj.value;
	var params = {
		'lvid': lvid,
		'groupid': groupid,
		'msgtype': obj.value,
		'sign': sign
	};
	$.getJSON(requestUrlMap['groupUpdateMsgType']['url'], params, function(data) {
		var params = "{command:3008,params:{msgtype:" + obj.value + ",groupid:" + groupOut['groupid'] + "}}";
		sendCommand(params);
	});
}

//修改云组头像
function groupiconupdate() {
	if(creatorid == myuserid) {
		var params = "{command:9002,params:{headtype:2,lvid:" + lvid + ", groupid:" + groupid + "}}";
		sendCommand(params);
	}
}

$(function() {
	$(".groupNav li").click(function() {
		$(this).addClass("tab_on").removeClass("tab_off")
			.siblings().removeClass("tab_on").addClass("tab_off");
		$("#groupList b").hide().eq($(".groupNav li").index(this)).show();
	});
	/*******点击 "设置" 身份验证类型********/
	$("input:radio").each(function(i, radioObj) {
		$(radioObj).click(function() {
			$("input[name='" + radioObj.name + "']").parent().removeClass('checkradio');
			$(this).parent().addClass('checkradio');
		});
	});
	$('.groupCon2 li input').blur(function() {
		$(this).addClass('bordefult').removeClass('boractive');
	})
	$('.groupCon2 li input').focus(function() {
		$(this).addClass('boractive').removeClass('bordefult');
	})
	$('.groupCon2 textarea').blur(function() {
		$(this).addClass('bordefult').removeClass('boractive');
	})
	$('.groupCon2 textarea').focus(function() {
		$(this).addClass('boractive').removeClass('bordefult');
	})

	function updataEdit() {
		$(".ziliao-tit").click();
		$('#tabCart li.tab_off').hide();
		$('#tabCart li.tab_on').css('width', '86px');
		$('#tabCart li.tab_on .ziliao-tit').addClass('updataInfo').text('编辑资料');
		$(".editBut,#groupmessview,.groupMember").hide();
		$(".groupKeep,#groupMainCon").show();
	}

	//编辑资料
	$(".editBut").click(function() {
		updataEdit();
	});
	//关闭
	$(".closeBut").click(function() {
		closeModifyInfo();
	});
	//关闭 "X"弹窗
	$(".newlyClose").click(function() {
		$(".cancelBut").click();
	});
	//保存
	$(".keepBut").click(function() {
		var params = '{"command":9012,"params":{"lvid":' + lvid + '}}';
		var result = $.parseJSON(sendCommand(params));
		var notince = $("#gongGaoText").val();
		var name = $("#groupCall").val();
		if(name == '' || name.match(/^\s+$/g)) {
			var paramStr = "{title:'修改资料',cat:0,content:'群组昵称不能为空！'}";
			var params = "{command:9006,params:" + paramStr + "}";
			var resultS = sendCommand(params);
			return;
		}
		$("#groupMainCon,.groupKeep").hide();
		$(".editBut,#groupmessview").show();
		var keyUpval = $('#gongGaoText').val();
		$('#gongGaoSpan').text(keyUpval);
		var params = {
			'lvid': lvid,
			'groupid': groupid,
			'notice': notince,
			'groupname': name,
			'sign': sign
		};
		$.ajax({
			url: requestUrlMap['groupUpdate']['url'],
			type: "POST",
			dataType: "jsonp",
			jsonp: "callback",
			data: params,
			success: function(data) {
				if(data.errorid != 0) {
					//showAlert(data.errmsg);
					return;
				}
				if(closeWindowHook) {
					closeDialogWindow();
				}
				noticeClient = true;
				var params = {
					'lvid': lvid,
					'groupid': groupid,
					'sign': sign
				};
				$.getJSON(requestUrlMap['cloudGroupInfo']['url'], params, searchGroupCallBack);
			}
		});
		$('#tabCart li').show();
		$('#tabCart li').attr('style', '');
		$('#tabCart li:first-child div').removeClass('updataInfo').text('资料');
	});
	//点击设置标签
	$(".set-tit").click(function() {
		tag = 2;
		$('.chengyuan-tit').attr('onclick', 'chengper()');
		if($('#groupMainCon').is(':visible')) {
			$(".closeBut").click();
		}
		$(".groupSet").show();
		$("#groupKeep").hide();
		$("#msgtype" + groupOut.msgtype, "#verifytype" + groupOut.verifytype).attr("checked", 'checked');

		if(myuserid == creatorid || setGroupinfo.indexOf(lvid) != -1) {
			$("#verifytypeul li,#verifytypeul li .sex-radio").show();
			$(".groupSetSel input").each(function(i, obj) {
				$(obj).attr("disabled", false);
			});
		} else {
			$(".groupSetSel input").each(function(i, obj) {
				$(obj).attr("disabled", true);
			});
			var verifymsg = '', tab;
			switch(groupOut.verifytype) {
				case 0:
					verifymsg = "允许任何人加入该组";
					tab = 0;
					break;
				case 1:
					verifymsg = "需要身份验证才能加入该组";
					tab = 1;
					break;
				case 2:
					verifymsg = "不允许任何人加入该组";
					tab = 2;
					break;
				default:
					break;
			}
			$("#verifytypeul li").hide();
			$("#verifytypeul li").eq(tab).show().find('.sex-radio').hide();
		}
		if(ismember) {
			$("input[name=msgtype]").attr("disabled", false);
		}
		//////////////设定云组纳新策略/////////////
		$("input:radio").each(function(i, radioObj) {
			if(radioObj.name == 'verifytype') {
				if($(radioObj).val() == groupOut.verifytype) {
					$(radioObj).parent().addClass('checkradio');
				} else {
					$(radioObj).parent().removeClass('defuradio');
				}
			} else if(radioObj.name == 'msgtype') {
				if($(radioObj).val() == groupOut.msgtype) {
					$(radioObj).parent().addClass('checkradio');
				} else {
					$(radioObj).parent().removeClass('defuradio');
				}
			}
		});
	});
	//点击资料标签
	$(".ziliao-tit").click(function() {
		tag = 0;
		if($(this).text() == '编辑资料') {
			return;
		}
		if($('#groupMainCon').is(':visible')) {
			$('#groupMainCon').hide();
		}
		$(".announPopup").hide();
		$(".groupKeep").hide();
		$("#groupmessview").show();
		if(myuserid == creatorid) {
			$("#editBut").show();
			$("#addHover").show();
		}
		$('.chengyuan-tit').attr('onclick', 'chengper()')
	});
	/**
	 * 关闭提示信息框
	 */
	$("#alertnewlyClose").click(function() {
		$("#alertpopupSureBut").click();
	});

	$("#alertpopupSureBut").click(function() {
		$(".PopupQueding").hide();
		$(".announPopup").hide();
		$("#viewdiv").hide();
		$("#editdiv").show();
	});
});
//点击成员按钮   
function chengper() {
	tag = 1;
	if($('#groupMainCon').is(':visible')) {
		$(".closeBut").click();
	}
	$(".groupMember").show();
	$("#groupKeep").hide();
	if(myuserid == creatorid) {
		$("#editBut").show();
		$("#addHover").show();
	}
	$('.loading-popup').show();
	var params = {
		'lvid': lvid,
		'groupid': groupid,
		'sign': sign
	};
	$.getJSON(requestUrlMap['groupUserAndChatlist']['url'], params, searchGroupUserCallBack);
	if(tag == 1) {
		$('.chengyuan-tit').attr('onclick', 'return false;')
	}
}
/**
 * 标签切换时运行
 */
function labelChange() {
	if(myuserid == creatorid) {
		$("#editBut").show();
		$("#addHover").show();
	} else {
		$("#editBut").hide();
		$("#addHover").show();
	}
}

function offGroup(th, lvid, userid) {
	var params = {
		'lvid': lvid,
		'groupid': groupid,
		'lvids': userid,
		'sign': sign
	};
	var delUser = $('#card_' + userid).prev().text() + '(' + userid + ')';
	var paramStr = "{title:'提示',cat:3,content:'你确定将" + delUser + "从本组中删除吗？'}";
	var comparams = "{command:9006,params:" + paramStr + "}";
	var result = $.parseJSON(sendCommand(comparams));
	if(result['errorid'] == 1) {
		$.ajax({
			url: requestUrlMap['offGroup']['url'],
			dataType: "jsonp",
			type: "POST",
			data: params,
			success: function(data) {
				chengper();
			}
		});
		return;
	}
	if(result['errorid'] == 2) {
		return;
	}
}

function lookUserView(tolvid) {
	var params = "{command:1003,params:{lvid:" + tolvid + "}}";
	var resultS = sendCommand(params);
}

function updateNa(editLvid) {
	$('.groupMember input').hide();
	$('.updataGn').find('span').show();
	var userInfoTd = $('#card_' + editLvid);
	userInfoTd.parents('tr').addClass('active').siblings().removeClass('active');
	userInfoTd.find('span').hide();
	userInfoTd.find('input').show();
	$('.groupMember input').focus().select();
	$('.groupMember input').blur(function() {
		var testN = $(this).val().trim();
		if(testN == '-') {
			testN = '';
		}
		$('.groupMember input').hide();
		var sourceCardName = $(this).prev('span').text();
		if(sourceCardName == testN) {
			$(this).hide();
			$(this).prev('span').show();
			return;
		}
		$(this).prev('span').text(testN == '' ? '-' : testN).show();
		var params = {
			'lvid': lvid,
			'groupid': groupid,
			'tolvid': editLvid,
			'groupnickname': testN,
			'sign': sign
		};
		$.ajax({
			url: requestUrlMap['updataName']['url'],
			dataType: "jsonp",
			type: "POST",
			data: params,
			success: function(data) {
				$.getJSON(requestUrlMap['groupUserAndChatlist']['url'], params, searchGroupUserCallBack);
			}
		});
	})
}

//窗口关闭调用方法
function closeWindow() {
	if(!initStatus) {
		closeDialogWindow();
	} else if($('#editBut').is(':hidden')) {
		closeWindowHook = true;
		closeModifyInfo();
	} else {
		closeDialogWindow();
	}
}
/**
 * 修改云组信息关闭按钮动作
 */
function closeModifyInfo() {
	var notince = $("#gongGaoText").val();
	var name = $("#groupCall").val();
	if(notince != groupOut.noticedata || name != groupOut.cloudgroupname) {
		//弹出提示框
		var paramStr = "{title:'修改资料',cat:3,content:'您已经对资料进行了修改,是否保存？'}";
		var params = "{command:9006,params:" + paramStr + "}";
		var result = $.parseJSON(sendCommand(params));
		if(result['errorid'] == 1) {
			doUpdate();
			return;
		}
		if(result['errorid'] == 2) {
			unUpdate();
			return;
		}
	} else {
		$('#tabCart li').show();
		$('#tabCart li').attr('style', '');
		$('#tabCart li:first-child div').removeClass('updataInfo').text('资料');
		$('#groupmessview').show();
		$('#groupMainCon').hide();
		$('.editBut').show();
		$('#groupKeep').hide();
	}
	if(closeWindowHook) {
		closeDialogWindow();
	}
}
//点击 关闭弹窗 "是" 按钮，保存修改
function doUpdate() {
	$(".keepBut").click();
}
//点击 关闭弹窗 "否" 按钮，不保存修改
function unUpdate() {
	$('#groupMainCon').hide();
	if(tag == 1) {
		chengper();
	} else if(tag == 2) {
		$(".set-tit").click();
	}
	if(closeWindowHook) {
		closeDialogWindow();
	}
	var data0 = {
		'myuserid': myuserid,
		'groupinfo': groupOut,
		'msgtype': groupOut.msgtype,
		'errorid': 0,
		'ismember': ismember
	};
	$("#groupmessview").show();
	$('#editBut').show();
	$('#groupKeep').hide();
	$('#tabCart li').show();
	$('#groupCall').val(repName);
	$('#gongGaoText').val(closeInfonotice);
	$('#tabCart li').attr('style', '');
	$('#tabCart li:first-child div').removeClass('updataInfo').text('资料');
	searchGroupCallBack(data0);
}
//提交云组成员的回调函数
function searchGroupUserCallBack(result) {
	if(result.errorid != 0) {
		$("#userDataList").html("非法请求");
		return;
	}
	var userArr = result.data;
	if(userArr.length == 0) {
		$("#userDataList").html("没有成员");
		return;
	}
	$("#onlineuser").html(userArr.length + "/500");
	var html = "";
	var tdHt = '';
	var imgurl = '';
	var proType;
	for(var i = 0; i < userArr.length; i++) {
		if(userArr[i].lvid == lvid) {
			proType = userArr[i].role;
			break;
		}
	}
	//对用户进行排序
	userArr.sort(function(u1, u2) {
		var r1 = u1['role'];
		var r2 = u2['role'];
		if(r1 == 0) {
			r1 = 3;
		}
		if(r2 == 0) {
			r2 = 3;
		}
		return r1 - r2;
	});
	var userObj, userNa, params, resultS, shenfen, chatData, userNickname;
	for(var i = 0; i < userArr.length; i++) {
		userObj = userArr[i];
		userNa = userObj.groupnickname || '-';
		userNa = userNa.replaceAll('<', '&lt;').replaceAll('>', '&gt;');
		imgurl = userObj.sex == 0 ? '../images/classic/HEAD-gg-16.png' : '../images/classic/HEAD-mm-16.png';
		params = "{command:1016, params:{lvid:" + userArr[i].lvid + ", size:16}}";
		resultS = $.parseJSON(sendCommand(params)); //获取16*16头像
		if(resultS.errorid == 0) {
			imgurl = !resultS.url ? imgurl : resultS.url;
		}
		shenfen = creatorid == userArr[i].userid ? "管" : "";
		chatData = userObj.chatdatestr;
		if(chatData.length > 3) {
			chatData = chatData.replaceAll('-', '/');
		}
		userNickname = userObj.nickname.replaceAll('<', '&lt;').replaceAll('>', '&gt;');
		html += "<tr>";
		html += " <td>";
		switch(parseInt(userObj['role'])) {
			case 1: //创建人
				groupMainid = userObj.lvid;
				html += "<div class=\"groupCreat\"></div>";
				break;
			case 2: //管理员
				html += '<div class="groupT" onclick="cancelre(' + userArr[i].lvid + ')"></div>';
				break;
			default: //普通用户
				html += "<div></div>";
				break;
		}
		html += "</td>";
		html += "<td style='width:125px;'>";
		html += '<div class="groupHead">';
		html += "<img src='" + imgurl + "'>";
		html += "<div class=\"groupHead-Mask\">";
		html += "<img src=\"../images/GroupCY.png\"/>";
		html += "</div>";
		html += "</div>";
		html += "<span class=\"chengYNam\" title=" + userNickname + ">" + userNickname + "</span>";
		html += "</td>";
		html += '<td id="card_' + userObj.lvid + '" class="updataGn" style="width:100px;"><span>' + userNa + '</span> <input maxlength="20"' + (userObj.lvid == lvid ? ' class="showmy"' : '') + ' type ="text" value ="' + userNa + '"/></td>';
		html += "<td style='width:105px;'>" + (userObj.phone == '' ? '-' : userObj.phone) + "</td>";
		html += "<td  style='width:68px;' class='hoverIcon'>";
		if(proType == 1) {
			html += "<span class='shwodata'>" + chatData + "</span><span class='imgHo'><a title='修改群组名片' onclick='updateNa(" + userObj.lvid + ")' class='fri-update' href='###'></a><a title='查看资料' onclick='lookUserView(" + userObj.lvid + ")' href='###' class='fri-info'></a>";
			if(!entGroup && creatorid != userObj['userid']) {
				html += "<a href='###' title='从本群组中移除' onclick='offGroup(this," + lvid + "," + userObj.lvid + ")' class='fri-del'></a></span></span>";
			}
		} else if(proType == 2) {
			html += "<span class='shwodata'>" + chatData + "</span><span class='imgHo'><a title='修改群组名片' onclick='updateNa(" + userObj.lvid + ")' class='fri-update' href='###'></a><a title='查看资料' onclick='lookUserView(" + userObj.lvid + ")' href='###' class='fri-info'></a>";

		} else {
			html += "<span class='shwodata'>" + chatData + "</span><span class='imgHo'><a title='查看资料' onclick='lookUserView(" + userObj.lvid + ")' href='###' class='fri-info'></a>";
		}
		html += "<td style='width:13px;'></td>";
		html += "</td>";
		html += " </tr>";
	}
	$('.loading-popup').hide();
	$("#userDataList tbody").html(html);
	if(editFlag && (creatorid == myuserid || lvid == tolvid || setGroupinfo.indexOf(lvid))) {
		editFlag = 0;
		updateNa(tolvid);
	}
	$('.updatamyNa').click(function() {
		updateNa(lvid);
	})
	$('.MemberWarp tbody tr').on('click', function() {
		$(this).addClass('active').siblings().removeClass('active');
	})
	var docuHeight = $('.tbody tbody').height();
	var contHeight = $('.tbody tbody tr').length * $('.tbody tbody tr').height();
	if(docuHeight > contHeight) {
		$('.tbody tbody').css('overflow', 'hidden');
		$('.tbodyMain table td:last-child').css('width', '20px');
	}
	$('.tbodyMain table tr').hover(function() {
		$(this).find($('.hoverIcon .imgHo')).show();
		$(this).find($('.hoverIcon span.shwodata')).hide();
	}, function() {
		$(this).find($('.hoverIcon .imgHo')).hide();
		$(this).find($('.hoverIcon span.shwodata')).show();
	})
}

function cancelre(id) {
	if(lvid == groupMainid) {
		sendCommand("{command:3010, params:{lvid:" + id + ",groupid:" + groupid + "}}");
	}
}
//关闭对话框
function closeDialogWindow() {
	sendCommand("{command:9001, params:{lvid:" + lvid + "}}");
}