
/* WeCaller guest.js  @Copyright weensoft.cn */

//显示大图片
function showImage(me, width, height){
	return;
}

//根据select设置对象显示title
function showTitle(select, position){
	if(!position || position != "left") position = "right";

	$(select).mouseover(function (e) {
		if(!this.title) return;
		this.Mytitle = this.title;
		this.title = "";
		$("body").append("<div id='welive_div_toop' style='border: 1px solid #000;background:#ffff00;padding:2px 3px;'>" + this.Mytitle + "</div>");

		if(position == "right"){
			$("#welive_div_toop").css({"top": (e.pageY - 25) + "px","position": "absolute","left": (e.pageX + 10) + "px"}).show("fast");
		}else{
			$("#welive_div_toop").css({"top": (e.pageY - 25) + "px","position": "absolute","right": (350 - e.pageX) + "px"}).show("fast");
		}

	}).mouseout(function () {

		if(!this.Mytitle) return;
		this.title = this.Mytitle;
		$("#welive_div_toop").remove();

	}).mousemove(function (e) {
		if(position == "right"){
			$("#welive_div_toop").css({"top": (e.pageY - 25) + "px","position": "absolute","left": (e.pageX + 10) + "px"}).show("fast");
		}else{
			$("#welive_div_toop").css({"top": (e.pageY - 25) + "px","position": "absolute","right": (350 - e.pageX) + "px"}).show("fast");
		}
	});
}

//JQ闪动特效  ele: JQ要闪动的对象; cls: 闪动的类(className); times: 闪动次数
function eleShake(ele, cls, times){
	var i = 0, t = false, o = ele.attr("class")+" ", c = "", times = times||3;
	if(t) return;
	t= setInterval(function(){
		i++;
		c = i%2 ? o+cls : o;
		ele.attr("class",c);
		if(i==2*times){
			clearInterval(t);
			ele.removeClass(cls);
		}
	},200);
}

//滚动到底部
function scrollBottom(){
	historier.scrollTop(20000); //滚动到底部
}

//Ajax封装
var ajax_isOk = 1;
function ajax(url, send_data, callback) {
	if(!ajax_isOk) return false;
	$.ajax({
		url: url,
		data: send_data,
		type: "post",
		cache: false,
		dataType: "json",
		beforeSend: function(){ajax_isOk = 0;},
		complete: function(){ajax_isOk = 1;},
		success: function(data){
			if(callback)	callback(data);
		},
		error: function(XHR, Status, Error) {
			welive.status = 1;
			file_temp_data = "";
			layer.msg('ajax error!', {time: 8000});
		}
	});
}

//设置cookie
function setCookie(n,val,d) {
	var e = "";
	if(d) {
		var dt = new Date();
		dt.setTime(dt.getTime() + parseInt(d)*24*60*60*1000);
		e = "; expires="+dt.toGMTString();
	}
	document.cookie = n+"="+val+e+"; path=/";
}

//获取cookie
function getCookie(n) {
	var a = document.cookie.match(new RegExp("(^| )" + n + "=([^;]*)(;|$)"));
	if (a != null) return a[2];
	return '';
}

//将json数据转换成json对象
function parseJSON(data) {
	if(window.JSON && window.JSON.parse) return window.JSON.parse(data);
	if(data === null) return data;
	if(typeof data === "string") {
		data = $.trim(data);
		if(data) {
			var rvalidchars = /^[\],:{}\s]*$/,
				rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
				rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
				rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g;

			if(rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {
				return (new Function("return " + data))();
			}
		}
	}
	return false;
}

//新消息闪动页面标题
function flashTitle() {
	clearInterval(ttt_3);
	flashtitle_step=1;
	ttt_3 = setInterval(function(){
		if (flashtitle_step==1) {
			welive_cprt.addClass("hover");
			document.title='【' + langs.msg + '】'+pagetitle;
			flashtitle_step=2;
		}else{
			welive_cprt.removeClass("hover");
			document.title='【　　　】'+pagetitle;
			flashtitle_step=1;
		}
	}, 500);
}

//停止闪动页面标题
function stopFlashTitle() {
	if(flashtitle_step != 0){
		flashtitle_step=0;
		clearInterval(ttt_3);
		welive_cprt.removeClass("hover");
		document.title=pagetitle;
	}
}

//获得计算机当前时间
function getLocalTime() {
	var date = new Date();

	function addZeros(value, len) {
		var i;
		value = "" + value;
		if (value.length < len) {
			for (i=0; i<(len-value.length); i++)
				value = "0" + value;
		}
		return value;
	}
	return addZeros(date.getHours(), 2) + ':' + addZeros(date.getMinutes(), 2) + ':' + addZeros(date.getSeconds(), 2);
}

