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

//弹出消息
function popInfo(info, sec){
	if(sec){
		layer.msg(info, {time: sec * 1000});
	}else{
		layer.msg(info);
	}
}

//显示大图片
function showImage(me, width, height){
	var popup = $("#welive_big_img");

	var new_w = 1, new_h = 1, new_top = 0, new_left = 0;

	if(window_height < 1) window_height = 1;

	if(width/height >= window_width/window_height){
		new_w = width;
		if(new_w > window_width) new_w = window_width - 30;
		new_h = height * new_w / width;
	}else{
		new_h = height;
		if(new_h > window_height) new_h = window_height - 30;
		new_w = width * new_h / height;
	}

	new_w = parseInt(new_w);
	new_h = parseInt(new_h);

	new_left = parseInt((window_width - new_w)/2);
	new_top = parseInt((window_height - new_h)/2);

	//点击或者触控弹出层外的半透明遮罩层, 关闭弹出层
	popup.bind("click",  function(e) {
		popup.hide();
		$(this).unbind("click");
	});

	popup.children('.big_img_wrap').css({top: new_top, left: new_left, width: new_w, height: new_h}).html('<img src="' + me.src + '" style="width: ' + new_w + 'px;height: ' + new_h + 'px;">');
	popup.fadeIn(200);
}

//根据select设置对象显示title
function showTitle(select){
	function showTT(e){
		$("#welive_div_toop").css({"top": (e.pageY + 20) + "px","position": "absolute","left": (e.pageX + 12) + "px"}).show("fast");
	}

	$(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 5px;'>" + this.Mytitle + "</div>");
		showTT(e);
	}).mouseout(function () {
		if(!this.Mytitle) return;
		this.title = this.Mytitle;
		$("#welive_div_toop").remove();
	}).mousemove(function (e) {
		showTT(e);
	});
}

//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 = "";
			popInfo('ajax error!', 8);
		}
	});
}

//设置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;

		if(welive.unread){
			welive.unread = 0;
			new_info.fadeOut(800);

			if(welive.status) weliveSend({type: "g_readed"}); //发送已读信号
		}
	}
}

//获得计算机当前时间
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;
	}
}

//设置为默认头像
function setDefaultAvatar(){
	welive_op.find("#welive_avatar").attr("src", SYSDIR + "public/img/welive.png");
	welive_op.find("#welive_name").html(langs.welive);
	welive_op.find("#welive_duty").html(langs.notready);
}

//socket连接
function weliveLink(){
	welive.ws = new WebSocket(WS_HEAD + WS_HOST + ':'+ WS_PORT);

	welive.ws.onopen = function(){
		welive.linked = 1; //websocket连接成功
		welive.closeQuiet = 1; //连接成功后, websocket连接断开时不显示: 连接失败，请稍后重试
		setTimeout(function(){weliveVerify();}, 100); //连接成功后, 小延时再验证用户, 否则IE下刷新时发送数据失败
	};

	welive.ws.onclose = function(){weliveClose();};
	welive.ws.onmessage = function(get){weliveParseOut(get);};
}


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

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

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


