var ChatType = {
	"PERSON": 0,
	"GROUP": 1
}; // 0 - 个人聊天；1 - 群组聊天
var imServer = getParameter("imserver");
var lvid = getParameter("lvid");
var groupId = getParameter("groupid");
var tolvid = getParameter("tolvid");
var sign = getParameter("sign");
imServer = getImServer(imServer);
var chatType = tolvid ? ChatType.PERSON : ChatType.GROUP;
var pageNo = 1;
var itemstart = 0;
var itemcount = 3;
var itemstep = 25;
var recordContainer; //聊天记录容器
var lastMsgDate; //上一条消息发布时间
var lastMsgLvid, lastMsgNickname; //上一条消息发布者驴ID
var mouseDown = false; //是否按下鼠标键
var mouseWheel = false; //是否正在滚轮
var keyUpOrDown = false; //触发上下键
var ownerScrollEvent = false; //主动触发滚动条事件 
var autoScroll = false; //主动滑动滚动条
var scrollBottomInterval; //滚动条到底定时器 
var resizeInterval; //滚动条显示定时器
var resizeCount = 0;
var pageFlag = 'chat'; //页面状态
var firstInsert = true; //是否为第一次插入消息
var initStatus = false; //初始化是否完成状态
var ctrlC = true; //是否按下了ctrl+c
var cachePool = []; //插入记录缓存
var lastRecord; //上一条聊天记录
var isNewMsg = true; //printMsg是否都为New消息
var ajaxReq; //ajax请求对象
var toNickName; //对方
var msgIdList = []; //输出消息ID列表
var reloadProjectCache = []; //重新加载项目缓存
/**
 * 滑过显示title
 */
$(window).resize(function() {
	/*var cont = $(window).width();
	$('#container img').not('.linkImg img').each(function(){
		var $this = $(this);
		var wid = $this.width();
		if(wid >= cont){
			$this.width(Number(cont) - 80);
		}else if(wid < cont && wid < $this.attr('wid')){
			$this.animate({width:(Number(cont) - 80)},100)
		}else{
			$this.animate({width:$this.attr('wid')},100)
		}
	})*/
	reSize();
	scrollBottom();
});
$("#atMsgInfo").click(function() {
	var $this = $(this);
	if($this.find('em').length >= 1) {
		var ti = $this.find('em').attr('id');
		if(ti){
			var rr = Number(ti.slice(3, 100)) - 1;
			ti = 'my_' + rr;
			location.hash = "#" + ti;
		}
	}
	if(autoScroll) {
		window.clearInterval(scrollBottomInterval);
		autoScroll = false;
	}
	$this.hide();
	window.location.hash = '';
});
$(window).load(function() {
	try {
		sendCommand('{command:9015, params:{title:"初始化", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 事件绑定开始……", iswritefile:1}}');
	} catch(e) {}
	$("#newInfo").click(function() {
		$(this).hide();
		scrollBottom();
	});
	$(window).mousedown(function(event) {
		mouseDown = true;
		//去除鼠标中间滚轮的点击事件
		if(2 == event.which) {
			return false;
		};
	});
	$(window).mouseup(function(event) {
		mouseDown = false;
	});
	$(window).mousewheel(function(event, delta) {
		mouseWheel = true;
		setTimeout(function() {
			if(mouseWheel) {
				mouseWheel = false;
			}
		}, 200);
	});
	$(window).mousedown(function(event, rig) {
		$("img").removeClass("imgcutbo");
		var target = event.target;
		var imgMd5 = "",
			faceSrc = '';
		var id, userId;
		if(target.nodeName.toLowerCase() == "img") {
			id = $(target).parents('dl').find('a.rightClick').text();
			userId = $(target).parents('.chatRecord').find('dl').attr('reportId');
			if(event.which == 1 || event.which == 3) {
				$(target).not('.linkInfo img,.atMsgInfo img,.errorIcon').addClass('imgcutbo');
				imgMd5 = $(target).attr("md5");
				if(!imgMd5) {
					faceSrc = $(target).attr("src");
				}
				if(isSelect() && window.getSelection().anchorOffset > 0 && window.getSelection().toString() != '') {
					window.getSelection().removeAllRanges();
				}
			}
		}
		if(event.which == 3 || rig == 'right') {
			if(window.getSelection().toString() == '') {
				$('.record').attr('contenteditable', 'false');
			}
			var isSelectStatus = isSelect() || imgMd5 || faceSrc ? true : false;
			if(imgMd5 && isSelect()) {
				imgMd5 = '';
			}
			if($(target).parents().hasClass('projectCont')) {
				return;
			}
			if($(target).parents().hasClass('linkImg')) {
				isSelectStatus = false;
			}
			var reportid = id || userId;
			var params = '{lvid:' + lvid + ', tolvid:' + tolvid + ', groupid:' + groupId + ', "select":' + isSelectStatus + ', "img":"' + (imgMd5 || "") + '", "face":"' + (faceSrc || "") + '",reportid:' + reportid + '}';
			sendCommand('{"command":9016, "params":' + params + '}');
		}
	});

	$('.scrfirBtn').click(function() {
		$('.record').scrollTop(0);
		if(autoScroll) {
			window.clearInterval(scrollBottomInterval);
			autoScroll = false;
		}
	});

	$('.scrbotBtn').click(function() {
		scrollBottom();
	});

	$('.record').scroll(function() {
		ownerScrollEvent = mouseDown || mouseWheel || keyUpOrDown;
		if(ownerScrollEvent) {
			window.clearInterval(scrollBottomInterval); 
			autoScroll = false;
		}
		if(isNotBottom() == false && $("#newInfo").is(':hidden') == false) {
			$("#newInfo").click();
		}
		if(!isNotBottom() && !autoScroll) {
			scrollBottomInterval = setInterval(scrollBottom, 300);
			autoScroll = true;
		}
	});
	resizeInterval = setInterval(function() {
		if($('.record').css('overflow') == 'hidden' && ++resizeCount <= 5) {
			reSize();
		} else {
			clearTimeout(resizeInterval);
		}
	}, 1000);
	//控制键盘按下ctrl c/a
	$(document).on('keydown', function(e) {
		if(e.keyCode >= 37 && e.keyCode <= 40) {
			keyUpOrDown = true;
			return true;
		}
		if(!e.ctrlKey) {
			//通知聊天窗口获取焦点
			sendCommand('{"command":9026, "params":{lvid: ' + lvid + ', tolvid: ' + tolvid + ', groupid: ' + groupId + ', keycode: ' + e.keyCode + '}}');
			return false;
		}
		var k = e.keyCode;
		var kStatus = false;
		switch(k) {
			case 65: //a
				kStatus = true;
				window.getSelection().removeAllRanges();
				break;
			case 67: //c
				kStatus = true;
				if(ctrlC && !isSelect()) {
					ctrlC = false;
					var selImgMd5 = $('.imgcutbo').attr('md5');
					if(selImgMd5) {
						var params = '{lvid:' + lvid + ', tolvid:' + tolvid + ', groupid:' + groupId + ', "img":"' + selImgMd5 + '"}';
						sendCommand('{"command":9022, "params":' + params + '}');
						break;
					}
					var selFaceSrc = $('.imgcutbo').attr('src');
					if(selFaceSrc) {
						var params = '{lvid:' + lvid + ', tolvid:' + tolvid + ', groupid:' + groupId + ', "face":"' + selFaceSrc + '"}';
						sendCommand('{"command":9027, "params":' + params + '}');
					}
				}
				break;
			default:
				kStatus = false;
				break;
		}
		return kStatus;
	});

	//控制键盘按下ctrl c/a
	$(document).on('keyup', function(e) {
		if(e.keyCode >= 37 && e.keyCode <= 40) {
			keyUpOrDown = false;
			return true;
		}
		if(e.keyCode == 67) {
			ctrlC = true;
		}
	});
	try {
		sendCommand('{command:9015, params:{title:"初始化", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 事件绑定初始化完成", iswritefile:1}}');
	} catch(e) {}
	recordContainer = $("#container");
	recordContainer.html('<div id="loadPrePage" class="dialogueWarp"><img src="../images/load.gif"></div>');
	reSize();
	scrollBottom();
	loadMsg();
});