//格式化输出信息
function formatOutput(data) {
	//生成URL链接
	data = data.replace(/((((https?|ftp):\/\/)|www\.)([\w\-]+\.)+[\w\.\/=\?%\-&~\':+!#;]*)/ig, function($1){return getURL($1);});
	//将表情代码换成图标路径
	data = data.replace(/\[:(\d*):\]/g, '<img src="' + SYSDIR + 'public/smilies/$1.png">').replace(/\\n/g, '<br>').replace(/\n/g, '<br>');
	return data;
}

//格式化生成URL
function getURL(url, limit) {
	if(!limit) limit = 60;
	var urllink = '<a href="' + (url.substr(0, 4).toLowerCase() == 'www.' ? 'http://' + url : url) + '" target="_blank" title="' + url + '">';
	if(url.length > limit) {
		url = url.substr(0, 30) + ' ... ' + url.substr(url.length - 18);
	}
	urllink += url + '</a>';
	return urllink;
}

//插入表情符号
function insertSmilie(code) {
	code = '[:' + code + ':]';
	var obj = msger[0];

	var selection = document.selection;
	obj.focus();

	if(typeof obj.selectionStart != 'undefined') {
		var opn = obj.selectionStart + 0;
		obj.value = obj.value.substr(0, obj.selectionStart) + code + obj.value.substr(obj.selectionEnd);
	} else if(selection && selection.createRange) {
		var sel = selection.createRange();
		sel.text = code;
		sel.moveStart('character', -code.length);
	} else {
		obj.value += code;
	}
}


//socket连接
function weliveLink(){
	welive.ws = new WebSocket(WS_HEAD + WS_HOST + ':'+ WS_PORT);
	welive.ws.onopen = function(){setTimeout(function(){weliveVerify();}, 100);}; //连接成功后, 小延时再验证用户, 否则IE下刷新时发送数据失败
	welive.ws.onclose = function(){weliveClose();};
	welive.ws.onmessage = function(get){weliveParseOut(get);};
}


//记住访客id, 排队票号tn, 上传session会话
function rememberGuest(gid, tn, sess){
	gid = parseInt(gid);

	if(!guest.gid || guest.gid != gid){
		guest.gid = gid; //更新ID号
		setCookie(COOKIE_USER, gid, 365); //写cookie
	}

	//记住排队票号
	setCookie(COOKIE_USER + "_tn", tn, 0); //随进程消失, 用于刷新等断线重连的情况下回传

	//产生一个session会话记录, 用于验证上传图片等, 以免产生非法操作
	guest.sess = sess; //解决safari禁止第三方cookie的问题
	setCookie(COOKIE_USER + "_sess", sess, 0); //随进程消失, 上传文件等时首先验证
}


//输出聊天记录
function outputRecords(reArr){
	var recs = '';
	$.each(reArr, function(i, rec){
		if(rec.ft == 1){//上传图片记录
			var img_arr = rec.m.split("|");
			var img_w = parseInt(img_arr[1]);
			var img_h = parseInt(img_arr[2]);

			if(img_w < 1) img_w = 1;
			var new_h = parseInt(img_h * 250 / img_w); //CSS样式中已确定宽度为250

			var rec_i = '<div class="sending_div" style="height:' + new_h + 'px;"><img src="' + SYSDIR + "upload/img/" + img_arr[0] + '" class="sending_img" onclick="showImage(this, ' + img_w + ', ' + img_h + ');"></div>';

		}else if(rec.ft == 2){ //上传的文件记录
			var file_arr = rec.m.split("|");

			if(rec.t == 1){ //客服的
				var rec_i = '<a href="' + SYSDIR + 'upload/file/' + file_arr[0] + '" target="_blank" download="' + file_arr[1] + '" class="down"><img src="' + SYSDIR + 'public/img/save.png">&nbsp;&nbsp;' + langs.click_download +  file_arr[1] + '</a>';
			}else{ //自己的
				var rec_i = file_arr[1] + "<br>... " + langs.upload_done;
			}
		}else{
			var rec_i = formatOutput(rec.m);
		}

		if(rec.t == 1){ //客服的
			if(rec.fid == guest.aid){
				var welive_duty_i = welive_duty;
			}else{
				var welive_duty_i = langs.wecaller;
			}

			recs += '<div class="msg l"><div class="a">' +  rec.f + ' - ' + welive_duty_i + '<i>' + rec.d + '</i></div><b></b><div class="b"><div class="i">' + rec_i + '</div></div></div>';

		}else{ //自己的

			recs += '<div class="msg r"><b></b><div class="b"><div class="i">' + rec_i + '</div></div><i>' + rec.d + '</i></div>';
		}
	});

	if(recs != '') {
		recs += '<div class="msg s"><div class="b"><div class="i">' + langs.records + '</div></div></div>';
		historier.append(recs); //输出
		scrollBottom(); //滚动到底部
	}
}


//解析数据并输出
function weliveParseOut(get){
	var d = false, type = 0, data = parseJSON(get.data);
	if(!data) return; //没有数据返回

	switch(data.x){

		case 5: //客人与客服文字对话
			if(data.a == 1){ //客服发来的
				welive.flashTitle = 1;
				type = 1; d = data.i;

				//机器人工作时
				if(welive.isRobot){
					historier.find("s.un").html(langs.readed).removeClass("un");

					setTimeout(function() {
						welive.status = 1; //机器人回复输出后才能发送第二条
						if(typeof data.av != 'undefined' && data.av != ''){
							clearTimeout(ttt_5);
							toggleAvatar(data.av); //变换头像

							ttt_5 = setTimeout(function() {
								welive_op.find("#welive_avatar").attr("src", SYSDIR + "avatar/robot/0.png");
							}, 30000); //30秒后头像恢复
						}

						historier.children(".robot_typing").remove(); //清除机器人思考标志
						weliveOutput(d, type); //输出

					}, 1000); //信息延迟显示

					return;
				}
			}else{ //自己发出的对话
				type = 2; 
				if(!welive.isRobot) welive.status = 1; //发送完成允许发送第二条信息

				d = welive.msg.replace(/</g, "&lt;").replace(/>/g, "&gt;"); //防止自己发js代码时发生显示错误
				welive.msg = ''; //清空临时信息

				sender.removeClass('loading2');
			}

			break;

		case 4: //webRTC

			var event = data.e;
			var msg = data.m;

			//此事件在audioStatusOk前
			if(event == "audio_status_ok"){
				weliveCallStart(); //开始语音通话, 由客服发来的语音准备状态触发
				return;
			}

			if(!audioStatusOk) return; //实时语音状态未OK

			switch(event) {

				case 'client-audio-offer': //访客收到客服发来的offer后
					if(!userAudioStream || !msg) return;

					applyAudioIceCandidate(userAudioStream, msg); //申请ICE

					break;

				case 'client-audio-candidate': //请求方与接收方互传: candidate传输地址
					if(!peerAudioConnection || !msg || !msg.candidate) return;

					//添加对方的candidate
					peerAudioConnection.addIceCandidate(new RTCIceCandidate(msg), function(){}, function(e){
						console.error(e);
					});

					break;

				//////// 视频相关

				case 'client-video-start': //访客收到视频开始指令后
					if(!userVideoStream) return;
					applyVideoIceCandidate(userVideoStream);

					break;

				case 'client-video-answer': //访客收到客服应答后
					if(!peerVideoConnection || !msg || !msg.sdp) return;

					peerVideoConnection.setRemoteDescription(new RTCSessionDescription(msg), function(){}, function(e){
						console.error(e);
					});

					break;

				case 'client-video-candidate': //访客收到: candidate传输地址
					if(!peerVideoConnection || !msg || !msg.candidate) return;
					//添加对方的candidate
					peerVideoConnection.addIceCandidate(new RTCIceCandidate(msg), function(){}, function(e){
						console.error(e);
					});

					break;

				case 'client-camera-close': //客服关闭摄像头
					stopVideo();
					$("#toolbar_camera").removeClass("camera_on");

					break;
			}

			return true;
			break;

		case 3: //客服接通或挂断电话时返回

			if(data.a == 1){ //接通

				guest.aid = parseInt(data.aid); //客服aid
				if(!guest.aid) return false;

				welive.isRobot = 0;
				welive.isCalling = 1; //客服通话中

				 //更客服头像及身份
				welive_name = data.an;
				welive_duty = data.p;
				welive_op.find("#welive_name").html(welive_name);
				welive_op.find("#welive_duty").html(welive_duty);
				//welive_op.find("#welive_avatar").attr("src", SYSDIR + "avatar/" + data.av);
				toggleAvatar(data.av); //变换头像

				guest.sess = data.sess; //解决safari禁止第三方cookie的问题
				setCookie(COOKIE_USER + "_sess", data.sess, 0); //随进程消失, 上传文件等时首先验证

				historier.html(""); //清除与机器人的对话记录
				msger.html("").focus(); //清除输入框, 获焦点

				outputRecords(data.recs); //输出对话记录
				updateCallingStatus("calling");

				welive.flashTitle = 1;
				if(welive.sound) sounder.html(welive.ring); //发出电话铃声
				type = 3; d = welive_name + " " + langs.pickup_info;

			}else if(data.a == 3){ //挂断
				welive.status = 0;
				welive.autolink = 0; //不允许重连
				welive.closeQuiet = 1; //连接断开时无消息
				type = 3; d =  langs.call_end_info;

				guest.tw = 0;
				guest.aid = 0;
				welive.isRobot = 1;
				welive.isCalling = 0; //未通话中

				updateCallingStatus("callend");

				//取号作废
				guest.tn = 0;
				setCookie(COOKIE_USER + "_tn", 0, 0);
			}

			break;

		case 6: //客人特别操作或返回信息
			switch(data.a){

				case 8: //客人登录成功
					welive.linked = 1; //连接成功
					welive.status = 1; //允许发信息
					welive.autolink = 1; //允许自动重连
					welive_relink_times = 7;

					//配置iceConfig
					var iceArr = [];
					iceArr.push({urls: "stun:" + data.ice.stun});

					if(data.ice.turn != ''){
						iceArr.push({urls: "turn:" + data.ice.turn, username: data.ice.user, credential: data.ice.pass});
					}

					iceConfig = {iceServers: iceArr, sdpSemantics: 'plan-b'};

					//客服aid(未接通电话时为0)
					guest.aid = parseInt(data.aid);

					if(guest.aid){
						welive.isRobot = 0;
						welive.isCalling = 1; //客服通话中
					}else{
						welive.isRobot = 1; //机器人服务中
						welive.isCalling = 0;
					}

					guest.fn = data.fn; //客人姓名
					guest.tn = parseInt(data.tn); //访客排队取号的号码
					guest.tw = parseInt(data.tw); //访客排队取号后还需要等待多少

					 //更客服头像及身份
					welive_name = data.an;
					welive_duty = data.p;
					welive_op.find("#welive_avatar").attr("src", SYSDIR + "avatar/" + data.av);
					welive_op.find("#welive_name").html(welive_name);
					welive_op.find("#welive_duty").html(welive_duty);

					//去掉loading样式
					historier.removeClass('loading3');

					msger.focus();
					welive.flashTitle = 1;
					type = 8; d = welcome;

					var info = "";

					//连接成功
					if(guest.aid){ //此前正在通话中(断线重连, 非重复连接)

						type = 3; d = welive_name + " " + langs.pickup_info;

						if(!guest.sess) outputRecords(data.recs); //离开过当前页面的断线重连, 输出对话记录

						$(".ticket_no").html(langs.ticket_no.replace(/xxxx/ig, guest.tn));
						toolbar_ticket.animate({height:"50px"}, 2000);
						updateCallingStatus("calling");

					}else if(guest.tn){ //已取号(新连接、断线重连或重复连接)

						info = langs.connected.replace(/xxxx/ig, guest.tn).replace(/yyyy/ig, guest.tw);
						$(".ticket_no").html(langs.ticket_no.replace(/xxxx/ig, guest.tn));

						toolbar_ticket.animate({height:"50px"}, 2000);
						updateCallingStatus();

					}else{ //未取号

						info = langs.robotworking;
						autoOffline(); //未取号时启动自动离线
					}

					if(info) historier.append('<div class="msg s"><div class="b"><div class="i">' + info + '</div></div></div>');

					//记住访客id, 排队票号tn, 上传session会话
					rememberGuest(data.gid, guest.tn, data.sess);

					//启动心跳, 即每隔26秒自动发送一个特殊信息, 解决IE下30秒自动断线的问题
					//设置一个怪异的数字避免与自动离线的时间间隔重合, 避免在同一时间点上send数据时, 可能产生-----幽灵bug
					ttt_1 = setInterval(function() {
						weliveSend({type: "ping"});
					}, 26125);

					break;

				case 1: //客服重新上线
					welive.status = 1;
					welive.flashTitle = 1;
					welive.isCalling = 1; //通话中
					if(welive.sound) sounder.html(welive.ring); //发出电话铃声
					updateCallingStatus("calling");
					type = 3; d = welive_name + langs.aback;

					break;

				case 2: //客服离线
					welive.flashTitle = 1;
					welive.status = 0;
					welive.isCalling = 0; //通话中断
					updateCallingStatus("call_break");
					type = 4; d = welive_name + langs.offline;

					break;

				case 4: //重复连接返回的指令
					welive.status = 0;
					welive.autolink = 0; //不允许自动重连
					welive.flashTitle = 1;
					welive.closeQuiet = 1; //连接断开时无消息
					type = 4;

					d = langs.relinked + '<br><a onclick="weliveLink();$(this).parents(\'.msg\').hide();return false;" class="relink">' + langs.rebtn + '</a>';

					break;

				case 5: //客人自动离线返回的通知
					welive.status = 0;
					welive.autolink = 0; //不允许自动重连
					welive.flashTitle = 1;
					welive.closeQuiet = 1; //连接断开时无消息
					type = 4;

					d = langs.autooff + '<br><a onclick="weliveLink();$(this).parents(\'.msg\').hide();return false;" class="relink">' + langs.rebtn + '</a>';

					break;

				case 6: //更新排队等候人数
					welive.flashTitle = 1;
					guest.tw = parseInt(data.tw);
					type = 3; d = langs.ticket_wait.replace(/xxxx/ig, guest.tw);
					updateCallingStatus();

					break;

				case 7: //评价返回

					msger.focus();

					if(data.s == "1"){
						welive.flashTitle = 1;
						type = 1; d = '<font color=red>' + langs.rating_thanks + '</font>[:16:]';
					}else{
						layer.msg(langs.rating_limit, {time: 6000});
						return false;
					}

					break;

				case 9: //客服组不存在且不自动转接, 正在通话而又重复连接, 排队取号失败等
					welive.status = 0;
					welive.autolink = 0; //不允许自动重连

					type = 4;
					welive.flashTitle = 1;
					welive.closeQuiet = 1; //连接断开时无消息

					//在socket关闭时输出消息
					switch(data.i){
						case "noGroup":
							d =  langs.team_off;
							break;
						case "isCalling":
							d =  langs.repeat_call;
							break;
						case "noTicket":
							d =  langs.no_ticket;
							break;
					}

					break;
			}

			break;
	}

	weliveOutput(d, type); //输出
}

//交流输出信息
function weliveOutput(d, type){
	if(d === false || !type) return; //没有信息及类型返回

	if(welive.flashTitle){
		flashTitle();
		if(welive.sound && !welive.isCalling) sounder.html(welive.mp3); //通话时无声音
		welive.flashTitle = 0;
	}

	switch(type){
		case 1: //客服
			d = '<div class="msg l"><div class="a">' + welive_name + ' - ' + welive_duty + '<i>' + getLocalTime() + '</i></div><b></b><div class="b"><div class="i">' + formatOutput(d) + '</div></div></div>';
			break;
		case 2: //客人
			d = '<div class="msg r"><b></b><div class="b"><div class="i">' + formatOutput(d) + '</div></div><i>' + getLocalTime() + '<br><s class="un">' + (welive.isRobot ? langs.unread : '') + '</s></i></div>';
			break;
		case 3: //正常提示
			d = '<div class="msg s"><div class="b"><div class="i">' + d + '</div></div></div>';
			break;
		case 4: //错误提示
			d = '<div class="msg e"><div class="b"><div class="i">' + d + '</div></div></div>';
			break;
		case 8: //问候语, 信息不解析(支持html)
			d = '<div class="msg l"><div class="a">' + welive_name + ' - ' + welive_duty + '<i>' + getLocalTime() + '</i></div><b></b><div class="b"><div class="i">' + d + '</div></div></div>';
			break;
	}

	historier.append(d);

	//机器人工作时, 访客发送的信息显示后, 添加机器思考标志
	if(type == 2 && welive.isRobot){
		historier.children(".robot_typing").remove();
		d = '<div class="msg l robot_typing"><div class="a">' + welive_name + ' - ' + welive_duty + '<i></i></div><b></b><div class="b"><div class="i"></div></div></div>';
		historier.append(d);
	}

	scrollBottom(); //滚动到底部
}


//更新访客通话状态及等候人数等
function updateCallingStatus(mod) {
	switch(mod){
		case "calling":
			ticket_waitings.removeClass("callend").addClass("calling").html(langs.calling);
			break;
		case "callend":
			weliveCallStop(); //语音中断
			ticket_waitings.removeClass("calling").addClass("callend").html(langs.call_end);
			break;
		case "call_break":
			weliveCallStop(); //语音中断
			ticket_waitings.removeClass("calling").addClass("callend").html(langs.call_break);
			break;
		default:
			ticket_waitings.html("" + guest.tw); //jquery1.2.6的bug不输出0
			break;
	}

	eleShake(ticket_waitings, "tw_shake", 8); //闪动8次
}


//变换头像
function toggleAvatar(av) {
	history_wrap.append('<div class="animate_avatar"><img src="' + SYSDIR + "avatar/" + av + '"></div>');
	$(".animate_avatar").animate({left:0, bottom: (history_wrap.height() + 120) + "px"}, 300, "", function(){
		$(this).remove();
		welive_op.find("#welive_avatar").attr("src", SYSDIR + "avatar/" + av);
	});
}


//访客连接验证
function weliveVerify(){
	welive.linked = 1; //websocket已连接
	weliveSend({type: "login", from: "front", gid: guest.gid, grid: guest.grid, oid: guest.oid, tn: guest.tn, fn: guest.fn, lang: guest.lang, key: SYSKEY, code: SYSCODE, fromurl: guest.fromurl, agent: guest.agent, mobile: 0});
}

//连接断开时执行
function weliveClose(){
	welive.status = 0; //不允许发信息
	welive.linked = 0; //标记连接失败
	clearInterval(ttt_1); //连接断开后停止发送心跳数据

	if(welive.isCalling){
		weliveCallStop(); //停止通话
		welive.isCalling = 0; //设置为未通话状态
	}

	//允许重连时
	if(welive.autolink && welive_relink_times > 0){
		welive_relink_times -= 1;
		weliveOutput(langs.failed, 4);
		setTimeout(function(){weliveLink();}, 6000); //6秒后自动重连
		return false;
	}

	//不允许重连时
	historier.removeClass('loading3');
	if(welive.closeQuiet){
		welive.closeQuiet = 0;
	}else{
		weliveOutput(langs.link_failed, 4);
	}
}


//发送信息(直接)
function weliveSend(d){
	var re = 0;

	if(welive.linked){
		re = 1;
		welive.ws.send(JSON.stringify(d)); //将json对象转换成字符串发送
	}else{
		layer.msg(langs.notconnected);
	}

	return re; //回返是否成功
}

//发送信息
function weliveSendMsg(){
	if(welive.status) {
		var msg = $.trim(msger.val());

		if(msg){
			if(msg.length > 2048){
				layer.msg(langs.msg_too_long);
				return false;
			}

			sender.addClass('loading2');
			welive.msg = msg; //先记录客人的发言

			msg = {type: "msg", sendto: "back", msg: msg};
			if(!weliveSend(msg)) return false;

			welive.status = 0; //发送后，改变状态避免未完成时发送第二条信息
			autoOffline(); //信息发送完成后, 自动离线计时开始
		}else{
			layer.msg(langs.notinput);
		}

		msger.val('');
	}else{
		layer.msg(langs.notready);
	}

	msger.focus(); //输入框焦点
}

//自动离线
function autoOffline(){
	if(!welive.linked || guest.tn) return; //未连接或已取号(包括通话中)不自动离线
	if(welive.ttt) clearTimeout(welive.ttt);//清除自动离线

	welive.ttt = setTimeout(function(){
		//未排队未领号时, 发送离线请求
		if(guest.tn <= 0) weliveSend({type: "g_handle", operate: "offline"});
	}, offline_time);
}


//发送服务评价
function sendEvaluate(){
	if(!welive.linked){
		layer.msg(langs.notconnected);
		return false;
	}

	if(rating_star == 0){
		layer.msg(langs.select_star);
		return false;
	}

	$("#starRating").hide();
	var msg = $.trim($("#rating_advise").val());

	if(msg.length > 600){
		layer.msg(langs.too_long);
		return false;
	}

	weliveSend({type: "g_handle", operate: "rating", star: rating_star, msg: msg});
}

//设置发送信息按钮模式
function setSendMod(mod, me){
	if(mod == send_btn_mod) return;
	send_btn_mod = mod;
	$(me).parent().children().removeClass("curr_send_mod").eq(mod).addClass("curr_send_mod");

	setCookie(COOKIE_USER + "_sbm", mod, 1000);
}

//调整操作区DIV高度等
function resizeOperateArea(){
	window_width =$(window).width();
	window_height =$(window).height();

	var main_div = $(".main");
	var main_div_height = 780;

	if((window_height - main_div_height) < 4){
		main_div_height = window_height - 4;
	}
	$(".top_div").css({"height": (main_div_height - 30) + "px"});
	main_div.css({"top": (window_height - main_div_height)/2 + "px"});

	scrollBottom();
}


//webRTC语音视频 start
//开始语音通话
function weliveCallStart(){
	if(audioStatusOk) return;

	if(!userNavigator.getUserMedia){
		weliveSend({type: "webrtc", event: "client-call-stop", msg: ""}); //通话客服关闭通话
		layer.msg(langs.not_support_rtc, {time: 6000});
		return false;
	}

	userNavigator.getUserMedia({
        audio:{
			noiseSuppression: true, // 降噪
			echoCancellation: true, // 回音消除
			autoGainControl: true, //自动增益
			channelCount: 1, //单声道, 否则有噪音
			volume: 1.0
		}
	}).then(function(stream){
		wRecordWaver.fadeIn(500); //麦克风波形先显示

		userAudioStream = stream;

		audioStatusOk = 1; //语音通话已准备OK

		//访客发起语音连线请求
		weliveSend({type: "webrtc", event: "client-call", msg: ""});

		$("#toolbar_camera").show(); //摄像头按钮

	}).catch(function(e){
		weliveSend({type: "webrtc", event: "client-call-stop", msg: ""}); //通话客服关闭通话
		layer.msg(langs.not_auth_mic, {time: 6000});
	});
}

//停止通话
function weliveCallStop(){
	audioStatusOk = 0;

	if(userAudioStream){
		userAudioStream.stop();
		userAudioStream = null;

		wRecordWaver.fadeOut(500);
		$("#toolbar_camera").removeClass("camera_on").hide(); //摄像头按钮
	}

	if(peerAudioConnection){
		peerAudioConnection.close();
		peerAudioConnection = null;

		try{ //避免DOM权限报错
			voicePlayer.srcObject = null;
		}catch(e){}
	}

	stopVideo(); //终止视频
}

//发起音频ice申请(NAT穿透服务器)
function applyAudioIceCandidate(stream, offer){
    const rtcPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
	peerAudioConnection = new rtcPeerConnection(iceConfig); //连接

	peerAudioConnection.onicecandidate = function(event){
		if(event.candidate) {
			//将ice申请结果发送给对方
			weliveSend({type: "webrtc", event: "client-audio-candidate", msg: event.candidate});
		}
	};

	//使用addTrack 和 ontrack, addStream 和 onaddstream 将被废弃
	if(typeof peerAudioConnection.addTrack == 'function'){
		peerAudioConnection.ontrack = function(e){
			voicePlayer.srcObject = e.streams[0];
			voicePlayer.muted = false;
			voicePlayer.play();
		};

		peerAudioConnection.addTrack(stream.getAudioTracks()[0], stream);
	}else{
		peerAudioConnection.onaddstream = function(e){
			voicePlayer.srcObject = e.stream;
			voicePlayer.muted = false;
			voicePlayer.play();
		};

		peerAudioConnection.addStream(stream);
	}

	const desc = new RTCSessionDescription(offer);
	peerAudioConnection.setRemoteDescription(desc);

	peerAudioConnection.createAnswer().then(function(answer) {
	    peerAudioConnection.setLocalDescription(answer);
		weliveSend({type: "webrtc", event: "client-audio-answer", msg: answer});
	}).catch(function(e){
		console.error(e);		
	});
}

////////////////////////// ****************************** ////////////////////////////////////

//视频开关按钮
function operateCamera(me){
	if(userVideoStream){ //关闭
		stopVideo();
		$(me).removeClass("camera_on");

		weliveSend({type: "webrtc", event: "client-camera-close", msg: ""}); //给客服发一个关闭视频的通知
		
	}else{ //打开
		startVideo();
		$(me).addClass("camera_on");
	}
}

//发起视频
function startVideo(){
	if(!audioStatusOk) return; //语音未OK, 返回
	
	userNavigator.getUserMedia({
		video: true
	}).then(function(stream) {
		localVideo.srcObject = stream;
		userVideoStream = stream;

		$("#video_container").slideDown(800); //本地视频窗口
		weliveSend({type: "webrtc", event: "client-video", msg: ""}); //请求客服允许

	}).catch(function (e) {
		layer.msg(langs.not_auth_camera, {time: 6000});
	});
}

//结束视频
function stopVideo(){
	if(userVideoStream){
		userVideoStream.stop();
		userVideoStream = null;

		try{ //避免DOM权限报错
			localVideo.srcObject = null;
		}catch(e){}
		
		$("#video_container").slideUp(400); //本地视频窗口
	}

	if(peerVideoConnection){
		peerVideoConnection.close();
		peerVideoConnection = null;
	}
}

//发起视频ice申请(NAT穿透服务器)
function applyVideoIceCandidate(stream){
    const rtcPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
	peerVideoConnection = new rtcPeerConnection(iceConfig); //连接

	peerVideoConnection.onicecandidate = function(event){
		if(event.candidate) {
			//将ice申请结果发送给客服
			weliveSend({type: "webrtc", event: "client-video-candidate", msg: event.candidate});
		}
	};

	//使用addTrack 和 ontrack, addStream 和 onaddstream 将被废弃
	if(typeof peerVideoConnection.addTrack == 'function'){
		peerVideoConnection.addTrack(stream.getVideoTracks()[0], stream);
	}else{
		peerVideoConnection.addStream(stream);
	}

	//给客服提供offer
	peerVideoConnection.createOffer().then(function(desc){
		peerVideoConnection.setLocalDescription(desc).then(function(){
			//访客将申请的ICE发送给客服
			weliveSend({type: "webrtc", event: "client-video-offer", msg: peerVideoConnection.localDescription});
		}).catch(function(e){
			console.error(e);
		});
	}).catch(function(e){
		console.error(e);
	});
}

//切换视频大小
function toggleVideoSize(me){
	var original = $(me).attr("original"); //原始bottom值

	if(original){
		$(me).css("bottom", original);
		$(me).attr("original", "");
	}else{
		var bottom = $(me).css("bottom");
		$(me).attr("original", bottom); //记录下来

		var height = $(me).height();

		bottom = (parseInt(bottom) + height / 2) + "px";
		$(me).css("bottom", bottom);
	}
}
//webRTC语音视频 end


//welive初始化
function weliveInit(){
	sender = $("#sender_msg");
	msger = $(".msger");
	sounder = $("#wl_sounder");
	toolbar_ticket = $(".toolbar_ticket");
	ticket_waitings = $(".ticket_waitings");
	send_mod_div = $("#send_mod_div");

	pagetitle = document.title;

	weliveLink(); //socket连接

	$(window).resize(function(){
		resizeOperateArea();
	});

	//发送信息
	msger.keydown(function(e){
		var e = e||event, keyCode=e.keyCode||e.which||e.charCode;
		if((send_btn_mod == 0 && e.ctrlKey && keyCode == 13) || (send_btn_mod == 1 && keyCode == 13)){
			weliveSendMsg();
			e.preventDefault();
		}	
	});   

	//发送信息
	sender.click(function(e) {
		weliveSendMsg();
		e.preventDefault();
	});

	//工具栏按钮title
	showTitle("div.tool_bar_i");

	//评价按钮动作
	$("#toolbar_evaluate").click(function(){
		rating_star = 0;
		$("#starRating .star span").find('.high').css('z-index',0);
		$(".starInfo").html(langs.select_star);
		$("#starRating").toggle();
	});

	//评价层
	$("#starRating").mouseover(function(){
		clearTimeout(ttt_4);
	}).mouseout(function(){
		var me = $(this);
		ttt_4 = setTimeout(function(){
			me.hide();
		}, 800);
	});

	//星星打分
	$("#starRating .star span").mouseover(function () {
		rating_star = parseInt($(this).attr("star_val"));

		$(this).prevAll().find('.high').css('z-index',1);
		$(this).find('.high').css('z-index',1);
		$(this).nextAll().find('.high').css('z-index',0);

		$('.starInfo').html(star_info[rating_star -1]);
	});

	//表情符号
	$("#toolbar_emotion").click(function(){
		clearTimeout(ttt_4);
		smilies_div.toggle();
	}).mouseover(function(){clearTimeout(ttt_4);}).mouseout(function(){
		ttt_4 = setTimeout(function() {
			smilies_div.hide();
		}, 800);
	});

	smilies_div.mouseover(function(){
		clearTimeout(ttt_4);
	}).mouseout(function(){
		ttt_4 = setTimeout(function() {
			smilies_div.hide();
		}, 800);
	});

	//开关声音
	sound_btn.click(function(){
		if(welive.sound){
			welive.sound = 0;
			sound_btn.addClass('sound_off');
			setCookie(COOKIE_USER + "_soff", 1, 2); //关闭声音cookie保持2天		
		}else{
			welive.sound = 1;
			sound_btn.removeClass('sound_off');
			sounder.html(welive.mp3);
			setCookie(COOKIE_USER + "_soff", 0, 0);
		}
		msger.focus(); //输入框焦点
	});

	//上传图片按钮
	$("#toolbar_photo").click(function(){
		$("#welive_div_toop").hide(); //隐藏title

		if(!welive.status || !welive.linked){
			layer.msg(langs.notready);
			return;
		}

		//验证上传图片权限
		if(welive.isRobot || !welive.isCalling){
			layer.msg(langs.no_upload_robot);
			return;
		}

		layer.msg("WeCaller免费版无上传图片功能");
	});

	//上传文件按钮
	$("#toolbar_file").click(function(){
		$("#welive_div_toop").hide(); //隐藏title

		if(!welive.status || !welive.linked){
			layer.msg(langs.notready);
			return;
		}

		layer.msg("WeCaller免费版无上传文件功能");
	});

	//发送模式按钮及选择层
	$("#send_mod_btn").click(function(){	send_mod_div.toggle();}).mouseout(function(){ttt_4 = setTimeout(function(){send_mod_div.hide();}, 600);});
	send_mod_div.mouseover(function(){	clearTimeout(ttt_4);}).mouseout(function(){ttt_4 = setTimeout(function(){send_mod_div.hide();}, 600);});


	//停止标题闪烁、禁止刷新
	$(document).mousedown(stopFlashTitle).keydown(function(e){
		stopFlashTitle();

		var e = e||event, keyCode=e.keyCode||e.which||e.charCode;

		//已取号且status正常时, 禁止F5, ctrl或shift + F5或R键 刷新
		if(welive.status && guest.tn && (keyCode == 116 || ((e.ctrlKey || e.shiftKey) && (keyCode == 82 || keyCode == 116))) ){
			layer.msg(langs.not_refresh);
			e.returnValue = false;
			e.cancelBubble = true;
			e.keyCode = e.which = e.charCode = 0;
			e.preventDefault();
			return false;
		}
	});

	welive.mp3 = '<audio src="' + SYSDIR + 'public/sound_f.mp3" autoplay="autoplay"></audio>';
	welive.ring = '<audio src="' + SYSDIR + 'public/ring_f.mp3" autoplay="autoplay"></audio>';

	//已取号且状态正常时, 离开当前页面时提示及选择
	window.onbeforeunload=function(event){if(welive.status && guest.tn){return " ";}};
	$(window).unload(function(){welive.status=0;clearTimeout(welive.ttt);clearInterval(ttt_1);clearInterval(ttt_2);clearInterval(ttt_3);});
}

//websocket
var WebSocket = window.WebSocket || window.MozWebSocket;

//定义全局变量
var ttt_1 = 0, ttt_2 = 0, ttt_3 = 0, ttt_4 = 0, ttt_5 = 0, rating_star = 0, pagetitle, flashtitle_step = 0, sounder, sound_btn, sending_mask, sending_mask_h, send_btn_mod = 1, send_mod_div;
var welive_op, welive_cprt, history_wrap, historier, sender, msger, smilies_div, toolbar_ticket, ticket_waitings;

var welive_name; //客服姓名
var welive_duty; //客服职位
var welive_relink_times = 7; //允许重连次数, 超过后显示无法连接

var window_width, window_height; //屏幕宽和高px

var file_chunk_size = 1048576; //切片大小 默认为1M
var file_temp_data = ""; //切片上传文件时使用

//webRTC语音相关
var userNavigator, userAudioStream, peerAudioConnection, iceConfig;
var audioStatusOk = 0;
var wRecordWaver, voicePlayer; //语音播放dom对象

//视频相关
var userVideoStream, peerVideoConnection, localVideo;


//linked        1已连接,   0未连接
//status        1登录成功允许发信息,   0不允许发信息
//autolink     1允许重新连接,   0不允许重新连接
var welive = {ws:{}, ttt: 0, linked: 0, status: 0, autolink: 0, flashTitle: 0, sound: 1, mp3: '', ring: '', msg: '', closeQuiet: 0, isRobot: 1, isCalling: 0};

var star_info = ['<img src="' + SYSDIR + 'public/img/star_icon1.png">' + langs.star_1, '<img src="' + SYSDIR + 'public/img/star_icon2.png">' + langs.star_2, '<img src="' + SYSDIR + 'public/img/star_icon3.png">' + langs.star_3, '<img src="' + SYSDIR + 'public/img/star_icon4.png">' + langs.star_4, '<img src="' + SYSDIR + 'public/img/star_icon5.png">' + langs.star_5];


//页面加载完成
$(function(){
	welive_op = $("#welive_operator");
	welive_cprt = $("#welive_copyright");
	sound_btn = $("#toolbar_sound");
	smilies_div = $(".smilies_div");
	history_wrap = $(".history");
	historier = history_wrap.find(".overview");

	//调整操作区高度及位置
	resizeOperateArea();

	//获取客人的gid
	var gid = parseInt(getCookie(COOKIE_USER));
	if(gid) guest.gid = gid;

	//获取客人的排队票号
	var tn = parseInt(getCookie(COOKIE_USER + "_tn"));
	if(tn) guest.tn = tn;

	if(WS_HOST == "")	WS_HOST = document.domain; //先记录下来供websocket连接使用

	//获取当前的声音状态
	var wl_soundoff = parseInt(getCookie(COOKIE_USER + "_soff"));
	if(wl_soundoff == 1){
		welive.sound = 0;
		sound_btn.addClass('sound_off');
	}

	//初始化发送按钮模式
	send_btn_mod = getCookie(COOKIE_USER + "_sbm");
	if(!send_btn_mod) send_btn_mod = 1;
	$(".send_mod_" + send_btn_mod).addClass("curr_send_mod");


	//通话相关 start
	//MediaStream stop兼容性处理
	if(typeof MediaStream !== 'undefined') {
		if(typeof MediaStream.prototype.stop === 'undefined') {
			MediaStream.prototype.stop = function() {
				this.getTracks().forEach(function(track) {
					track.stop();
				});
			};
		}
	}

	//兼容性处理
	userNavigator = navigator.mediaDevices||{};
	if(!userNavigator.getUserMedia){
		userNavigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
	}

    window.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate;
	window.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;

	//先授权使用麦克风
	if(userNavigator.getUserMedia){
		userNavigator.getUserMedia({audio:true}).then(stream => {
			setTimeout(function(){stream.stop();}, 200);
		}).catch(err => {
			layer.msg(langs.not_auth_mic, {time: 6000});
		});
	}else{
		layer.msg(langs.not_support_rtc, {time: 6000});
	}


	wRecordWaver = $(".voice_waver"); //波形图
	localVideo = document.getElementById('localVideo'); //本地摄像头
	voicePlayer = document.getElementById("voice_player"); //播放器
	//通话相关 end


	weliveInit(); //welive初始化


	//发送截图title
	showTitle(".how_sendimg");

	//常见问题
	$("#common_questions li").click(function(){
		var txt = $(this).text();
		msger.val(txt);
		msger.focus();
	});

});