//输出聊天记录
function outputRecords(reArr){
	var recs = '';
	$.each(reArr, function(i, rec){
		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.welive;
			}

			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, raw = 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;

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

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

				sender.removeClass('loading2');
			}

			break;

		case 8: //人工客服发来的标记已读信息

			historier.find("s.un").html(langs.readed).removeClass("un");
			return true;

			break;

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

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

					welive.isRobot = 0; //系统是否为无人值守状态

					guest.fn = data.fn; //客人姓名
					guest.aid = parseInt(data.aid); //更新客服的id, 重新连接时用
					guest.an = data.an; //客服姓名
					guest.au = parseInt(data.au); //上传授权, 强制转成数字1或0, 方便判断, JS里if("0") 是true, php里为false

					 //更新头像及身份
					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);

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

					msger.focus();
					welive.flashTitle = 1;
					type = 8; d = welcome;
					raw = 1; //原生的, 不解析html

					outputRecords(data.re); //输出对话记录

					rememberGuest(data.gid, data.sess); //记住访客id, 上传session会话

					autoOffline(); //启动自动离线

					welive.temp = '';
					weliveRuntime(); //非机器人服务时, 启动实时输入状态
					$("#toolbar_transto").hide();

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

					break;

				case 1: //客服重新上线
					clearTimeout(welive.ttt2); //清除客服离线时自动转接

					setTwoStatus(1); //状态正常, 允许重连
					welive.flashTitle = 1;
					type = 3; d = welive_name + langs.aback;

					break;

				case 2: //客服离线
					welive.status = 0;
					welive.flashTitle = 1;
					type = 4; d = welive_name + langs.offline;

					//1分钟后发送请求重新分配客服的请求
					welive.ttt2 = setTimeout(function(){
						weliveSend({type: "g_handle", operate: "redistribute"});
					}, 59973);

					break;

				case 4: //重复连接
				case 5: //自动离线
					type = 4;
					setTwoStatus(0); //状态未正常, 不允许重连
					d = (data.a == 4 ? langs.relinked : langs.autooff) + '<br><a onclick="weliveLink();$(this).parents(\'.msg\').hide();return false;" class="relink">' + langs.rebtn + '</a>';
					setDefaultAvatar(); //设为初始头像

					break;

				case 6: //被踢出
					setTwoStatus(0);
					type = 4; d = langs.kickout;
					setDefaultAvatar(); //设为初始头像

					break;

				case 7: //被禁言
					setTwoStatus(0);

					welive.flashTitle = 1;
					type = 4; d = langs.banned;

					break;

				case 9: //无客服在线 或 客服组不存在或关闭时 或 禁言中
					setTwoStatus(0);
					type = 4;
					d = langs.nosuppert; //客服不在线

					if(data.i == "nogroup"){
						d = langs.team_off; //客服组不存在或关闭
					}else if(data.i == "banned"){
						d = langs.banned; //禁言中
					}

					setDefaultAvatar(); //设为初始头像

					break;

				case 11: //被转接
					setTwoStatus(1);

					welive.isRobot = 0; //系统是否为无人值守状态

					guest.aid = data.aid; //更新客服的id, 重新连接时用
					guest.an = data.an; //客服姓名
					guest.au = parseInt(data.au); //上传权限

					 //更新头像及身份
					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);

					welive.temp = '';
					weliveRuntime(); //启动实时输入状态
					$("#toolbar_transto").hide();

					msger.focus();
					welive.flashTitle = 1;
					type = 4; d = langs.transfer + data.an;

					break;

				case 14: //评价返回
					msger.focus();

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

					break;
			}

			break;

		case 7: //其它
			switch(data.a){

				case 9: //客服撤回一条消息

					type = 3; d = langs.draw_back;
					historier.find(".msg.l:last").remove();

					break;
			}

			break;
	}

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

