<!--
/**
 * chat.js
 * @fileoverview 交谈功能，包含交谈设计到的各个函数，从初始化交谈组->交谈过程中的各个功能->交谈结束的各个功能函数都在此类中实现；包含{@link Chat}、{@link ChatGroup}、{@link ChatMember}3个类
 * @author Lynk Li
 */

/**
 * @class Chat 交谈类
 * @constructor
 * @author Lynk Li
 */
function Chat() {
	/**
	 * 交谈组数组，其每个元素都是一个{@link ChatGroup}对象
	 */
	this.arrChatGroups = new Array();
	/**
	 * 当前交谈组的ID
	 */
	this.currentGroup = null;
	this.getGroupById = Chat_getGroupById;
	
	this.replyVisitorRequest = Chat_replyVisitorRequest;
	this.newChatGroup = Chat_newChatGroup;
	this.newChatInterface = Chat_newChatInterface;
	this.sendWelcome = Chat_sendWelcome;
	this.sendMsg = Chat_sendMsg;
	this.receiveMsg = Chat_receiveMsg;
	this.insertChatLog = Chat_insertChatLog;
	this.showChatInterface = Chat_showChatInterface;
	this.resizeTitle = Chat_resizeTitle;
	this.showChatMemberList = Chat_showChatMemberList;
	this.showVisitorInfo = Chat_showVisitorInfo;
	this.memberInOut = Chat_memberInOut;
	this.buildSendToSelect = Chat_buildSendToSelect;
	this.visitorPreMsg = Chat_visitorPreMsg;
	this.leaveChat = Chat_leaveChat;
	this.deleteMember = Chat_deleteMember;
	this.closeChat = Chat_closeChat;
	this.deleteGroup = Chat_deleteGroup;
	
	/**
	 * 字体
	 */
	this.font_family = "SIMSUN";
	/**
	 * 斜体
	 */
	this.font_style = "normal";
	/**
	 * 粗体
	 */
	this.font_weight = "normal";
	/**
	 * 下划线
	 */
	this.text_decoration = "none";
	/**
	 * 字体大小
	 */
	this.font_size = "12px";
	/**
	 * 字体颜色
	 */
	this.font_color = "#000066";
	
	this.styleChange = Chat_styleChange;
	this.doStyleChange = Chat_doStyleChange;
	this.showFontDiv = Chat_showFontDiv;
	this.selectColor = Chat_selectColor;
	this.showColorDiv = Chat_showColorDiv;
	this.showEmotionDiv = Chat_showEmotionDiv;
	this.sendFace = Chat_sendFace;
	this.showLinkDiv = Chat_showLinkDiv;
	this.sendLink = Chat_sendLink;
	this.previewLink = Chat_previewLink;
	this.showFileDiv = Chat_showFileDiv;
	this.showInviteOperatorDiv = Chat_showInviteOperatorDiv;
	this.opInCurrentGroup = Chat_opInCurrentGroup;
	this.inviteOperatorWhenChating = Chat_inviteOperatorWhenChating;
	
	this.saveFontSetting = Chat_saveFontSetting;
	this.loadFontSetting = Chat_loadFontSetting;
	this.displaySetting = Chat_displaySetting;
	this.defaultFontSetting = Chat_defaultFontSetting;
	
	this.sendChatRequestToOperator = Chat_sendChatRequestToOperator;
	this.opInputCheck = Chat_opInputCheck;
	/**
	 * 发送方式: 0-Enter; 1-Ctrl+Enter
	 */
	this.sendWay = 0;
	this.divKeyDown = Chat_divKeyDown;
	this.changeSendType = Chat_changeSendType;
	this.insertReserve = Chat_insertReserve;
	this.sendFile = Chat_sendFile;
	this.closeAll = Chat_closeAll;
	this.sendOperatorInfo = Chat_sendOperatorInfo;
	this.changeChatTitleStyle = Chat_changeChatTitleStyle;
	this.addOption = Chat_addOption;
	this.move2end = Chat_move2end;
}

/**
 * @class ChatGroup 交谈组对象类
 * @constructor
 * @author Lynk Li
 * @param String id 交谈组的ID
 * @param String snid 交谈组中访客成员的ID，每个交谈最多包含1个访客
 */
function ChatGroup(id, snid) {
	/**
	 * 交谈组的ID
	 */
	this.id = id;
	/**
	 * 交谈组中访客成员的ID，每个交谈最多包含1个访客
	 */
	this.snid = snid;
	/**
	 * 客服上次输入的内容
	 */
	this.inputCache = "";
	/**
	 * 检查客服是否正在输入的Timer
	 */
	this.inputCheckTimer = setInterval("_chat.opInputCheck('" + this.id + "');", 3000);
	/**
	 * 交谈组成员数组,其每个元素都是一个{@link ChatMember}对象
	 */
	this.members = new Array();
}

/**
 * @class ChatMember 交谈成员对象类
 * @constructor
 * @author Lynk Li
 * @param id 成员ID
 * @param name 成员名
 * @param type 成员类型：1-客服;2-访客
 */
function ChatMember(id, name, type) {
	/**
	 * 成员ID
	 */
	this.id = id;
	/**
	 * 成员名
	 */
	this.name = name;
	/**
	 * 成员类型：1-客服;2-访客
	 */
	this.type = type; //1:operator;2:visitor
}

/**
 * 接受/拒绝访客邀请，消息格式&lt;M>&lt;C>9104;reply_status;g_chat_id;co_id;op_id;sn_id;page_op_id&lt;/C>&lt;/M>，应用于{@link Monitor#showVisitorMenu} {@link Monitor#changeHeadButtonStatus} {@link Monitor#visitorOnDblClick} {@link Monitor#showVisitorPage} {@link Monitor#visitorRequestChat}
 * @param int reply 接受/拒绝标志1-拒绝；2-接受
 * @param String opid 客服ID
 * @param String snid 访客ID
 * @param Srring pageid 访客页面ID
 * @param String chatGroupId 交谈组ID
 */
function Chat_replyVisitorRequest(reply, opid, snid, pageid, chatGroupId) {
	//9104,reply_status,g_chat_id,co_id,op_id,sn_id,page_op_id
	_common.send("<M><C>9104;" + reply + ";" + chatGroupId + ";" + _setting.companyCodeReplace + ";" + opid + ";" + snid + ";" + pageid + "</C></M>");
}