/**
 * 重新调整也没布局适配窗口大小
 */
function reSize() {
	try {
		sendCommand('{command:9015, params:{title:"resize", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ', resizeCount: ' + resizeCount + ' 重新计算窗口大小", iswritefile:1}}');
	} catch(e) {}
	$(".recline").css({
		width: ($(window).width() - $(".timeCon").width()) / 2 - 9
	});
	var winHeight = $(window).height() - 20;
	$('.record').css({'height': winHeight});
	$('.lvbg').css({'height':$(window).height()})
	$("#newInfo").width($(window).width() - 20);
	if($('#container').height() < winHeight) {
		$('.record').css('overflow', 'hidden');
		$('#container').css('overflow', 'hidden');
		$('.scrfirBtn,.scrbotBtn').hide();
		$('#container').css('margin-right', '15px');
	} else {
		$('.record').css({
			'overflow': 'hidden',
			'overflow-y': 'scroll'
		})
		$('#container').css({'margin-right': '5px','overflow':'hidden'});
		$('.scrfirBtn,.scrbotBtn').show();
	}
}

/**
 * 加载上一页聊天记录
 */
var listDot = true;
function loadPrePageGroupMsg() {
	listDot = false;
	var params = '{"command":9012,"params":{"lvid":' + lvid + '}}';
	var result = $.parseJSON(sendCommand(params));
	if(result['errorid'] != 0 || result['status'] == 0) {
		return;
	}
	itemstart = itemstart + itemcount;
	itemcount = itemstep;
	pageNo++;
	loadMsg();
}

function userOnline() {
	itemstart = 0;
	itemcount = 3;
	$('.atMsgInfo').hide();
	loadMsg();
}

/**
 * 拉取聊天信息
 */
function loadMsg() {
	var params = '{"command":9012,"params":{"lvid":' + lvid + ',"ishidedlg":1}}';
	var result = $.parseJSON(sendCommand(params));
	if(result['errorid'] != 0 || result['status'] == 0) {
		$('.atMsgInfo p').addClass('recorderror').html('你已处于离线状态，无法发送消息，请上线后再次尝试。');
		$('.atMsgInfo').show();
		return;
	}
	try {
		var data = sendCommand('{command:9004,params:{"lvid":' + lvid + '}}');
		if(data) {
			var result = $.parseJSON(data);
			if(result['errorid'] == 0) {
				sign = result['sign'];
			}
		}
	} catch(e) {}
	var param = {
		"lvid": parseInt(lvid),
		"tolvid": parseInt(tolvid),
		"groupid": parseInt(groupId),
		"itemstart": itemstart,
		"itemcount": itemcount,
		"callback": 'printMsg'
	}
	sendCommand('{command:9030, params:' + $.toJSON(param) + '}');
	$("#loadPrePage").html('<img src="../images/load.gif">');
	try {
		sendCommand('{command:9015, params:{title:"loadMsg", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 开始拉取聊天记录, start: ' + itemstart + ', count: ' + itemcount + '", iswritefile:1}}');
	} catch(e) {}
}
function printMsg(result) {
	try {
		sendCommand('{command:9015, params:{title:"printMsg", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 开始输出聊天记录", iswritefile:1}}');
	} catch(e) {}
	$("#loadPrePage").remove();
	//异常 || 没有记录
	if(result['errorid'] != 0 || result['count'] == 0) {
		printCacheRecord();
		return;
	}
	itemcount = result.data.length;
	var records = result.data;
	var html = '';
	//更多消息提示 
	if(result['count'] > itemstart + itemcount) {
		if(itemstart <= 100) {
			html += '<div id="loadPrePage" class="dialogueWarp"><a href="javascript:;" onclick="loadPrePageGroupMsg()">查看更多消息</a></div>';
		} else {
			html += '<div id="loadPrePage" class="dialogueWarp">更多聊天信息请在聊天记录中查阅 ,<a style="background:none;padding-left:0" href="javascript:;" onclick="openChatHistory()">打开聊天记录</a></div>';
		}
	}
	var record;
	var ownerClass, showDate;
	var chatDateTime, chatDate, chatTime, currDate = $.formatDateStyle1(new Date());
	var projectInfo, fileInfo;
	var firstPrint = true; //控制输出昵称标签
	try {
		sendCommand('{command:9015, params:{title:"printMsg", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ', start: ' + itemstart + ', step: ' + itemcount + ', count: ' + records.length + ' 开始组装记录", iswritefile:1}}');
	} catch(e) {}
	html += '<div class="chatRecord">';
	var chatName;
	toNickName = result['tonickname'];

	for(var i = records.length - 1; i >= 0; i--) {
		record = records[i];
		try {
			msgIdList.push(record['id']);
			//验证是否都为未读消息
			if(isNewMsg && (chatType == ChatType.PERSON && record['readstate'] == 0) || (chatType == ChatType.GROUP && record['id'] <= result['maxmsgid'])) {
				isNewMsg = false;
			}
			chatName = record['groupnickname']
			if(chatName === undefined || chatName.length == 0 || chatName == '-') {
				if(record['lvid'] != lvid && toNickName) {
					chatName = toNickName;
				} else {
					chatName = record['nickname'];
				}
			}
			chatName = chatName.replaceAll('<', '&lt;').replaceAll('>', '&gt;');
			if(chatName.length > 9) {
				chatName = chatName.slice(0, 9) + '...';
			} else {
				chatName = chatName;
			}
			chatDateTime = new Date(record["datetime"] * 1000);
			chatDate = $.formatDateStyle1(chatDateTime);
			chatTime = $.formatDateStyle2(chatDateTime);
			ownerClass = record["lvid"] == lvid ? "partner-one" : "partner-two";
			showDate = currDate == chatDate ? chatTime : (chatDate + ' ' + chatTime);
			html += '<dl reportId = "' + record['lvid'] + '">';
			if(firstPrint || lastMsgLvid != record['lvid'] || lastMsgNickname != chatName || !sameMinute(lastMsgDate, chatDateTime)) {
				firstPrint = false;
				html += '<p class="' + ownerClass + '">' + chatName;
				if(chatType == ChatType.GROUP) {
					if(record['lvid'] == lvid) {
						html += '(<a class="rightClick myLvid" href="javascript:;"  onclick="userMenu(this, event)">' + record['lvid'] + '</a>)';
					} else {
						html += '(<a class="rightClick otherLvid" href="javascript:;" onclick="userMenu(this, event)">' + record['lvid'] + '</a>)';
					}
				}
				html += ' ' + chatDate + ' ' + chatTime + '</p>';
			}
			html += '<p class="notStyle pdd" style="' + parseFontStyle(record['fontstyle']) + '">';
			html += parseMsg(record["msgcontent"], false, lvid);
			html += '</p>';
			projectInfo = parseProject(record['msgcontent']);
			if(projectInfo) {
				html += projectInfo;
			}
			fileInfo = parseFileHtml(record['msgcontent']);
			if(fileInfo) {
				html += fileInfo;
			}
			html += '</dl>';
			lastMsgDate = chatDateTime;
			lastMsgLvid = '<a class="myLvid" href="javascript:;">' + record['lvid'] + '</a>';
			lastMsgNickname = chatName;
			//如果是云组聊天，检测是否有@消息
			if(chatType == ChatType.GROUP && record['lvid'] != lvid && record['id'] > result['maxmsgid']) {
				var atLvidArr = parsePersonReLvidArr(record['msgcontent']);
				if(atLvidArr) {
					for(var j = 0; j < atLvidArr.length; j++) {
						if(atLvidArr[j] == 'all' || lvid == atLvidArr[j]) {
							var newMsgHtml = "<xmp>" + record["nickname"] + "</xmp>";
							var ts = parseMsg(record['msgcontent'], true)
							var rep = ts.replaceAll('<a', '<em').replaceAll('a>', 'em>')
							newMsgHtml += '：' + rep;
							$("#atMsgInfo").show().find('p').removeClass('recorderror').html(newMsgHtml);
							break;
						}
					}
				}
			}
			lastRecord = record;
		} catch(e) {
			try {
				sendCommand('{command:9015, params:{title:"printMsg", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 组装聊天记录异常: ' + e + '", iswritefile:1}}');
			} catch(e) {}
		}
	}
	html += '</div>';
	if(pageNo != 1) {
		clearInterval(scrollBottomInterval);
		autoScroll = false;
	}
	html += '<a name="page_' + pageNo + '"></a>';
	recordContainer.html(html + recordContainer.html());
	$('img').load(function() {
		var chatOuterHei = $('.chatRecord').outerHeight();
		$('.record').scrollTop(chatOuterHei);
	})
	$('.par b').hide();
	var chatOuterHei = $('.chatRecord').outerHeight();
	$('.record').scrollTop(chatOuterHei);
	imgOnloadResize();
	resetImgView();
	if(pageNo > 1) {
		//		window.location.href = "#page_" + pageNo;
		var imgArr = parseImgReArr($.toJSON(records));
		if(imgArr.length > 0) {
			sendCommand('{"command":9014, "params":{"lvid":' + lvid + ', "groupid": ' + groupId + ', "imgarray":' + $.toJSON(imgArr.reverse()) + '}}');
		}
	} else {
		printCacheRecord();
	}
	try {
		sendCommand('{command:9015, params:{title:"printMsg", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 聊天记录输出完毕", iswritefile:1}}');
	} catch(e) {}
	reSize();
}

function sameMinute(lastMsgDate, chatDateTime) {
	if(lastMsgDate == '') {
		return false;
	}
	var lastDate = $.formatDateStyle1(lastMsgDate);
	var chatDate = $.formatDateStyle1(chatDateTime);
	if(lastDate != chatDate) {
		return false;
	}
	if(lastMsgDate.getHours() != chatDateTime.getHours()) {
		return false;
	}
	return lastMsgDate.getMinutes() == chatDateTime.getMinutes();
}

//延迟重新加载项目
function reloadProjectInfo(projectBaseInfo) {
	var params = {
		"projectid": projectBaseInfo['id'],
		"lvid": lvid,
		"sign": sign
	};
	$.getJSON(requestUrlMap['projectInfo']['url'], params, function(resultData) {
		if(!resultData || resultData['errorid'] != 0) {
			var delTip = '项目：';
			if(projectBaseInfo['name']) {
				delTip += projectBaseInfo['name'] + ' (' + projectBaseInfo['id'] + ')';
			} else {
				delTip += projectBaseInfo['id'];
			}
			delTip += ' 已被删除!';
			$('.project_' + projectBaseInfo['id']).parent().html(delTip);
			return;
		}
		var projectInfo = resultData['projectinfo'];
		$('.project_' + projectBaseInfo['id']).html(htmlProject(projectInfo));
	});
}

/**
 * 解析项目
 */
function parseProject(text) {
	var projectBaseInfo = parseProjectBaseInfo(text);
	if(!projectBaseInfo) {
		var projectId = parseProjectId(text);
		if(!projectId) {
			return "";
		}
		projectBaseInfo = {
			'id': projectId,
			'name': ''
		};
	}
	var data = sendCommand('{command:9004,params:{"lvid":' + lvid + '}}');
	if(data) {
		var result = $.parseJSON(data);
		if(result['errorid'] == 0) {
			sign = result['sign'];
		}
	}
	var params = {
		"projectid": projectBaseInfo['id'],
		"lvid": lvid,
		"sign": sign
	};
	$.getJSON(requestUrlMap['projectInfo']['url'], params, function(resultData) {
		if(!resultData || resultData['errorid'] != 0) {
			var delTip = '项目：';
			if(projectBaseInfo['name']) {
				delTip += projectBaseInfo['name'] + ' (' + projectBaseInfo['id'] + ')';
			} else {
				delTip += projectBaseInfo['id'];
			}
			delTip += ' 已被删除!';
			$('.project_' + projectBaseInfo['id']).parent().html(delTip);
			return;
		}
		var projectInfo = resultData['projectinfo'];
		$('.project_' + projectBaseInfo['id']).html(htmlProject(projectInfo));
	});
	return '<dd><div class="linkBox project_' + projectBaseInfo['id'] + '"></div></dd>'
}

/**
 * 模板输出项目
 */
function htmlProject(projectInfo) {
	var dateobj = $.formatDateStyle3(new Date(projectInfo['uploadtime'] * 1000))
	var html = '';
	var projectType = projectInfo['projecttype'] == 0 ? "硫酸纸" : "3D";
	createorname = projectInfo['creatorname'];
	if(createorname && createorname.length > 3) {
		createorname = createorname.substring(0, 3) + "...";
	}
	if(projectInfo['iconurl'] == '' || !projectInfo['iconurl']) {
		projectInfo['iconurl'] = '../images/blue/projectImg.png';
		if(reloadProjectCache.indexOf(projectInfo['projectid']) == -1) {
			reloadProjectCache.push(projectInfo['projectid']);
			setTimeout(function() {
				reloadProjectInfo({
					'id': projectInfo['projectid'],
					'name': projectInfo['projectname']
				});
			}, 5000);
		}
	}
	html += '<div class="linkWarp projectCont">';
	html += '<div class="linkInfo">';
	var projectName = projectInfo['projectname'].indexOf('/') == 0 ? projectInfo['projectname'].slice(1, projectInfo['projectname'].length) : projectInfo['projectname'];
	html += '<div class="linkImg" onclick="openProject(' + projectInfo['projectid'] + ')"><img title=\"' + projectName.replaceAll(' ', '') + '\" src="' + projectInfo['iconurl'] + '" onerror=\'javascript:this.src ="../images/blue/projectImg.png"\' ></div>';
	html += '<div class="linkMessage">';
	html += '<dl>';
	html += '<dt onclick="openProject(' + projectInfo['projectid'] + ')" title=\"' + projectName.replaceAll(' ', '') + '\" style="padding-left:0px;">' + projectName + '</dt>';
	html += '<dd style="padding-left: 0px;"><span onclick="openProject(' + projectInfo['projectid'] + ')" style="float:left" title=\"' + dateobj + '\" class="linkUpdated">' + dateobj + '</span></dd>';
	html += '</dl>';
	html += '</div>';
	html += '<div class="clear"></div>';
	html += '<div class="linkOpen">';
	if(projectType == '3D') {
		html += '<img src="../images/3D.png" alt="">';
		html += '<span title="查看项目" onclick="openProject(' + projectInfo['projectid'] + ')">打开</span>';
		html += '<i></i>';
		var tit3d = projectType + "模型(" + projectInfo['handlenum'] + ")张";
		html += '<p onclick="openProject(' + projectInfo['projectid'] + ')" title=' + tit3d + '>' + projectType + '模型' + '&nbsp;(<span>' + projectInfo['handlenum'] + '</span>张)</p>';
	} else {
		html += '<img src="../images/2D.png" alt="">';
		html += '<span title="查看项目"  onclick="openProject(' + projectInfo['projectid'] + ')">打开</span>';
		html += '<i></i>';
		var tit2d = projectType + "(" + projectInfo['handlenum'] + ")张";
		html += '<p onclick="openProject(' + projectInfo['projectid'] + ')" title=' + tit2d + '>' + projectType + '&nbsp;(<span>' + projectInfo['handlenum'] + '</span>张)</p>';
	}
	html += '</div>';
	html += '</div>';
	return html;
}

/**
 * 打开项目
 * @param projectId 项目ID
 */
function openProject(projectId) {
	var data = sendCommand('{command:9004,params:{"lvid":' + lvid + '}}');
	if(data) {
		var result = $.parseJSON(data);
		if(result['errorid'] == 0) {
			sign = result['sign'];
		}
	}
	var params = {
		"projectid": projectId,
		"lvid": lvid,
		"sign": sign
	};
	$.getJSON(requestUrlMap['projectInfo']['url'], params, function(resultData) {
		if(!resultData || resultData['errorid'] != 0) {
			var paramStr = "{title:'提示',cat:0,content:'该项目已被删除！'}";
			var params = "{command:9006,params:" + paramStr + "}";
			var resultS = sendCommand(params);
			return;
		}
		var projectInfo = resultData['projectinfo'];
		var projectJSON = $.toJSON(projectInfo);
		var params = "{command:1008,params:" + projectJSON + "}";
		var resultS = sendCommand(params);
	});
}
/**
 * 追加消息，支持个人消息、云组消息
 * {"lvid": 50022, msgtime: 2131231231231,"nickname": "测试", "msgcontent": "测试", "fontstyle":""}
 */
var listDot = 50;

function insertMessage(record) {
	listDot = listDot + 1;
	try {
		sendCommand('{command:9015, params:{title:"insertMessage", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 插入聊天记录, id: ' + record['id'] + '", iswritefile:1}}');
	} catch(e) {}
	if(record['id'] && msgIdList.indexOf(record['id']) != -1) {
		try {
			sendCommand('{command:9015, params:{title:"insertMessage", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 插入重复聊天记录, id: ' + record['id'] + '", iswritefile:1}}');
		} catch(e) {}
		return;
	}
	if(!initStatus) {
		cachePool.push(record);
		try {
			sendCommand('{command:9015, params:{title:"insertMessage", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 页面未初始化完成, 记录加入缓存池. Length: ' + cachePool.length + '", iswritefile:1}}');
		} catch(e) {}
		return;
	}
	var currDate = $.formatDateStyle1(new Date());
	var chatDateTime = new Date(record.msgtime);
	var chatDate = $.formatDateStyle1(chatDateTime);
	var chatTime = $.formatDateStyle2(chatDateTime);
	var sendchatName = record["nickname"].replaceAll('<', '&lt;').replaceAll('>', '&gt;');
	if(sendchatName.length > 9) {
		sendchatName = sendchatName.slice(0, 9) + '...';
	}
	var ownerClass = record["lvid"] == lvid ? "partner-one" : "partner-two";
	var html = '<div class="chatRecord clearfix">';
	html += '<dl style="clear:both" reportId = "' + record['lvid'] + '">';
	if(firstInsert || lastMsgLvid != record['lvid'] || lastMsgNickname != sendchatName || !sameMinute(lastMsgDate, chatDateTime)) {
		firstInsert = false;
		html += '<p class="userCont ' + ownerClass + '">' + sendchatName;
		if(chatType == ChatType.GROUP) {
			if(record['lvid'] == lvid) {
				html += '(<a class="rightClick myLvid" href="javascript:;"  onclick="userMenu(this, event)">' + record['lvid'] + '</a>)';
			} else {
				html += '(<a class="rightClick" style="color:#3c93d5" href="javascript:;" onclick="userMenu(this, event)">' + record['lvid'] + '</a>)';
			}
		}
		if(currDate != chatDate) {
			html += ' ' + chatDate + ' ' + chatTime + '</p>';
		} else {
			html += '　 ' + chatTime + '</p>';
		}
	}
	html += '<p newsId="'+record['id']+'" class="list_' + listDot + ' pdd" style="' + parseFontStyle(record['fontstyle']) + '">';
	html += parseMsg(record["msgcontent"], false, lvid, false, record["lvid"]);
	html += '</p>';
	var projectInfo = parseProject(record['msgcontent']);
	if(projectInfo) {
		html += '<div class="removeList">'+projectInfo + '</div>';
	}
	var fileInfoHtml = parseFileHtml(record['msgcontent']);
	if(fileInfoHtml) {
		html += fileInfoHtml;
	}
	lastMsgDate = chatDateTime;
	lastMsgLvid = record['lvid'];
	lastMsgNickname = sendchatName;
	html += '</dl>';
	html += '</div>';
	if(record['lvid'] != lvid && isNotBottom()) {
		var newMsgHtml = sendchatName;
		if(chatType == ChatType.GROUP) {
			newMsgHtml += ' (' + record['lvid'] + ')';
		}
		newMsgHtml += '：' + parseMsg(record['msgcontent'], true)
		$("#newInfo").html(newMsgHtml).show();
	} else if(record['lvid'] == lvid) {
		scrollBottom();
	}
	recordContainer.append(html);
	listStyle();
//	resetImgView();
	imgOnloadResize();
	itemcount++;
	try {
		sendCommand('{command:9015, params:{title:"insertMessage", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ', itemcount: ' + itemcount + '", iswritefile:1}}');
	} catch(e) {}
	//如果是云组聊天，检测是否有@消息
	if(chatType == ChatType.GROUP && record['lvid'] != lvid) {
		var atLvidArr = parsePersonReLvidArr(record['msgcontent']);
		if(atLvidArr) {
			for(var i = 0; i < atLvidArr.length; i++) {
				if(atLvidArr[i] == 'all' || lvid == atLvidArr[i]) {
					var newMsgHtml = "<xmp>" + record["nickname"] + "</xmp>";
					if(chatType == ChatType.GROUP) {
						newMsgHtml += ' (' + record['lvid'] + ')';
					}
					var ts = parseMsg(record['msgcontent'], true)
					var rep = ts.replaceAll('<a', '<em').replaceAll('a>', 'em>')
					newMsgHtml += '：' + rep;
					$("#atMsgInfo").show().find('p').removeClass('recorderror').html(newMsgHtml);
					break;
				}
			}
		}
	}
	reSize();
}
//合并消息时显示原点
function listStyle(){
	if($('.list_' + listDot).prev().hasClass('userCont')) {
		$('.list_' + listDot).removeClass('listStyle');
	}else {
		$('.list_' + Number(listDot - 1)).addClass('listStyle2');
		$('.chatFile,.removeList').prev('p').removeClass('listStyle2');
		if(!$('.list_' + listDot).hasClass('loadStyle')){
			$('.list_' + Number(listDot - 1)).addClass('listStyle');
			if($('.list_' + listDot).find('.imgface').length >= 1 ){
				$('.list_' + listDot).addClass('listStyle').css({
					'background-position': '20px 32px'
				})
				return;
			}
			var listHeight = ($('.list_' + listDot).height() / 2) + 3;
			var txt = '<xmp>' + $('.list_' + listDot).html() + '</xmp>';
			var txtPrev = '<xmp>' + $('.list_' + Number(listDot - 1)).html() + '</xmp>';
			var txtPrevSize = parseInt($('.list_' + Number(listDot - 1)).css('font-size'));
			$('.list_' + listDot).addClass('listStyle').css({
				'background-position': '20px ' + listHeight + 'px'
			});
			if(txt.indexOf('<br>') > -1) {
				if(txtPrev.indexOf('<br>') > -1) {
					txtPrevSize = txtPrevSize > 18 ? txtPrevSize - 7 : 11;
					$('.list_' + Number(listDot - 1)).css({
						'background-position': '20px ' + txtPrevSize + 'px'
					});
				}
				var txtSize = parseInt($('.list_' + listDot).css('font-size'));
				txtSize = txtSize > 18 ? txtSize - 7 : 11;
				$('.list_' + listDot).css({
					'background-position': '20px ' + listHeight + 'px'
				});
			} else {
				if(txtPrev.indexOf('<br>') > -1) {
					txtPrevSize = txtPrevSize > 18 ? txtPrevSize - 7 : 11;
					$('.list_' + Number(listDot - 1)).css({
						'background-position': '20px ' + txtPrevSize + 'px'
					});
				} else {
					$('.list_' + listDot).css({
						'background-position': '20px ' + listHeight + 'px'
					});
				}
			}
		}
	}
	$('.chatFile,.removeList').prev('p').removeClass('listStyle');
}
// 图片加载进度 status 0 = 错误值退出   1=只加载进度   2=完成图裂  3=完成图片正常
function imgLoading(msg){ 
	var bar = msg.bar;
	var md5 = msg.md5.slice(0,32).toLocaleLowerCase();
	var status = msg.status;
	if(!$('.img_'+md5).prev().is('b')){
		var clickPic = $('.img_'+md5).attr('ondblclick');  
		$('.img_'+md5).before('<b class="imgLoad" ondblclick='+clickPic+'><i></i></b>');
		$('.img_'+md5).hide();
	}
	$('.img_'+md5).parent().find('.pic').hide();
	$('.img_'+md5).prev('.imgLoad').find('i').css('width',bar+'%');
	if(status == 0 || status == 2){
		$('.img_'+md5).prev('.imgLoad').css({'background':'url(../images/imgError.png) !important','width':'42px','height':'32px'});
	}
}

function imgReload(imgInfo){
	try {
		sendCommand('{command:9015, params:{title:"强制更新图片", content:' + $.toJSON(imgInfo) + ', iswritefile:1}}');
	} catch(e) {}
	if(!imgInfo || !imgInfo['name'] || !imgInfo['src']) {
		return -1;
	}
	var md5Name = imgInfo['name'].toLocaleLowerCase();
	var tag = ".img_" + md5Name;
	$(tag).next('b').addClass('success').hide();
	$(tag).next('.load').remove();
	$(tag).parent().find('.pic').hide();
}

function imgUploading(msg){
	if(msg.status == 1){
		$('.img_'+msg.uploadimg.toLocaleLowerCase()).next('b').addClass('success').hide();
		$('.img_'+msg.uploadimg.toLocaleLowerCase()).next('.load').remove();
		return;
	}
	var errorImg = msg.uploadimg.toLocaleLowerCase();
	$('.img_'+errorImg).before('<a onclick="reSendImg(this)" title="重新发送!" class="errorPic"><em>'+JSON.stringify(msg)+'</em></a>').show();
}
function errorMsg(msg){
	$('p[newsId='+msg.id+']').prepend('<img class="errorIcon" onclick="reSend(this)" src="../images/imp.png" title="重新发送!"><i style="display:none">'+JSON.stringify(msg)+'</i>');
}
function reSend(a){
	if($(a).parents('dl').find('p.pdd').length > 1){
		$(a).parent('p.pdd').hide();
	}else{
		$(a).parents('dl').hide();
	}
	var dataMsg = $(a).next('i').text();
	var data = JSON.parse(dataMsg);
		data.tolvid = Number(tolvid);
		data.groupid = Number(groupId);
	sendCommand('{command:9039, params:'+JSON.stringify(data)+'}');
} 
function reSendImg(a){
	var dataMsg = $(a).find('em').text();
	var data = JSON.parse(dataMsg);
		data.md5 = $(a).parent('.par').find('.imgcut').attr('md5');
		data.tolvid = Number(tolvid);
		data.groupid = Number(groupId);
	sendCommand('{command:9040, params:'+JSON.stringify(data)+'}');
	if($(a).parents('.pdd').find('.imgcut').length == 1){
		$(a).parents('dl').remove();
	}else{
		$(a).next().remove();
		$(a).remove();
	}
} 
/**
 * 发送文件消息
 * {"lvid": 50022, msgtime: 2131231231231,"nickname": "测试", "msgcontent": "测试", "fontstyle":""}
 */
function insertFileMessage(record) {
	try {
		sendCommand('{command:9015, params:{title:"insertFileMessage", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 插入文件记录: ' + record['msgcontent'] + '", iswritefile:1}}');
	} catch(e) {}
	chatDateTime = new Date(record.msgtime);
	chatDate = $.formatDateStyle1(chatDateTime);
	chatTime = $.formatDateStyle2(chatDateTime);
	var sendchatName = record["nickname"].replaceAll('<', '&lt;').replaceAll('>', '&gt;');
	if(sendchatName.length > 9) {
		sendchatName = sendchatName.slice(0, 9) + '...';
	}
	var ownerClass = record["lvid"] == lvid ? "partner-one" : "partner-two";
	var html = '<div class="chatRecord clearfix">';
	html += '<dl fileId = "' + record['id'] + '">';
	if(firstInsert || lastMsgLvid != record['lvid'] || lastMsgNickname != sendchatName || !sameMinute(lastMsgDate, chatDateTime)) {
		firstInsert = false;
		html += '<p class="' + ownerClass + '">' + sendchatName;
		if(chatType == ChatType.GROUP) {
			if(record['lvid'] == lvid) {
				html += '(' + record['lvid'] + ')';
			} else {
				html += '(<a style="color:#3c93d5" href="javascript:;" onclick="userMenu(this, event)">' + record['lvid'] + '</a>)';
			}
		}
		html += '　 ' + chatTime + '</p>';
	}
	var fileInfoHtml = parseFileHtml(record['msgcontent']);
	if(fileInfoHtml) {
		html += fileInfoHtml;
	}
	lastMsgDate = chatDateTime;
	lastMsgLvid = record['lvid'];
	lastMsgNickname = sendchatName;
	html += '</dl>';
	html += '</div>';
	if(record['lvid'] != lvid && isNotBottom()) {
		var newMsgHtml = sendchatName;
		newMsgHtml += '：' + parseMsg(record['msgcontent'], true)
		$("#newInfo").html(newMsgHtml).show()
	} else if(record['lvid'] == lvid) {
		scrollBottom();
	}
	recordContainer.append(html);
	try {
		sendCommand('{command:9015, params:{title:"insertFileMessage", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + '", iswritefile:1}}');
	} catch(e) {}
	reSize();
}

/**
 * 插入系统消息
 * @param systemInfo 系统消息内容  {"msg":"测试系统消息"}
 */
function insertSystemNotice(systemInfo) {
	try {
		sendCommand('{command:9015, params:{title:"insertSystemNotice", content:"toLvid: ' + tolvid + ', groupId: ' + groupId + ' 插入系统消息", iswritefile:1}}');
	} catch(e) {}
	if(!systemInfo || !systemInfo['msg']) {
		return;
	}
	var tipClass;
	if(systemInfo['msg'].indexOf('对方取消接收') > -1 || systemInfo['msg'].indexOf('您取消了') > -1) {
		tipClass = 'errorbg';
	} else if(systemInfo['msg'].indexOf('您已成功接收') > -1 || systemInfo['msg'].indexOf('对方已成功接收') > -1) {
		tipClass = 'successbg';
	}
	var html = '<div class="dialogueWarp"><p class="dialogueTit"><span class=' + tipClass + '>' + systemInfo['msg'] + '</span></p></div>';
	if(ownerScrollEvent && isNotBottom()) {
		$("#newInfo").html(systemInfo['msg']).show();
	}
	recordContainer.append(html);
	reSize();
}

/**
 * 清空屏幕消息
 */
function clearMsg() {
	lastMsgDate = 0;
	recordContainer.html('');
	reSize();
}

/**
 * 显示用户菜单
 */
function userMenu(obj, event) {
	event.stopPropagation();
	var eventLvid = $(obj).text();
	var params = "{command:9009, params:{lvid: " + eventLvid + ", groupid: " + groupId + "}}";
	sendCommand(params);
}

/**
 * 滚动页面底部
 */
function scrollBottom() {
	var scrollTop = recordContainer.height() - $(window).height() + 20;
	$('.record').scrollTop(scrollTop == 0 ? recordContainer.height() : scrollTop);
	if(!autoScroll) {
		scrollBottomInterval = setInterval(scrollBottom, 300);
		autoScroll = true;
	}
}

function isNotBottom() {
	return $(".record").height() + $(".record").scrollTop() < $("#container").height();
}

//发起@云聊
function clickAtMsg(atLvid) {
	if(atLvid == 'all') {
		atLvid = 0;
	}
	var params = '{command: 1009, params: {"lvid":' + lvid + ', "groupid":' + groupId + ', "tolvid":' + atLvid + '}}';
	sendCommand(params);
}

//拉起聊天记录窗体
function openChatHistory() {
	var params = '{"command":9013, "params": {"lvid":' + lvid + ', "groupid":' + groupId + ', "tolvid": ' + tolvid + '}}';
	sendCommand(params);
}

/**
 * 输出缓存中的记录 
 */
function printCacheRecord() {
	initStatus = true;
	if(cachePool.length > 0) {
		for(var i = 0; i < cachePool.length; i++) {
			insertMessage(cachePool[i]);
		}
		cachePool.length = 0;
	}
}

function imgOnloadResize() {
	$('img.imgcut').load(function() {
		reSize();
	})
}

function notifyWaterMarks(data) {
	var right = data.x == 1 ? 0 : data.x;
	$('.lvbg').css({'background':'url(../images/lvbg.png) no-repeat ' + right + 'px  ' + '-3px'});
}