//交流输出信息, raw为true时不解析html
function weliveOutput(d, type, raw){
	if(d === false || !type) return; //没有信息及类型返回

	if(welive.flashTitle){
		flashTitle();
		if(welive.sound) sounder.html(welive.mp3); //发声音
		welive.flashTitle = 0;
	}

	switch(type){
		case 1: //客服
		case 8: //问候语, 信息不解析(支持html), 不计数
			if(type == 1){
				welive.unread += 1; //有未读信息
				new_info.html(welive.unread).show();
			}

			d = '<div class="msg l"><div class="a">' + welive_name + ' - ' + welive_duty + '<i>' + getLocalTime() + '</i></div><b></b><div class="b"><div class="i">' + (raw ? d : formatOutput(d)) + '</div></div></div>';
			break;
		case 2: //客人
			d = '<div class="msg r"><b></b><div class="b"><div class="i">' + (raw ? d : formatOutput(d)) + '</div></div><i>' + getLocalTime() + '<br><s class="un">' + 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;
	}

	historier.append(d);

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

//设置welive的两个状态
function setTwoStatus(option){
	if(option){
		welive.status = 1; //状态正常, 可以送消息
		welive.autolink = 1; //允许重连
	}else{
		welive.status = 0;
		welive.autolink = 0;
	}
}

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

//连接断开时执行
function weliveClose(){
	welive.linked = 0; //标记连接失败
	clearTimer(); //清理定时器

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

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

//离开页面或断线时清理定时器
function clearTimer(){
	welive.status=0;
	clearTimeout(welive.ttt); //自动离线
	clearTimeout(welive.ttt2); //客服离线时自动转接
	clearInterval(ttt_1); //发送心跳数据
	clearInterval(ttt_2); //上传进度条
	clearInterval(ttt_3); //标题闪烁
	clearInterval(ttt_6); //实时输入状态
}

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

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

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

//发送输入框文本
function weliveSendMsg(){
	if(welive.status) {
		var msg = $.trim(msger.val());

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

			welive.temp = ''; //终止实时输入提交数据
			sender.addClass('loading2');
			welive.msg = msg; //先记录客人的发言

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

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

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

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

//自动离线
function autoOffline(){
	if(!welive.linked) return; //未连接不自动离线
	if(welive.ttt) clearTimeout(welive.ttt); //清除自动离线

	welive.ttt = setTimeout(function(){
		weliveSend({type: "g_handle", operate: "offline"});
	}, offline_time);
}

//启动输入状态更新
function weliveRuntime(){
	ttt_6 = setInterval(function(){
		if(welive.status) {
			var msg = $.trim(msger.val());

			if(msg && msg != welive.temp){

				weliveSend({type: "runtime", msg: msg});
				welive.temp = msg; //记录正在输入的信息

			//清空输入框后, 给客服发通知, 去掉输入状态
			}else if(!msg && welive.temp){

				weliveSend({type: "runtime", msg: ""});
				welive.temp = '';
			}
		}

	}, update_time);
}


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

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

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

	if(msg.length > 600){
		popInfo(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");

	if(send_btn_mod == 1){
		msger.attr("placeholder", "Enter : " + langs.send);
	}else{
		msger.attr("placeholder", "Ctrl + Enter : " + langs.send);
	}

	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();
}


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

	pagetitle = document.title;

	weliveLink(); //socket连接

	//工具栏按钮, 发送截图, 发送模式的title
	showTitle("div.tool_bar_i, #send_mod_btn");

	$(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();
	});

	//评价按钮动作
	$("#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").mouseover(function(){
		clearTimeout(ttt_4);
		smilies_div.show();
	}).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

		popInfo(langs.notready);
		return;
	});

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

		popInfo(langs.notready);
		return;
	});

	//发送模式按钮及选择层
	$("#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 && (keyCode == 116 || ((e.ctrlKey || e.shiftKey) && (keyCode == 82 || keyCode == 116))) ){
			popInfo(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>';

	//状态正常时, 离开当前页面时提示选择及动作
	window.onbeforeunload=function(event){
		if(welive.status){
			return " ";
		}else{
			clearTimer();
		}		
	};

	$(window).unload(function(){clearTimer();});
}

//定义全局变量
var WebSocket = window.WebSocket || window.MozWebSocket; //websocket

var ttt_1 = 0, ttt_2 = 0, ttt_3 = 0, ttt_4 = 0, ttt_5 = 0, ttt_6 = 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, new_info, historier, sender, msger, smilies_div;

var welive_name; //客服姓名
var welive_duty; //客服职位

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

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


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

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");
	msger = $("#guest_msg");
	smilies_div = $(".smilies_div");
	new_info = $("#new_info");
	historier = $(".overview");

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

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

	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;
	if(send_btn_mod == 0) msger.attr("placeholder", "Ctrl + Enter : " + langs.send);
	$(".send_mod_" + send_btn_mod).addClass("curr_send_mod");


	weliveInit(); //welive初始化


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

});