/**
 * 初始化交谈组
 * @param HJWebClMsgStringMsg msg9112 服务器发送的初始化交谈组消息，格式如下：&lt;M>&lt;C>9112;errId;groupId;snid&lt;/C>&lt;R>&lt;F>交谈成员,交谈成员名称&lt;/F>&lt;/R>&lt;R>&lt;F>交谈纪录&lt;/F>&lt;/R>&lt;/M>
 * @see #arrChatGroups
 * @see #newChatInterface
 * @see #sendWelcome
 * @see #sendOperatorInfo
 */
function Chat_newChatGroup(msg9112) {
	var groupid = msg9112.commands[1];
	var snid = msg9112.commands[2];
	var pageid = "";
	var companyVersion = msg9112.commands[3]; //高级版、基础版等
	var sendWelcome = msg9112.commands[4];
	var chatRecords = new Array();
	if (msg9112.datas.length == 3) {
		chatRecords = msg9112.datas[2];
	}
	var group = new ChatGroup(groupid, snid);
	this.arrChatGroups.push(group);
	
	var id = snid.substring(3);
	while (id.length > 0 && id.substring(0, 1) == "0") {
		id = id.substring(1);
	}
	
	var chatName = "Chat";	
	for (var i = 0; i < msg9112.datas[0].length; i++) {
		var memberString = msg9112.datas[0][i];
		var arr = memberString.split(",");
		var type = 1;		
		var name = arr[1];
		if (arr[0].length > 4 && arr[0].substring(0,4) == "PAGE") {
			pageid = arr[0];
			type = 2;
			var aName = arr[1].split("~");
			if (aName[0] == id) name = id;//"访客";
			else name = aName[0];
			/*
			if (aName[1] != "") {
				if (aName[1] == id) name += "~" + "访客";
				else name += "~" + aName[1];				
			}
			*/
		}
		
		try {
			name = _urlCoder.decode(name, "UTF-8");
		} catch (eURI) {
			_common.alertDebug("系统产生一个异常:" + eURI);
		}
		
		if (arr[0] != _personSession.id) chatName = name;
		
		var member = new ChatMember(arr[0], name, type);
		group.members.push(member);
	}
	
	this.newChatInterface(group, snid, chatName);
	if (chatRecords.length > 0) {
		for (var i = 0; i < chatRecords.length; i++) {
			var record = chatRecords[i];
			if (record == "") continue;
			record = record.replace(/\+/g, " ");
			record = _urlCoder.decode(record, "UTF-8");
			var chatwin_msg_box_text = document.getElementById("chatwin_msg_box_text_" + groupid);
			var msgInDiv = document.createElement("div");
			msgInDiv.style.styleFloat = "left";
			msgInDiv.style.clear = "left";
			try {
				msgInDiv.style.width = chatwin_msg_box_text.clientWidth - 20;
			} catch (exc) {
				_common.alertDebug("系统产生一个异常:" + exc);
			}
			msgInDiv.innerHTML = record;
			chatwin_msg_box_text.insertBefore(msgInDiv, null);
			chatwin_msg_box_text.scrollTop = 10000000;
		}
	}
	//发送欢迎语
	this.sendWelcome(group.id, 0);
	this.sendOperatorInfo(snid, pageid);
}

/**
 * 发送客服信息，消息格式"&lt;M>&lt;C>9300;" + snid + ";" + pageid + ";4;" + _personSession.id + ";" + _personSession.nick + "|" + _personSession.position + "|" + _personSession.telephone + "|" + _personSession.phone + "|" + _personSession.email + "&lt;/C>&lt;D>&lt;/D>&lt;/M>"
 * @param String snid 访客ID
 * @param Srring pageid 访客页面ID
 */
function Chat_sendOperatorInfo(snid, pageid) {
	_common.send("<M><C>9300;" + snid + ";" + pageid + ";4;" + _personSession.id + ";" + _personSession.nick + "|" + _personSession.position + "|" + _personSession.telephone + "|" + _personSession.phone + "|" + _personSession.email + "</C><D></D></M>");
}

/**
 * 发送欢迎语，消息格式为："&lt;M>&lt;C>9105;"+ groupid +";" + sendType + ";" + _personSession.id + ";" + sendTo + ";" + _urlCoder.encode(text, "UTF-8") + "&lt;/C>&lt;/M>"
 * @param String groupid 交谈组ID
 * @param int type 欢迎语类型 0-问候语；1-道别语
 * @see #insertChatLog
 */
function Chat_sendWelcome(groupid, type) {
	var sendType = "0";
	var sendTo = "0";
	var msgDiv = document.getElementById("chatwin_putin_box_" + groupid);
	var text = "";
	if (type == 0) text = _personSession.hello;
	else if (type == 1) text = _personSession.bye;
	
	text = "<span style='font-family:" + this.font_family + "; font-style:" + this.font_style + "; font-size:" + this.font_size + "; text-decoration:" + this.text_decoration + "; font-weight:" + this.font_weight + "; color:" + this.font_color + "; line-height:100%'>" + text + "</span>";
	_common.send("<M><C>9105;"+ groupid +";" + sendType + ";" + _personSession.id + ";" + sendTo + ";" + _urlCoder.encode(text, "UTF-8") + "</C></M>");
	this.insertChatLog(groupid, _personSession.nick, text, sendType);
	try {		
		msgDiv.focus();
	} catch (fcEx) {
		_common.alertDebug("系统产生一个异常:" + fcEx);
	}
}

/**
 * 交谈输入窗口键盘触发，完成相应功能，屏蔽一些按键功能
 * <pre><code>
	if (event.ctrlKey && (event.keyCode != 90 && event.keyCode != 88 && event.keyCode != 86 && event.keyCode != 67)) {
		if (event.keyCode != 17) {
			return false;
		}
	}
	if (event.altKey) {
		return false;
	}
 * </code></pre>
 * 并根据发送方式，判断是否应该发送消息：event.keyCode == 13 && this.sendWay == 0 按Enter发送；event.keyCode == 13 && this.sendWay == 1 && (event.ctrlKey || event.shiftKey) 按Ctrl/Shift+Enter发送，否则在按下Enter键情况下执行换行
 * <pre><code>
	tR = document.selection.createRange();
	tR.text = "\r\n";
	tR.collapse(false);
	tR.select();
 * </code></pre>
 */
function Chat_divKeyDown() {
	if (event.keyCode == 13 && this.sendWay == 0){
		if (event.ctrlKey || event.shiftKey) {
			tR = document.selection.createRange();
 			tR.text = "\r\n";
			tR.collapse(false);
			tR.select();		
			return false;
		} else {
			_chat.sendMsg();
			return false;
		}
	} else {
		if (event.keyCode == 13 && this.sendWay == 1) {
			if (event.ctrlKey || event.shiftKey){
				_chat.sendMsg();
				return false;			
			} else {
				tR=document.selection.createRange();
 				tR.text = "\r\n";
				tR.collapse(false);
				tR.select();		
				return false;
			}		
		}
	} 
	
	//屏蔽一些键盘输入	
	if (event.ctrlKey && (event.keyCode != 90 && event.keyCode != 88 && event.keyCode != 86 && event.keyCode != 67)) {
		if (event.keyCode != 17) {
			return false;
		}
	}
	
	if (event.altKey) {
		return false;
	}
}

/**
 * 新建一个交谈界面
 * @param ChatGroup group 交谈组对象
 * @param String snid 访客ID
 * @param String viName 访客名
 * @see #resizeUI
 */
function Chat_newChatInterface(group, snid, viName) {
	var groupid = group.id;
	
	var data = {
		images_path : _setting.imagesPath,
		groupid		: groupid,
		viName		: viName
		};
	var strTitle = TrimPath.processDOMTemplate("chat_title_message_tpl", data);
	
	var newChatTitle = document.createElement("div");
	newChatTitle.id = "monitor_chatTitle_" + groupid;
	newChatTitle.innerHTML = '<div id="web_chat_title_' + groupid + '" class="web_chat_message">' + strTitle + '</div>';
	newChatTitle.style.styleFloat = "left";
	var monitor_chatTitle = document.getElementById("monitor_chatTitle");
	monitor_chatTitle.insertBefore(newChatTitle, null);	
	
	var enterCheck = "checked=\"checked\"";
	var ctrlCheck = "";
	if (this.sendWay == 1) {
		enterCheck = "";
		ctrlCheck = "checked=\"checked\"";
	}
	var data = {
		images_path : _setting.imagesPath,
		groupid		: groupid,
		enterCheck	: enterCheck,
		ctrlCheck	: ctrlCheck,
		_versionFlag: _versionFlag
		};
	var strMain = TrimPath.processDOMTemplate("chat_tpl", data);
	var newChatMain = document.createElement("div");
	newChatMain.innerHTML = strMain;
	var monitor_chat_chat = document.getElementById("monitor_chat_chat");
	monitor_chat_chat.insertBefore(newChatMain, null);	
	
	this.buildSendToSelect(group);
	if (this.currentGroup == null) this.showChatInterface(groupid);
	
	try {
		var monitor_chat = document.getElementById("monitor_chat");
		if (monitor_chat.style.display == "none") {
			monitor_chat.style.display = "";
		}
		_monitor.resizeUI();
	} catch (exc) {
		_common.alertDebug("系统产生一个异常:" + exc);
	}
}

/**
 * 改变交谈标题的显示布局。
 */
function Chat_resizeTitle() {
	var monitor_chatTitle = document.getElementById("monitor_chatTitle");
	var chat_closeAllDiv = document.getElementById("chat_closeAllDiv");
	var maxWidth = monitor_chatTitle.clientWidth - chat_closeAllDiv.clientWidth;
	var perWidth = Math.floor(maxWidth / this.arrChatGroups.length) - 40;
	if (perWidth <= 20) perWidth = 20;
	if (perWidth > 80) perWidth = 80;
	for (var i = 0; i < this.arrChatGroups.length; i++) {
		var obj = document.getElementById("chattitle_name_" + this.arrChatGroups[i].id);
		obj.style.width = perWidth;
	}
}

/**
 * 切换交谈标题风格
 * @param String style 交谈界面风格：wait-等待；ing-当前；message-有新的消息
 * @param String groupid 交谈组ID
 */
function Chat_changeChatTitleStyle(style, groupid) {
	var webChatTitle = document.getElementById("web_chat_title_" + groupid);
	if (!webChatTitle) return false;
	var viName = document.getElementById("chattitle_name_" + groupid).innerHTML;
	var data = {
		images_path : _setting.imagesPath,
		groupid		: groupid,
		viName		: viName
		};
	var strTitle = TrimPath.processDOMTemplate("chat_title_" + style + "_tpl", data);
	webChatTitle.innerHTML = strTitle;
	webChatTitle.className = "web_chat_" + style;
	this.resizeTitle();
}


/**
 * 显示组ID为groupid的交谈界面
 * @param String groupid 交谈组ID
 * @see Common#resizeInnerUI
 * @see #doStyleChange
 * @see #showChatMemberList
 * @see #resizeTitle
 */
function Chat_showChatInterface(groupid) {
	var interface = document.getElementById("monitor_chat_chat_" + groupid);
	var webChatTitle = document.getElementById("web_chat_title_" + groupid);
	if (interface) {
		if (this.currentGroup == null) {
			try {
				document.getElementById("monitor_chat_chat_0").style.display = "none";
			} catch (e) {
				_common.alertDebug("系统产生一个异常:" + e);
			}
		} else {
			document.getElementById("monitor_chat_chat_" + this.currentGroup.id).style.display = "none";
			//document.getElementById("web_chat_title_" + this.currentGroup.id).className = "web_chat_wait";
			this.changeChatTitleStyle('wait', this.currentGroup.id);
		}
		interface.style.display = "";
		this.changeChatTitleStyle('ing', groupid);
		var group = _common.getArrayObjByPropertyValue(this.arrChatGroups, "id", groupid);
		this.currentGroup = group;
	}
	
	var chatwin_msg_box_text = document.getElementById("chatwin_msg_box_text_" + groupid);
	chatwin_msg_box_text.scrollTop = 10000000;
	var msgDiv = document.getElementById("chatwin_putin_box_" + groupid);
	try {		
		msgDiv.focus();
	} catch (fcEx) {
		_common.alertDebug("系统产生一个异常:" + fcEx);
	}
	this.move2end("chatwin_putin_box_" + groupid);
	try {
		_common.resizeInnerUI();
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
	
	if (document.getElementById("sendType_0_" + groupid)) {
		if (this.sendWay == 0) document.getElementById("sendType_0_" + groupid).checked = true;
		else document.getElementById("sendType_1_" + groupid).checked = true;
	}
	
	this.doStyleChange();
	
	this.showChatMemberList(groupid);
	
	this.resizeTitle();
}


/**
 * 显示访客信息
 * @param String snid 访客ID
 * @param Object eve 按键事件
 * @see Monitor#showVisitorInfo
 */
function Chat_showVisitorInfo(snid, eve) {
	var fieldIndex = _common.findTableField (9070, 0, 0, snid, -1, "");
	var pageIndex = _common.lists.l9070[fieldIndex][22];
	var pageid = _common.lists.l9070[fieldIndex][1];
	_monitor.showVisitorInfo(pageIndex, snid, pageid, eve);
}

/**
 * 显示交谈成员列表
 * @param String groupid 聊天组ID
 */
function Chat_showChatMemberList(groupid) {
	var group = _common.getArrayObjByPropertyValue(this.arrChatGroups, "id", groupid);
	if (group == null) return false;
	var listDiv = document.getElementById("chatwin_id_list_" + groupid);
	var visitors = new Array();
	var operators = new Array();
	for (var i = 0; i < group.members.length; i++) {
		var member = group.members[i];
		if (member.type == 1) {
			var obj = {
				name : member.name
				};
			operators.push(obj);
		} else if (member.type == 2) {
			var obj = {
				id		: member.id,
				snid	: group.snid,
				name	: member.name
				};
			visitors.push(obj);
		}
	}
	var data = {
		images_path : _setting.imagesPath,
		visitors	: visitors,
		operators	: operators,
		_versionFlag:_versionFlag
		};
	var str = TrimPath.processDOMTemplate("chat_member_tpl", data);
	listDiv.innerHTML = str;
}

/**
 * 将光标置于输入内容最后
 * @param String id HTML输入框的ID
 */
function Chat_move2end(id) { 
	var obj = document.getElementById(id);
	var r = document.selection.createRange();
	r.moveStart('character', obj.innerHTML.length); 
	r.collapse(true); 
	r.select(); 
}

/**
 * 发送交谈消息
 * 消息格式：&lt;M>&lt;C>9105;groupid;type;fromid;toid;text&lt;/C>&lt;/M>
 * <pre><code>
 	//将直接打开的连接设置为在新窗口中打开
	var reg = /&lt;a href=(\S*?)>(.*?)&lt;\/a>/ig;
	text = text.replace(reg, "&lt;a href=$1 target=_blank>$2&lt;/a>");
 * </code></pre>
 */
function Chat_sendMsg() {
	var groupid = this.currentGroup.id;
	//var visitor = _common.getArrayObjByPropertyValue(this.currentGroup.members, "type", "2");
	//var snid = visitor.id;
	var sendTo = "0";
	try {
		sendTo = document.getElementById("chatwin_putin_send_to_" + groupid).value;
	} catch (exc) {
		_common.alertDebug("系统产生一个异常:" + exc);
	}
	var sendType = "0";
	if (sendTo != "0") sendType = "1"; 
	
	var msgDiv = document.getElementById("chatwin_putin_box_" + groupid);
	var text = msgDiv.innerHTML;
	if (text == "") {
		try {		
			msgDiv.focus();
		} catch (fcEx) {
			_common.alertDebug("系统产生一个异常:" + fcEx);
		}
		return;
	}
	msgDiv.innerHTML = "";
	
	/*
	var text = document.getElementById("chat_opMsg").value;
	document.getElementById("chat_opMsg").value = "";
	*/
	/*
	re = /&/g;							// 创建正则表达式模式。
	text = text.replace(re, "&amp;");	// 用 "&gt;" 替换 ">"。
	re = /"/g;							// 创建正则表达式模式。
	text = text.replace(re, "&quot;");	// 用 "&gt;" 替换 ">"
	re = /'/g;							// 创建正则表达式模式。
	text = text.replace(re, "&#039;");	// 用 "&gt;" 替换 ">"
	var re = /</g;						// 创建正则表达式模式。
	text = text.replace(re, "&lt;");	// 用 "&lt;" 替换 "<"。
	re = />/g;							// 创建正则表达式模式。
	text = text.replace(re, "&gt;");	// 用 "&gt;" 替换 ">"。
	*/
	var reg = /<a href=(\S*?)>(.*?)<\/a>/ig;
	text = text.replace(reg, "<a href=$1 target=_blank>$2</a>");
	text = "<span style='font-family:" + this.font_family + "; font-style:" + this.font_style + "; font-size:" + this.font_size + "; text-decoration:" + this.text_decoration + "; font-weight:" + this.font_weight + "; color:" + this.font_color + "; line-height:100%'>" + text + "</span>";
	_common.send("<M><C>9105;"+ groupid +";" + sendType + ";" + _personSession.id + ";" + sendTo + ";" + _urlCoder.encode(text, "UTF-8") + "</C></M>");
	this.insertChatLog(groupid, _personSession.nick, text, sendType);
	try {		
		msgDiv.focus();
	} catch (fcEx) {
		_common.alertDebug("系统产生一个异常:" + fcEx);
	}
}

/**
 * 插入交谈消息
 * @param String groupid 交谈组的ID
 * @param String fromname 发送者的名字
 * @param String text 交谈消息内容
 * @param int type 消息类型 1-悄悄话；0-普通交谈消息 
 */
function Chat_insertChatLog(groupid, fromname, text, type) {
	var chatwin_msg_box_text = document.getElementById("chatwin_msg_box_text_" + groupid);
	var msgInDiv = document.createElement("div");
	msgInDiv.style.styleFloat = "left";
	msgInDiv.style.clear = "left";
	try {
		msgInDiv.style.width = chatwin_msg_box_text.clientWidth - 20;
	} catch (exc) {
		_common.alertDebug("系统产生一个异常:" + exc);
	}
	var date = new Date();
	var hours = date.getHours();
	if (hours < 10) hours = "0" + hours;
	var minutes = date.getMinutes();
	if (minutes < 10) minutes = "0" + minutes; 
	var seconds = date.getSeconds()
	if (seconds < 10) seconds = "0" + seconds;
	var strSecret = "";
	if (type == "1") strSecret = _langPackage.chat.private;
	msgInDiv.innerHTML = hours + ":" + minutes + ":" + seconds + " [" + fromname + "] " + strSecret + ":<br />" + text;
	//将滚动条置于最下方
	chatwin_msg_box_text.insertBefore(msgInDiv, null);
	chatwin_msg_box_text.scrollTop = 10000000;
}


/**
 * 接受到服务器发送的交谈消息
 * @param HJWebClMsgStringMsg msg9105 消息格式 &lt;M>&lt;C>9105;groupid;消息类型(0,正常,1悄悄话);fromId;toId;text&lt;/C>&lt;/M>
 */
function Chat_receiveMsg(msg9105) {
	var groupid = msg9105.commands[0];
	var msgType = msg9105.commands[1];
	var fromid = msg9105.commands[2];
	var toid = msg9105.commands[3];
	var text = msg9105.commands[4];
	var fromname = "";
	
	var group = this.getGroupById(groupid);
	
	if (group == null) return false;
	
	for (var i = 0; i < group.members.length; i++) {
		if (group.members[i].id == fromid) {
			fromname = group.members[i].name;
			break;
		}
	}
	
	var rg = /\+/g;
	text = text.replace(rg, " ");
	this.insertChatLog(groupid, fromname, _urlCoder.decode(text, "UTF-8"), msgType);
	_common.soundPrompt(2);
	var webChatTitle = document.getElementById("web_chat_title_" + groupid);
	if (webChatTitle && webChatTitle.className == "web_chat_wait") {
		this.changeChatTitleStyle('message', groupid);
	}
}

/**
 * 收到服务器发送的 访客正在输入的内容
 * @param HJWebClMsgStringMsg msg9109 消息格式 &lt;M>&lt;C>9109;text&lt;/C>&lt;/M>
 */
function Chat_visitorPreMsg(msg9109) {
	var groupid = msg9109.commands[0];
	var msg = msg9109.commands[1];
	
	if (msg == null || msg == "null") msg = "";
	try {
		document.getElementById("chatwin_msg_box_predict_" + groupid).innerHTML = _urlCoder.decode(msg, "UTF-8");
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
}

/**
 * 根据交谈组ID获取交谈组对象
 * @param String groupid 交谈组的ID
 * @returns {@link ChatGroup}对象
 */
function Chat_getGroupById(groupid) {
	return _common.getArrayObject(this.arrChatGroups, "id", groupid);
}

/**
 * 往HTML Select中添加Option
 * @param Object objSelectNow HTML Select Object
 * @param String txt Option显示值
 * @param String val Option的Value
 * @param String s_txt Select的选中值
 */
function Chat_addOption(objSelectNow, txt, val, s_txt) {
	var objOption = document.createElement("OPTION");
	objOption.selected = "";
	objOption.text = txt;
	objOption.value = val;

	if (s_txt != "" && val == s_txt)  {	
		 objOption.selected = "selected";
	}
	objSelectNow.options.add(objOption);
}

/**
 * 设置交谈组发送至Select
 * @param ChatGroup group 交谈组对象
 */
function Chat_buildSendToSelect(group) {
	var groupid = group.id;
	try {
		var selectObj = document.getElementById("chatwin_putin_send_to_" + groupid);
		var selectValue = selectObj.value;
		while (selectObj.length > 0) {
			selectObj.remove(0);
		}
		this.addOption(selectObj, _langPackage.chat.toAll, "0", selectValue);
		for (var i = 0; i < group.members.length; i++) {
			var member = group.members[i];
			if (member.id != _personSession.id) this.addOption(selectObj, member.name, member.id, selectValue);
		}
	} catch(exc) {
		_common.alertDebug("系统产生一个异常:" + exc);
	}
}

/**
 * 交谈成员进入/退出
 * @param HJWebClMsgStringMsg msg9111 消息格式：&lt;M>&lt;C>9111;groupId;功能码(0,加入;1,退出);op_id;op_name&lt;/C>&lt;/M>
 * @see #getGroupById
 * @see #insertChatLog
 * @see #deleteMember
 * @see #changeChatTitleStyle
 * @see #showChatMemberList
 * @see #buildSendToSelect
 */
function Chat_memberInOut(msg9111) {
	var groupid = msg9111.commands[0];
	var inOut = msg9111.commands[1];
	var opid = msg9111.commands[2];
	var opname = msg9111.commands[3];
	
	var group = this.getGroupById(groupid);
	if (group == null) return false;
	
	var strInOut = "";
	if (inOut == "0") {
		strInOut = _langPackage.chat.joinChat;		
		var member = new ChatMember(opid, opname, 1);
		group.members.push(member);	
		this.insertChatLog(groupid, _langPackage.chat.systemInfo, opname + strInOut + _langPackage.chat.chat, "0");
	} else {
		strInOut = _langPackage.chat.leftChat;
	
		if (!opname || opname.name == "") {
			for (var i = 0; i < group.members.length; i++) {
				if (group.members[i].id == opid) {
					opname = group.members[i].name;
					break;
				}
			}
		}	
		this.insertChatLog(groupid, _langPackage.chat.systemInfo, opname + strInOut + _langPackage.chat.chat, "0");	
		this.deleteMember(groupid, opid);
	}
	
	var webChatTitle = document.getElementById("web_chat_title_" + groupid);
	if (webChatTitle && webChatTitle.className == "web_chat_wait") {
		this.changeChatTitleStyle('message', groupid);
	}
	
	this.showChatMemberList(groupid);
	this.buildSendToSelect(group);
}

/**
 * 删除交谈组成员
 * @param String groupid 交谈组ID
 * @param String meid 交谈组成员ID
 * @see #insertChatLog
 */
function Chat_deleteMember(groupid, meid) {
	var group = this.getGroupById(groupid);
	if (group == null) return false;
	for (i = 0; i < group.members.length; i++) {
		if (meid == group.members[i].id) {
			group.members = group.members.slice(0, i).concat(group.members.slice(i+1));
			break;
		}
	}
	if (group.members.length <= 1) {
		this.insertChatLog(groupid, _langPackage.chat.systemInfo, _langPackage.chat.allLeft + "<a href='#' onclick=\"_chat.closeChat('" + groupid + "');\">" + _langPackage.chat.closeWin + "</a>", "0");
	}
}

/**
 * 删除交谈组
 * @param String groupid 交谈组ID
 * @see #showChatInterface 
 */
function Chat_deleteGroup(groupid) {
	for (i = 0; i < this.arrChatGroups.length; i++) {
		if (groupid == this.arrChatGroups[i].id) {
			window.clearInterval(this.arrChatGroups[i].inputCheckTimer);
			this.arrChatGroups = this.arrChatGroups.slice(0, i).concat(this.arrChatGroups.slice(i+1));
			break;
		}
	}
	
	var lastId = 0;
	
	if (this.arrChatGroups.length > 0) {
		lastId = this.arrChatGroups[0].id;
		if (this.currentGroup.id == groupid) {
			this.currentGroup = this.getGroupById(lastId);
		}
	} else {
		this.currentGroup = null;
	}
	
	this.showChatInterface(lastId);
}

/**
 * 关闭交谈界面
 * @param String groupid 交谈组ID
 * @see #deleteGroup
 * @see #resizeTitle
 */
function Chat_closeChat(groupid) {
	var titleDiv = document.getElementById("monitor_chatTitle_" + groupid);
	titleDiv.removeNode(true);
	
	var mccDiv = document.getElementById("monitor_chat_chat_" + groupid);
	mccDiv.removeNode(true);
	this.deleteGroup(groupid);
	this.resizeTitle();
}

/**
 * 离开交谈
 * @param String groupid 交谈组ID
 * @see #sendWelcome
 * @see #closeChat
 */
function Chat_leaveChat(groupid) {
	if (window.confirm(_langPackage.chat.leaveConfirm)) {
		this.sendWelcome(groupid, 1);
		_common.send("<M><C>9106;" + groupid + "</C></M>");
		this.closeChat(groupid);
	}
}

/**
 * 改变字体
 * @param String str 设置字体的类型 'bold'-粗体；'italic'-斜体；'uline'-下划线
 * @see #doStyleChange
 */
function Chat_styleChange(str) {
	try {
		this.font_family = document.getElementById("chat_functions__font_font-family").value;
		this.font_size = document.getElementById("chat_functions__font_font-size").value;
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
	switch (str) {
		case 'bold':
			if (this.font_weight == "normal") {
				this.font_weight = "bold";
			} else {
				this.font_weight = "normal";
			}
			break;
		case 'italic':
			if (this.font_style == "normal") {
				this.font_style = "italic";
			} else {
				this.font_style = "normal";
			}
			break;
		case 'uline':
			if (this.text_decoration == "none") {
				this.text_decoration = "underline";
			} else {
				this.text_decoration = "none";
			}
			break;
	}
	this.doStyleChange();
}

/**
 * 将更改应用到msgDiv
 */
function Chat_doStyleChange() {
	try {
		var groupid = this.currentGroup.id;
		var msgDiv = document.getElementById("chatwin_putin_box_" + groupid);
		msgDiv.style.fontFamily = this.font_family;
		msgDiv.style.fontStyle = this.font_style;
		msgDiv.style.fontWeight = this.font_weight;
		msgDiv.style.fontSize = this.font_size;
		msgDiv.style.color = this.font_color;
		msgDiv.style.textDecoration = this.text_decoration;
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
}


/**
 * 设置字体颜色
 */
function Chat_selectColor() {
	var srcElem = event.srcElement;
	if (srcElem.tagName == "TD") {
		this.font_color = srcElem.bgColor;
		this.styleChange();
		document.getElementById("popDiv__list_1").innerHTML = "";
		document.getElementById("popDiv__list_1").style.display = "none";
	}
}

/**
 * 保存字体等设置到COOKIE
 * @see Common#clearPopDiv
 */
function Chat_saveFontSetting() {
	Cookie_set("HJWEBCL_FONT", this.font_family + "," + this.font_style + "," + this.font_weight + "," + this.font_size + "," + this.font_color + "," + this.text_decoration, 315636000);	
	_common.clearPopDiv();
}

/**
 * 应用字体
 * @see #doStyleChange
 * @see #displaySetting
 */
function Chat_loadFontSetting() {
	var hj_font = Cookie_get("HJWEBCL_FONT");
	if (hj_font == null || hj_font.length == 0) return;
	var ss = hj_font.split(",");
	if (ss.length != 6) return;
	this.font_family = ss[0];
	this.font_style = ss[1];
	this.font_weight = ss[2];
	this.font_size = ss[3];
	this.font_color = ss[4];
	this.text_decoration = ss[5];
	this.doStyleChange();
	this.displaySetting();
}


/**
 * 根据设置来设定字体选项选中值
 */
function Chat_displaySetting() {
	try {
		document.getElementById("chat_functions__font_font-family").value = this.font_family;
		document.getElementById("chat_functions__font_font-size").value = this.font_size;		
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
}

/**
 * 还原默认设置
 * @see #doStyleChange
 * @see #displaySetting
 * @see Common#clearPopDiv
 */
function Chat_defaultFontSetting() {
	this.font_family = "SIMSUN";
	this.font_style = "normal";
	this.font_weight = "normal";
	this.text_decoration = "none";
	this.font_size = "12px";
	this.font_color = "#000066";
	this.doStyleChange();
	this.displaySetting();	
	_common.clearPopDiv();
}

/**
 * 显示设置颜色Div
 */
function Chat_showColorDiv() {
	var oColorStr = new Array("00","33","66","99","cc","ff");
	var oColorStr_1 = new Array("00","33","66");
	var oColorStr_2 = new Array("99","cc","ff");
	var data = {
		oColorStr 	: oColorStr,
		oColorStr_1	: oColorStr_1,
		oColorStr_2	: oColorStr_2
		};
	var str = TrimPath.processDOMTemplate("color_tpl", data);
	
	var colorDiv = document.getElementById("popDiv__list_1");
	colorDiv.className = "";
	colorDiv.width = 214;
	var divLeft = event.x - 15;
	if (divLeft < 0) divLeft = 0;
	colorDiv.style.left = divLeft;	
	var divTop = event.y - 125;
	if (divTop < 0) divTop = 0;
	colorDiv.style.top = divTop;
	colorDiv.style.position = "absolute";
	colorDiv.style.display = "";
	colorDiv.innerHTML = str;
}

/**
 * 显示设置字体Div
 * @see #displaySetting
 */
function Chat_showFontDiv() {
	var str = TrimPath.processDOMTemplate("font_tpl", null);
	
	var fontDiv = document.getElementById("popDiv__list");
	fontDiv.className = "";
	var divLeft = event.x - 15;
	if (divLeft < 0) divLeft = 0;
	fontDiv.style.left = divLeft;	
	var divTop = event.y - 45;
	if (divTop < 0) divTop = 0;
	fontDiv.style.top = divTop;
	fontDiv.style.position = "absolute";
	fontDiv.style.display = "";
	fontDiv.innerHTML = str;
	this.displaySetting();
}

/**
 * 显示表情Div
 */
function Chat_showEmotionDiv() {
	var aId = new Array(
				new Array('101', '102', '103', '104', '105', '106', '107'),
				new Array('108', '109', '110', '111', '112', '201', '202'),
				new Array('203', '204', '205', '206', '207', '208', '209')
			);
	var data = {
		images_path	: _setting.imagesPath,
		aId			: aId
		};
	var str = TrimPath.processDOMTemplate("emotions_tpl", data);
	
	var faceDiv = document.getElementById("popDiv__list");
	faceDiv.className = "";
	var divLeft = event.x - 15;
	if (divLeft < 0) divLeft = 0;
	faceDiv.style.left = divLeft;	
	var divTop = event.y - 125;
	if (divTop < 0) divTop = 0;
	faceDiv.style.top = divTop;
	faceDiv.style.position = "absolute";
	faceDiv.style.display = "";
	faceDiv.innerHTML = str;
}

/**
 * 发送表情
 * @see Common#clearPopDiv
 * <pre><code>
var	tR = document.selection.createRange();	
tR.pasteHTML(str);
 * </code></pre>
 */
function Chat_sendFace(num) {
	var img_src = _setting.imagesPath + "face/"+ num +".gif";
	var str = "<span contentEditable=false><img src=" + img_src + " border=0 width=24 height=24 /></span>";
	var groupid = this.currentGroup.id;
	try {
		document.getElementById("chatwin_putin_box_" + groupid).focus();
	} catch (fcEx) {
		_common.alertDebug("系统产生一个异常:" + fcEx);
	}
	var	tR = document.selection.createRange();	
	tR.pasteHTML(str);
	_common.clearPopDiv();
}

/**
 * 显示发送连接Div
 */
function Chat_showLinkDiv() {
	var str = TrimPath.processDOMTemplate("links_tpl", null);
	var sendLinkDiv = document.getElementById("popDiv__list");
	sendLinkDiv.className = "";
	var divLeft = event.x - 110;
	if (divLeft < 0) divLeft = 0;
	sendLinkDiv.style.left = divLeft;	
	var divTop = event.y - 45;
	if (divTop < 0) divTop = 0;
	sendLinkDiv.style.top = divTop;
	sendLinkDiv.style.position = "absolute";
	sendLinkDiv.style.display = "";
	sendLinkDiv.innerHTML = str;
}


/**
 * 根据客服Id判断客服是否在当前交谈组中
 * @param String opid 待判断的客服ID
 * @see #currentGroup
 */
function Chat_opInCurrentGroup(opid) {
	if (this.currentGroup == null) return true;
	
	var members = this.currentGroup.members;
	for (var i = 0; i < members.length; i++) {
		if (members[i].type == 1 && members[i].id == opid) return true;
	}
	return false;
}

/**
 * 在交谈的时候邀请客服加入，消息格式"&lt;M>&lt;C>9108;" + this.currentGroup.id + ";" + opid + "&lt;/C>&lt;/M>"
 * @param String opid 待判断的客服ID
 */
function Chat_inviteOperatorWhenChating(opid) {
	_common.send("<M><C>9108;" + this.currentGroup.id + ";" + opid + "</C></M>");
}

/**
 * 显示邀请其他客服Div
 */
function Chat_showInviteOperatorDiv() {
	_common.clearPopDiv();
	var popDiv = document.getElementById("popDiv__list");

	var ops = new Array();
	var a = null;
	var bL = true;
	for (var i = 0; i < _operators.operators.length; i++) {
		var op = _operators.operators[i];
		if (op.status == "C") {
			if (this.opInCurrentGroup(op.id)) continue;
			if (bL) {
				a = new Array();
				var obj = {
					id	 : op.id,
					name : op.name
					};
				a[0] = obj;
				bL = false;
			} else {
				var obj = {
					id	 : op.id,
					name : op.name
					};
				a[1] = obj;
				ops.push(a);
				bL = true;
			}
		}
	}
	if (!bL) {
		ops.push(a);
	}
	
	var data = {
		images_path	: _setting.imagesPath,
		ops			: ops
		};
	var strOps = TrimPath.processDOMTemplate("ivop_tpl", data);
	
	popDiv.innerHTML = strOps;
	popDiv.className = "";
	popDiv.style.position = "absolute";
	var divLeft = event.x - 230;
	if (divLeft < 0) divLeft = 0;
	popDiv.style.left = divLeft;
	popDiv.style.top = event.y;
	popDiv.style.display = "";
}

/**
 * 发送链接
 * <pre><code>
var sl_url;
var sl_url1 = document.getElementById("chat_functions__linkType").value;
var sl_url2 = document.getElementById("chat_functions__linkSend").value;
if (sl_url1 != "mailto:") 	sl_url = "&lt;a href='" + sl_url1 + sl_url2 + "' target='_blank'>" + sl_url1 + sl_url2 + "&lt;/a>";
else sl_url = "&lt;a href='" + sl_url1 + sl_url2 + "' target='_blank'>" + sl_url2 + "&lt;/a>";
var groupid = this.currentGroup.id;
try {
	document.getElementById("chatwin_putin_box_" + groupid).focus();
} catch (fcEx) {
}
var	tR = document.selection.createRange();	
tR.pasteHTML(sl_url);
 * </code></pre>
 * @see Common#clearPopDiv
 */
function Chat_sendLink() {
	try {
		var sl_url;
		var sl_url1 = document.getElementById("chat_functions__linkType").value;
		var sl_url2 = document.getElementById("chat_functions__linkSend").value;
		if (sl_url1 != "mailto:") 	sl_url = "<a href='" + sl_url1 + sl_url2 + "' target='_blank'>" + sl_url1 + sl_url2 + "</a>";
		else sl_url = "<a href='" + sl_url1 + sl_url2 + "' target='_blank'>" + sl_url2 + "</a>";
		var groupid = this.currentGroup.id;
		try {
			document.getElementById("chatwin_putin_box_" + groupid).focus();
		} catch (fcEx) {
			_common.alertDebug("系统产生一个异常:" + fcEx);
		}
		var	tR = document.selection.createRange();	
		tR.pasteHTML(sl_url);
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
	
	_common.clearPopDiv();
}

/**
 * 查看连接
 */
function Chat_previewLink() {
	try {
		var pl_url = document.getElementById("chat_functions__linkType").value;
		pl_url += document.getElementById("chat_functions__linkSend").value;
		try {
			var f = window.open(pl_url, "_blank", "");
			f.focus();
		} catch(ex) {
			_common.alertDebug("系统产生一个异常:" + ex);
		}
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
}

/**
 * 显示发送文件Div
 */
function Chat_showFileDiv() {
}

/**
 * 发送交谈邀请给客服
 * @param String opid 待邀请的客服ID
 */
function Chat_sendChatRequestToOperator(opid) {
	_common.send("<M><C>9115;" + _setting.companyCodeReplace + ";" + opid + "</C></M>");
}

/**
 * 检查当前客服是否正在输入
 * 消息格式为：&lt;C>9107;交谈组ID;消息类型(0,文件发送;1,网页推送;2,修改访客名子;3,扩展功能开关);发送消息者ID;消息接收者ID;消息内容&lt;/C>
 * 此处使用："&lt;M>&lt;C>9107;" + groupid + ";3;" + _personSession.id + ";-1;1&lt;/C>&lt;/M>"正在输入；_common.send("&lt;M>&lt;C>9107;" + groupid + ";3;" + _personSession.id + ";0;0&lt;/C>&lt;/M>");停止输入
 * @param String groupid 交谈组ID
 */
function Chat_opInputCheck(groupid) {
	//alert("Chat_opInputCheck('" + groupid + "')");
	var group = this.getGroupById(groupid);
	if (group == null) return false;
	var textNow = document.getElementById("chatwin_putin_box_" + groupid).innerHTML;
	if (textNow != "" && group.inputCache != textNow) {
		group.inputCache = textNow;
		//<C>9107;交谈组ID;消息类型(0,文件发送;1,网页推送;2,修改访客名子;3,扩展功能开关);发送消息者ID;消息接收者ID;消息内容</C>
		_common.send("<M><C>9107;" + groupid + ";3;" + _personSession.id + ";-1;1</C></M>");
	} else {
		if (group.inputCache != "") _common.send("<M><C>9107;" + groupid + ";3;" + _personSession.id + ";0;0</C></M>");
		if (textNow == "") group.inputCache = "";
	}
}

/**
 * 插入预存消息
 * @param String text 预存内容
 */
function Chat_insertReserve(text) {
	if (this.currentGroup == null || this.currentGroup.id == 0) return false;
	try {
		var groupid = this.currentGroup.id;
		try {
			document.getElementById("chatwin_putin_box_" + groupid).focus();
		} catch (fcEx) {
			_common.alertDebug("系统产生一个异常:" + fcEx);
		}
		var	tR = document.selection.createRange();
		text = text.replace(/&amp;/g, "&").replace(/&quot;/g, "\"").replace(/&#039;/g, "'");
		tR.pasteHTML(text);
	} catch (e) {
		_common.alertDebug("系统产生一个异常:" + e);
	}
}

/**
 * 改变发送方式
 * @param int type 0-Enter发送；1-Ctrl+Enter发送
 */
function Chat_changeSendType(type) {
	if (this.sendWay == type) return false;
	else {
		this.sendWay = type;
		Cookie_set("HJWEBCL_SENDWAY", type, 365*24*60*60);
	}
}

/**
 * 发送一个文件到客户端
 * 消息格式：&lt;M>&lt;C>9107;交谈组ID;消息类型(0,文件发送;1,网页推送;2,修改访客名子;3,扩展功能开关);发送消息者ID;消息接收者ID;消息内容&lt;/C>&lt;/M>
 * 此处使用："&lt;M>&lt;C>9107;" + this.currentGroup.id + ";0;" + _personSession.id + ";;" + url + "&lt;/C>&lt;/M>"
 */
function Chat_sendFile(url) {
	//<M><C>9107;交谈组ID;消息类型(0,文件发送;1,网页推送;2,修改访客名子;3,扩展功能开关);发送消息者ID;消息接收者ID;消息内容</C></M>
	if (this.currentGroup == null || this.currentGroup.id == 0) return false;
	_common.send("<M><C>9107;" + this.currentGroup.id + ";0;" + _personSession.id + ";;" + url + "</C></M>");
	_common.clearPopDiv();
}

/**
 * 关闭所有交谈窗口
 */
function Chat_closeAll() {
	if (window.confirm(_langPackage.chat.closeAllConfirm)) {
		while (this.arrChatGroups.length > 0) {
			var groupid = this.arrChatGroups[0].id;
			this.sendWelcome(groupid, 1);
			_common.send("<M><C>9106;" + groupid + "</C></M>");
			this.closeChat(groupid);
		}
	}
}

var _chat = new Chat();
_chat.loadFontSetting();
var cookiesendway = Cookie_get("HJWEBCL_SENDWAY");
if (cookiesendway == null) cookiesendway = 0;
else cookiesendway = parseInt(cookiesendway);
_chat.sendWay = cookiesendway;
//-->