// JavaScript Document
var mainTime;
var num=0;
function clientList(list) {
	this._cnc = 0; 
	this.list = $(list);
};

/*var mainTime;
var num=0;
function clientList(list) {
	this._cnc = 0; 
	this.list = $(list);
};*/

clientList.prototype.add = function (client) {
	if(client.trim() == "" || client=="null") return;
	var self = this; 
	self.client = client;
	var _cnc = this._cnc;
	var cDiv = $C("div");
	cDiv.id = "client_div_" + client;
	var cButton = $C("button");
	var delButton = $C("img");
	delButton.id= "client_del_"+client;
	cButton.name = "client_button_" + client;	
	cButton.onclick = function () {
		$("client").value = client;
		showme('center');
		if(Line.clientArr[client].status=='connect'){
			self.stop(client);
			$('sendimg').attachEvent("onmouseover",setImageOnline1);
			$('sendimg').attachEvent("onmouseout",setImageOnline);
		}
		else{
			self.offline(client);
			Line.showHelpTips("你的信息将以短信形式发送给客户");
		}
		self.hideBgColor();
		this.style.backgroundColor  = '#6386de';
		//$("ip").innerHTML = Line.clientArr[client].ip;
		if(Line.clientArr[client].iduser && Line.clientArr[client].iduser!='null' && myUserInfoURL){
			$('userI_frame').setAttribute('src',myUserInfoURL+'?iduser='+Line.clientArr[client].iduser);
			$('userI_div').style.display = '';
		}
		else {
			$('userI_div').style.display = 'none';
		}
		if(Line.clientArr[client].ip.indexOf("[")==-1)
			showIPArea(Line.clientArr[client].ip,client);
		else
			$('ip').innerHTML = Line.clientArr[client].ip;
		$('tel').innerHTML = Line.clientArr[client].tel!=null && Line.clientArr[client].tel!="null"?Line.clientArr[client].tel:"";
		$("DataTime").innerHTML = Line.clientArr[client].time; 
		$("clientid").innerHTML = client;
		if (this.getAttribute('message')!=null){
			$('panel_main').innerHTML = unescape(this.getAttribute('message')) || "";
		}else {
			$('panel_main').innerHTML="";
		}
		$("panel_main").scrollTop = $("panel_main").scrollHeight - $("panel_main").clientHeight + 99999999;
		callTimeLen = parseInt(mainTime-this.startTime);
	};
	cButton.setAttribute('message',Line.clientArr[client].content);
	cButton.setAttribute('startTime',mainTime);
	cButton.id = "client_button_" + client;
	//cbuttonNickname = Line.clientArr[client].nickName;
	//alert(cbuttonNickname);
	cButton.className = "clientbutton";
	var tipl = "<img id='client_img_move_"+client+"' style='display:none;' src='images/calling.gif' />\
				<img id='client_img_offline_"+client+"' style='display:none;' src='images/offline.gif' />\
				<img id='client_img_offline_move_"+client+"' style='display:none;' src='images/offline_move.gif' />\
				<img id='client_img_stop_"+client+"' style='' src='images/clientstop.gif' title='客户已离开' />\
				<font class='font' id='Nickname_"+client+"'>"+ Line.clientArr[client].nickName+"</font>\
				<img id=\"client_edit_tips_"+client+"\" style='display:none;' src='images/edit1.gif' title='客户正在输入信息~！'>";
				
	cButton.innerHTML = tipl;
	cButton.style.textAlign="left";
	cButton.style.float="left";
	cDiv.style.verticalAlign=''
	cDiv.appendChild(cButton);
	if (Line.clientArr[client].status=="connect"){
		$('onlinelist').appendChild(cDiv);
	} else {
		$('offlinelist').appendChild(cDiv);
	}
//	this.list.appendChild(cDiv);
	this._cnc++;
	$('closeImg').style.dispaly = '';
	return this;
};

clientList.prototype._removeNode = function (id) {
	var a = $(id);
	a.style.dispaly = "none";
};

clientList.prototype.remove = function (id) {
	this._removeNode("client_button_" + id);
	this._removeNode("client_div_" + id);
	$("client_div_" + id).style.display = "none";
	return this;
};

clientList.prototype.move = function (id){
	try{
		$("client_img_stop_" + id).style.display = "none";
		$("client_img_offline_" + id).style.display ='none';
		$("client_img_offline_move_" + id).style.display ='none';
		$("client_img_move_" + id).style.display = "";
		$("showOnline").style.display="none";
		$("showOnline_move").style.display="block";
	}catch(e){}
};

clientList.prototype.stop = function (id){
	try{
		$("client_img_move_" + id).style.display = "none";
		$("client_img_offline_" + id).style.display ='none';
		$("client_img_offline_move_" + id).style.display ='none';
		$("client_img_stop_" + id).style.display = "";
		$("showOnline").style.display="block";
		$("showOnline_move").style.display="none";
		divs = $('offlinelist').getElementsByTagName("div");
		for (var i = 0;i<divs.length;i++){		
			if (divs[i].id==("client_div_"+id)){
				$('onlinelist').appendChild($('offlinelist').removeChild(divs[i]));
			}	
		}
		sendMethod="online";
		$("txtsendMethod").disabled="";
		$("txtsendMethod").checked="";
		
	}catch(e){}
};
clientList.prototype.offline = function(id){
	try{
		$("client_img_move_" + id).style.display = "none";
		$("client_img_stop_" + id).style.display = "none";
		$("client_img_offline_move_" + id).style.display ='none';
		$("client_img_offline_" + id).style.display ='';
		$("showOffline_move").style.display="none";
		$("showOffline").style.display="block";
		divs = $('onlinelist').getElementsByTagName("div");
		for (var i = 0;i<divs.length;i++){		
			if (divs[i].id==("client_div_"+id)){
				$('offlinelist').appendChild($('onlinelist').removeChild(divs[i]));
			}	
		}
		sendMethod="mobile";
		$("txtsendMethod").checked="true";
		$("txtsendMethod").disabled="true";
		
	}catch(e){}
}
clientList.prototype.offline_move=function(id){
	try{
		$("client_img_move_" + id).style.display = "none";
		$("client_img_stop_" + id).style.display = "none";
		$("client_img_offline_" + id).style.display ='none';
		$("client_img_offline_move_" + id).style.display ='';
		$("showOffline_move").style.display="block";
		$("showOffline").style.display="none";
	}catch(e){}
}

clientList.prototype.showclose = function (id){
	$("client_button_" + id).style.width = "60px";
	$("client_close_" + id).className = "showclose";
};

clientList.prototype.test = function() {
	alert("test");
};

clientList.prototype.showEdit = function(id){
	window.clearInterval(Line.clientArr[id].clearTyping);
	$("client_edit_tips_"+id).style.display = "";
	Line.clientArr[id].clearTyping = window.setInterval("Line.clientlist.hideEdit("+id+")", 5000);
};
clientList.prototype.hideEdit = function(id){
	try{
		$("client_edit_tips_"+id).style.display = "none";
		window.clearInterval(Line.clientArr[id].clearTyping);
	}catch(e){}
};
clientList.prototype.hideTips = function(id){
	$("client_button_" + id).title = "";
};
clientList.prototype.showTips = function(tips, id){
	$("client_button_" + id).title = tips;
};

clientList.prototype.hide = function(id){
	$("client_div_"+id).style.display = "none";
};
clientList.prototype.show = function(id){
	$("client_div_" + id).style.display = "";
	$('panel_main').innerHTML = $("client_button_"+id).getAttribute("message");
	$("client_button_"+id).setAttribute("startTime",mainTime);
	$("panel_main").scrollTop = 10000;
};
clientList.prototype.hideBgColor = function(){
	var clientButtonObjs = $('onlinelist').childNodes;
	for(var i=0;i<clientButtonObjs.length;i++){
		clientButtonObjs[i].childNodes[0].style.backgroundColor = 'ffffff';
	}
	var clientButtonObjs = $('offlinelist').childNodes;
	for(var i=0;i<clientButtonObjs.length;i++){
		clientButtonObjs[i].childNodes[0].style.backgroundColor = 'ffffff';
	}
}

function setImage(src){
	$('sendimg').src=src;
}

function setImageOnline(){
	setImage("images/send.jpg");
}

function setImageOnline1(){
	setImage("images/send1.jpg");
}
function setImageOffline(){
	setImage("images/sendoffline.jpg");
}
function setImageOffline1(){
	setImage("images/sendoffline1.jpg");
}

function showSetTimeout(id){
	alert(id);
}
var is_Win = 0;
Line = {
	clientlist:{},	panel:{},	clientArr:{},	itemArr:{},	client:'',nickname:'客户', clearTypingHelp:'',
	colorArr:{
		error:"#ff0000"
	},
	AudioStatus:'',

	initialize: function(){
		this.clientlist = new clientList("clientlist");
		this.initControl();
	},
	
	_getSendTpls : function(){
		return "<font class='send'>"+Name+" &nbsp;"+getNowTime()+"</font><br/>";
	},
	
	_getMobileTpls : function(){
		return "<font class='send'>"+Name+" &nbsp;"+getNowTime()+"(通过短信发送)</font><br/>";
	},
	_getMobileFailTpls : function(error){
		return "<font class='send'>"+Name+" &nbsp;"+getNowTime()+"(发送失败，请稍后再尝试)</font><br/><font class='send'>错误信息: "+error+"</font><br/>";
	},
	_getReceiverTpls2: function(client){
		return "<font class='receiver'>"+this.clientArr[client].nickName+" &nbsp;"+getNowTime()+"</font><font class=''></font><br/>";
	},
	
	_getReceiverTpls: function(client){
		return "<font class='receiver'><a href='#' onclick='setNickname("+client+")' title='单击可更改昵称' id='Nickname_"+client+"'>\
				"+this.clientArr[client].nickName+"</a> &nbsp;"+getNowTime()+"</font><br/>";
	},
	
	call: function(item){
		var client = item.client;
		if(!this.clientArr[client]){
			this.clientArr[client] = new Object();
			this.clientArr[client].status = "connect";
			this.clientArr[client].nickName = (item.name==null || item.name=="")?"客户"+(this.clientlist._cnc+1):item.name;
			this.clientArr[client].iduser   = item.iduser;
			this.clientlist.add(client);
			getLineChatlogs(client);
		}
		else{
			this.clientArr[client].iduser   = item.iduser; 
			this.clientlist.show(client);
			this.clientlist.stop(client);
		}
		this.clientArr[client].client = client;
		this.clientArr[client].name = client;
		this.clientArr[client].time = getNowTime();
		this.clientArr[client].ip = item.ip;
		this.clientArr[client].tel = item.tel;
		this.clientArr[client].status = "connect";
		this.write(this.clientArr[client].nickName+" 进入会话界面", client);
		$("Nickname_"+client).innerHTML = this.clientArr[client].nickName;
		if(this.clientlist._cnc <= 1) $("client_button_" + client).click();
		$('duration').style.display = '';
		playSound('online');
	},
	initClients : function(item) {
		var client = item.client;
		if(!this.clientArr[client]){
			this.clientArr[client] = new Object();
			this.clientArr[client].status = "close";
			this.clientArr[client].nickName = (item.nickName==null || item.nickName=="")?"客户"+(this.clientlist._cnc+1):item.nickName;
			this.clientArr[client].iduser   = item.iduser;
			this.clientArr[client].content=item.content;
			this.clientlist.add(client);
			this.clientlist.offline(client);
		}else{
			this.clientArr[client].iduser   = item.iduser; 
			this.clientlist.show(client);
			this.clientlist.stop(client);
		}
		this.clientArr[client].client = client;
		this.clientArr[client].name = client;
		this.clientArr[client].time = getNowTime();
		this.clientArr[client].ip = item.ip;
		this.clientArr[client].tel = item.tel;
		this.clientArr[client].content=item.content;
	},
	initClientsByCallID:function(callid,idipm,idline){
		var senddata="callId="+callid;
		senddata+="&IDIPM="+idipm;
		senddata+="&IDLine="+idline;
		clientObj.open("POST","getclientlastlog.inc.php",false);
		clientObj.setRequestHeader("Content-Length",senddata.length);
		clientObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
		clientObj.onreadystatechange = this.onreadychange;
		clientObj.send(senddata);
	},
	
	onreadychange:function (){
		if ( clientObj.readyState==4 ) {
				var recvdata = clientObj.responseText;
				if (recvdata == ''){
				}else{
					clientArr = recvdata.split("|");
					var item = new Object();
					item.client = clientArr[0];
					item.ip = clientArr[1];
					item.nickName = clientArr[2];
					item.tel = clientArr[3];
					item.content= clientArr[4];
					return item;
				}
		}
	},
	
	clientEndCall: function(client){
		endCall(client);
		this.clientArr[client].status = "close";
		this.write(Line.clientArr[client].nickName + " 临时编号" + client + "，结束对话离开(" + getNowTime() + ")", client);
		if($("client_img_move_"+client).style.display=='none')
			this.clientlist.offline(client);
		else
			this.clientlist.offline_move(client);
	},
	
	clientDisconnect: function(){
		var client = $("client").value;
		if(!client){
			return this.showHelpTips("尚未建立连接，<br/>不能断开！");
		}
		this.clientArr[client].status == "close";
		$("flashPhoto").clientDisconnect(client);
	},
	
	closeClient: function(){
		var client = $("client").value;
		this.clientlist.hide(client);
	},

	buildMessage: function(str, item){
		for(var i in item){
			str = str.replace("{#" + i + "#}", item[i]);
		}
		return str;
	},
	receiverAudioInvite: function(client){
		var str = this._getAudioInviteTpls(client);
		this.write(str);
	},
	_getAudioInviteTpls: function(client){
		return "<span id='audio_span' name='audio_span'>"+this.clientArr[client].nickName+"请求语音通话，<a href='#' onclick='Line.acceptVoice("+client+")'>接受</a>\
				 或 <a href='#' onclick='Line.rejuctVoice("+client+")'>拒绝</a></span>";
	},
	acceptVoice:function(client){
		/*$('flashphoto').acceptVoice(client);
		this.clientArr['client'].AStatus = 'connect';
		$("audio_span").innerHTML = "您接受语音对话  ！";
		$("audio_span").id = "audio_span_bak";
		$("flashPhoto").initAudio();*/
		alert('here');
	},
	rejuctVoice:function(client){
		//$('flashphoto').rejuctVoice(client);
	},
	
	sendMessage: function (client){
		var msg = $("message").value;
		if (msg.trim()=="") {
			return (this.showHelpTips("不能发送空消息！"));
		}
		msg=UBBEncode(msg);		
		client = client||$("client").value;
		if(client == ""){
			this.showHelpTips("尚未建立连接，<br />不能发送信息！");
			return;
		}
		else if(msg.trim() == "") {
			this.showHelpTips("不能发送空消息！");
			return;
		}
		else if(msg.length > 1000) {
			this.showHelpTips("每次最多只能发1000个字符!");
			return;
		}
		if (sendMethod=="mobile"){
			this.sendMessageToMobile(msg,client,smsuser,apitype);		
			return true;
		} 
		else if(sendMethod=="online"){
			msg=UBBCode(msg.trim());
			//alert(client);
			$("flashPhoto").sendMessage(escape(msg),client);
			msg = this._getSendTpls() + msg;
			//var client = client || this.getNonceClient();
			this.write(msg, client);
			editLogContent("<p>" + msg +"</p>", client);
			this.clearContent();
			return true;
		}	
	},
	 smsCount : function (textArea,maxlimit,atype){
	 	var maxlen = 60;
		 var chrlen=0;
		 var newvalue = "";
		 if(atype==3){
	    	newvalue = textArea.value.replace(/[^\x00-\xff]/g, "**");  
			chrlen = newvalue.length;  
    	}else chrlen = textArea.value.length;
		 if (chrlen > (maxlimit*maxlen)) {
			textArea.value = textArea.value.substring(0, maxlimit*maxlen);
			this.showHelpTips("您最多可以同时发"+maxlimit+"条短信("+(maxlimit*maxlen)+"个字符)");
		 }
		 return Math.ceil(chrlen/maxlen);
	 },
	 
	 
	sendMessageToMobile :function(msg,client,smsuser,apitype){
		if ($('message').value==null || $('message').value.length==0){
			alert("发送内容不能为空");
			return;
		}
		this.smsCount($('message'),3,0);
		var senddata="arg=phwyying4023255&sid="+sid+"&line_name="+$('lineName').value+"&client="+client+"&content=" + dealphrase($('message').value)+"&IDSMSUser="+smsuser+"&tel="+$('tel').innerHTML+"&apitype="+apitype;
//		window.open("sms_send.php?"+senddata);
		msg = $("message").value;
		$("flashPhoto").sendMessage(escape(msg),client);
		//msg = this._getMobileTpls() + msg;
		logObj.open("POST","sms_send.php",false);
		logObj.setRequestHeader("Content-Length",senddata.length);
		logObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
		logObj.onreadystatechange = function(){
			if ( logObj.readyState==4 ) {
				var recvdata = logObj.responseText;
				if (recvdata == ''){
					msg = Line._getMobileFailTpls(recvdata) + msg;
					return;
				}
				if (recvdata.indexOf("||")>0){
					deposit = recvdata.substring(recvdata.indexOf("||")+2,recvdata.length);
					msg = Line._getMobileTpls() + msg+"(当前剩余"+deposit+"条)";
				} else {
					msg = Line._getMobileFailTpls(recvdata) + msg;
				}
				Line.write(msg, client);
				Line.clearContent();	
			}
		}
		logObj.send(senddata);
	},
	receiverMessage: function(message, client){
		var	str = this._getReceiverTpls2(client) + message;
		editLogContent("<p>" + str + "</p>", client);
		str = this._getReceiverTpls(client);
		message = str + message;
        this.write(message, client);

        this.showTips("上一条消息收于 " + getNowTime(), client);
		this.clientlist.hideEdit(client);
		if($("client").value != client)this.clientlist.move(client);
		playSound('msg');
		if(isAutoReply){
			//alert(client);
			this.autoReply(client);
		} 
	},
	clientTelChange :function (tel){
		$("tel").innerText = tel;
	},
	sendAudioInvite: function(){
		if(!isAudio) return alert('此功能还没用开通，请先开通！');
		
		var client = $("client").value;
		if(!client){
			var tips = "没有选中客户，<br/>不能语音通话！";
			this.showHelpTips(tips);
		}
		else if(this.clientArr[client].status == "close"){
			this.showHelpTips("客户已离开！");
		}
		else if(this.clientArr[client].AStatus=="conncet"){
			return alert('正在语音通话中！');
		}
		else{
			this.write("<span id='audio_span_"+client+"'>发送语音请求成功,<a href='#' onclick='cancelAudio()'>取消</a>",client);
			$("flashPhoto").sendAudioInvite(client);
		}
	},
	
	sendInput: function(){
		if($("message").value == "") return;
		try{
			var client = $("client").value;
			$("flashPhoto").sendInput(client);
		}catch(e){}
	},
	
	clientInput: function(client){
		this.clientlist.showEdit(client);
	},
	
	sendTips: function(tips){
		$("flashPhoto").sendTips(tips);
	},
	
	showTips: function(tips, client){
		//$("tips").innerHTML = tips;
		//this.clientlist.showTips(tips, client);
	},
	
	showHelpTips: function(tips, mode){
		mode = mode || "error";
		tips = "<font color=\""+this.colorArr[mode]+"\">"+tips+"</font>";
		window.clearInterval(this.clearTypingHelp);
		$("helpTips").style.display = "";
		$("helpTips").filters.alpha.opacity = 100;
		$("helpTips").setAttribute("num", 0);
		$("helpTipsHTML").innerHTML = tips;
		this.clearTypingHelp = window.setInterval(function(){
			try{
				var num = new Number($("helpTips").getAttribute("num"));
				if(num >= 3) $("helpTips").filters.alpha.opacity -= 20;
				if($("helpTips").filters.alpha.opacity <= 0){
					window.clearInterval(this.clearTypingHelp);
					$("helpTips").style.display = "none";
					$("helpTips").setAttribute("num", 0);
				}
				$("helpTips").setAttribute("num", ++num);
			}catch(e){}
		}, 280);
	},
	
	clearContent: function(){
		$("message").value = "";
		$("message").focus();
	},
	
	getNonceClient: function(){
		return $("client").value;
	},

	write: function(content, client){
		if(!content ||content == "null" || content==null )return;
		if(client){
			if($('client').value == client){
				$("panel_main").innerHTML += unescape("<p>" + content + "</p>");
			}
			var message = $("client_button_"+client).getAttribute("message");
			message = unescape(message);
			if(!message ||message == "null" || message==null )message =' ';
			$("client_button_"+client).setAttribute("message",message+"<p>" + content + "</p>") ;
		}
		else{
			$("main_input").value = unescape("<p>" + content + "</p>");
			$("panel_main").innerHTML += unescape("<p>" + content + "</p>");
		}
		$("panel_main").scrollTop = $("panel_main").scrollHeight - $("panel_main").clientHeight + 99999999;
	 	if(is_Win==0)window.focus();
	},
	
	clear: function(){
	},
	
	toEvalua:function(){
			var client = this.getNonceClient();
			if(!client) { return alert("还没有客户连接！");}
			if(this.clientArr[client].status == 'close')
				return this.showHelpTips('客户已经离开！');
			msg = "客服"+Name+"邀请您对他进行评分，点击<a href='#' onclick='evalua_open()'>这里对客服评分</a>"; 
			$("flashPhoto").sendMessage(msg);
			this.write("邀请评分成功",client);
	},
	
	initControl: function(){
		var _this = this;
		$("closeWin").onclick = function(event){
			var client = _this.getNonceClient();
			if(_this.clientArr[client].status == "connect"){
				if (!confirm(language_infos[59]))return;
			}
			$("client_close_"+client).onclick();
		}
	},
	
	autoReply: function(client){
		//alert(client);
		$('message').value = autoReplyMessage;
		this.sendMessage(client);
	},
	getClientArr:function(){
		var list = new Array();
		for(key in this.clientArr){
			if(/^\d*$/.test(key)){
				list.push(key);				
			}
		}
		return list;
	}
};

function main()
{
	Line.initialize();
	$("helpTips").style.display = "none";
}

var headHeight = 20;var bodyHeight =445;var step = 25;

function moveme(num)
{
	return;
	for (var i=0; i<document.getElementsByName("item").length; i++) 
	{
		var obj=document.getElementsByName("item")[i];
		obj.style.display = "";
		if (i<num) {
			moveup(i);
		}else if (i==num) {
			moveup(i);
		}else {
			movedown(i);
		}
	}
}

function moveup(num)
{
	var obj=document.getElementsByName("item")[num];
	if (num*headHeight < parseInt(obj.style.top))
	{
		var currtop=parseInt(obj.style.top)-step;
		if (currtop<num*headHeight) currtop=num*headHeight;
		obj.style.top=currtop;
		setTimeout('moveup('+num+')',10);
		return;
	}
}

function movedown(num)
{
	var allnum=document.getElementsByName("item").length;
	var obj=document.getElementsByName("item")[num];
	if (bodyHeight-(allnum-num)*headHeight > parseInt(obj.style.top))
	{
		var currtop=parseInt(obj.style.top)+step;
		if (currtop>bodyHeight-(allnum-num)*headHeight) currtop=bodyHeight-(allnum-num)*headHeight;
		obj.style.top=currtop;
		setTimeout('movedown('+num+')',10);
		return;
	}	
}

function menu_mouse(id,type){
	if(type==1){
		$('menu_line_'+id).className="menu_line_over";	
	}else{
		$('menu_line_'+id).className="menu_line";	
	}
}

var MessageBox = {
	_cnm:0,	bodyHeight:580,	Height:150, Step:25,
	
	numArr:{},
	
	_getDivTpl:function(){
		return "<div id='MessageBox' num='{#NUM#}' style='top: 600px;'><div id='MessageBoxTitle'><span id='MessageBoxTitleContent'>网络在线客服系统</span><span id='MessageBoxClose' onclick='MessageBox.hide(this);' num='{#NUM#}'>r</span></div><div id='MessageBoxContent'>{#MessageBoxContent#}</div></div>";
	},

	_removeNode :function (num) {
		var a = $$("MessageBox")[num];
		try{
			document.body.removeChild(a);
		}catch(e){
			a = $("MessageBox");
			try{document.body.removeChild(a);}
			catch(e){}
		}
	},

	remove:function (num) {
		this._removeNode(num);
		this._cnm--;
	},

	show:function(html, num){
		var divTpl = this._getDivTpl();
		divTpl = divTpl.replace(/\{#MessageBoxContent#\}/, html);
		divTpl = divTpl.replace(/\{#NUM#\}/g, this._cnm);
		document.body.insertAdjacentHTML("beforeEnd", divTpl);
		this.moveup(this._cnm);
		if(num) this.numArr[num] = this._cnm;
		return this._cnm++;
	},
	
	hide:function(obj){
		var num;
		try{
			num = obj.getAttribute("num");
		}catch(e){
			num = this.numArr[obj];
		}
		this.remove(num);
		for(var i=0;i<$$("MessageBox").length;i++){
			this.movedown(i);
			num = $$("MessageBoxClose")[i].getAttribute("num");
			this.numArr[this.numArr.search(num)] = i;
			$$("MessageBoxClose")[i].setAttribute("num", i);
		}
	},
	
	moveup:function(num){
		var obj=$$("MessageBox")[num];
		tmpnum=num+1;
		if (this.bodyHeight-this.Height*tmpnum < parseInt(obj.style.top)){
			var currtop=parseInt(obj.style.top)-this.Step;
			if (currtop<this.bodyHeight-this.Height*tmpnum)currtop=this.bodyHeight-this.Height*tmpnum;
			obj.style.top=currtop;
			setTimeout('MessageBox.moveup('+num+')',10);
			return;
		}
	},
	
	movedown:function(num){
		var obj=$$("MessageBox")[num];
		if (this.bodyHeight-this.Height*num > parseInt(obj.style.top)+this.Height){
			var currtop=parseInt(obj.style.top)+this.Step;
			if (currtop>this.bodyHeight-num*this.Height) currtop=this.bodyHeight-num*this.Height;
			obj.style.top=currtop;
			setTimeout('MessageBox.movedown('+num+')',10);
			return;
		}
	}
};
window.onblur = function(){
	is_Win = 0;
}
window.onfocus = function(){
	is_Win = 1;
}

function cancelAudio(){
	var client = $('client').value;
	$('flashPhoto').cancelAudio(client);
	$('audio_span_'+client).innerHTML = "你已经取消了语音请求!";
	$('audio_span_'+client).id = "audio_span_bak";
	//var html = "";
	//MessageBox.show(html);
}

function acceptAudio(){
	var client = $('client').value;
	alert(client);
	$('audio_span_'+client).innerHTML = "客户接受您的语音邀请!";
	$('audio_span_'+client).id = "audio_span_bak";
	Line.clientArr[client].AStatus = "conncet";
}

function rejectAudio(){
	var client = $('client').value;
	$('audio_span_'+client).innerHTML = "客户取消您的语音邀请!";
	$('audio_span_'+client).id = "audio_span_bak";
	Line.clientArr[client].AStatus = "close";
}

function setVoiceStatus(client,status){
	Line.clientArr[client].AStatus=status;
}
function setInviteStatus(client){
	Line.receiverAudioInvite(client);
}
function showLeaveMessages(){
	if(leaveMassageNum<1) return ;
	var readNow = "<a href='#' onclick ='MessageBox.hide(this);$(\"browser\").src=\"msg_list.php?line_id="+line_id+"&sid="+sid+"\";showme(\"browser\");'>现在查看留言</a>";
	window.setTimeout(function(){MessageBox.show('您现在有'+leaveMassageNum + '条未读留言'+"<br>"+readNow);leaveMassageNum = null;},1000);
}
callTimeLen=0;
function DoCallTimer(){  
	window.timer = window.setTimeout("DoCallTimer()",1000);
	var minute=0;
	var second=0;
	callTimeLen++;
	mainTime = parseInt(new Date().getTime()/1000);
	if(!$('client').value || Line.clientArr[$('client').value].status != "connect") return;
	minute = parseInt(callTimeLen/60);
	second = callTimeLen%60;

	if(minute == 0){
		$("time").innerHTML = second+" 秒";
	}
	else{
		$("time").innerHTML = minute+" 分"+second+" 秒";
	}
}

function rejectSwitch(switchLine, switchClient, content)
{
	var html = rejectSwitchHTML;
	html = html.replace(/\{#lineName#\}/g, lineArr[switchLine]);
	html = html.replace(/\{#content#\}/g, content);
	var num = MessageBox.show(html, switchClient);
	$("switch_span_"+switchClient).innerHTML = "ffffffffff";
	//$("switch_span_"+switchClient).id = "switch_span_bak";
}

function lineSwitch(switchLine, client, switchContent)
{
	var html = inviteSwitchHTML;
	html = html.replace(/\{#content#\}/g, switchContent);
	html = html.replace(/\{#lineName#\}/g, lineArr[switchLine]);
	alert("lineSwitch"+lineArr[switchLine]);
	html = html.replace(/\{#client#\}/g, client);
	html = html.replace(/\{#switchLine#}/g, switchLine);
	var num = MessageBox.show(html, client);
}

function confirmSwitch(client, switchLine, flag)
{
	if(switchLine==null || switchLine=="")return;
	if(flag){
		$("flashPhoto").acceptSwitch(switchLine, client);
	}else{
		var swicthCause = prompt("拒绝原因是:", "");
		$("flashPhoto").rejectSwitch(switchLine, client, swicthCause);
	}
	MessageBox.hide(client);
}

function cancelSwitch(switchLine)
{
	if (!confirm("你确定要取消吗?"))return;
	var client = $("client").value;
	$("switch_span_"+client).innerHTML = cancelSwitchHTML.replace(/\{#lineName#\}/g, lineArr[switchLine]);
	$("switch_span_"+client).id = "switch_span_bak";
	$("flashPhoto").cancelSwitch(switchLine, client);
	MessageBox.hide(client);
}

function acceptSwitch(switchLine, switchClient)
{
	var html = acceptSwitchHTML;
	html = html.replace(/\{#lineName#\}/g, lineArr[switchLine]);
	$("switch_span_"+switchClient).innerHTML = html;
	$("switch_span_"+switchClient).id = "switch_span_bak";
	MessageBox.show(html, switchClient);
}
function flashClose(){
	window.isFC=1;
	window.close();
}
function clearLineList(){
	$("lineList").length = 0;
}
function addLineList(lineName){
	var list = $("lineList");
	list.options[list.length] = new Option(lineArr[lineName]+"____"+lineName,lineName);
}

function setNickname(client){
	var name = prompt('请输入昵称,长度不能超过8个字','');
	if (name==null||name.trim()=="")return;
	else if(name.length>8) {
		alert("长度不能超过8个字");
		return;
	}
	for (var i=0; i<$$("Nickname_"+client).length; i++){
		$$("Nickname_"+client)[i].innerHTML = name;
	}
	$("client_button_"+client).setAttribute("message",$("panel_main").innerHTML) ;
	var senddata="arg=phwyying4023255&sid="+sid+"&action=setname&line_id="+line_id+"&client=" + client+"&name="+dealphrase(name);
	logObj.open("POST","log_modify.php",false);
	logObj.setRequestHeader("Content-Length",senddata.length);
	logObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	logObj.send(senddata);
	Line.clientArr[client].nickName = name;
	//$("name").innerHTML = name;
}
function showSwitch(){
	if(!isSwitch) return alert('该功能还没有开通，请尽快开通！');
	var client = $("client").value;
	if(!client) { 
		return (Line.showHelpTips('线路还未连接成功！'));
	}
	if(Line.clientArr[client].status == 'close')
		return alert("客户已经离开");
	$('switch_div').style.display==''?$('switch_div').style.display='none':$('switch_div').style.display='';
}
function sendSwitch()
{
	var lineName = $("lineList").value;
	var swicthCause = $("switchBecause").value;
	var client = $("client").value;
	if(lineName==null || swicthCause==null || lineName.trim()=="" || swicthCause.trim()=="")return(alert("请选择客服!"));
	$("flashPhoto").sendSwitch(lineName, client, swicthCause);
	var html = sendSwitchHTML;
	alert(html);
	alert("sendSwitch"+lineArr[lineName]);
	html = html.replace(/\{#lineName#\}/g, lineArr[lineName]);
	html = html.replace(/\{#client#\}/g, client);
	html = html.replace(/\{#switchLine#\}/g, lineName);
	Line.write(html,client);
	$("switch_div").style.display = "none";
}

function showIPArea(ip,client){
	var senddata="sid="+sid+"&ip=" + ip;
	logObj.open("POST","ipArea.php",false);
	logObj.setRequestHeader("Content-Length",senddata.length);
	logObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	logObj.onreadystatechange = function(){
		if ( logObj.readyState==4 ) {
			var recvdata = logObj.responseText;
			if (recvdata == ''){
				return;
			}
			Line.clientArr[client].ip = recvdata;
			if($('client').value == client) $('ip').innerHTML = recvdata;
		}
	}
	logObj.send(senddata);
}

function evaluaLine(evalua, client){
	var senddata="arg=phwyying4023255&sid="+sid+"&action=evalua&line_id"+line_id+"&client="+client+"&evalua=" + evalua;
	logObj.open("POST","log_modify.php",false);
	logObj.setRequestHeader("Content-Length",senddata.length);
	logObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	logObj.send(senddata);
}

function endCall(client){
	var senddata="arg=phwyying4023255&sid="+sid+"&action=end&line_id="+line_id+"&client="+client;
	logObj.open("POST","log_modify.php",false);
	logObj.setRequestHeader("Content-Length",senddata.length);
	logObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	logObj.send(senddata);
}

function getLineChatlogs(client)
{
	var senddata="arg=phwyying4023255&sid="+sid+"&action=get&line_id="+line_id+"&client=" + client;
	logObj.open("POST","log_modify.php",false);
	logObj.setRequestHeader("Content-Length",senddata.length);
	logObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	logObj.onreadystatechange = function(){ 
		if ( logObj.readyState==4 ) { 
			var recvdata = logObj.responseText;
			if (recvdata == 0){
				return;
			}
			var recvdatas = unescape(recvdata).split("-|");
			var contents = recvdatas[0].split("<p>").reverse();
			var end = (contents.length-1)>6?6:contents.length-1;
			contents = contents.slice(0,6).reverse().join("<p>");
			var lastData = recvdatas[1];
			var name = recvdatas[2];
			if(contents.trim() == "" || contents.trim() == null)return;
			Line.write("--------", client);
			Line.write(contents, client);
			Line.write("上一次来访时间是 "+lastData+"", client);
			Line.write("--------", client);
			name = name||Line.clientArr[client].nickName;
			Line.clientArr[client].nickName = name||Line.clientArr[client].nickName;
		/*	for (var i=0; i<$$("Nickname_"+client).length; i++){
				$$("Nickname_"+client)[i].innerHTML = name;
			}*/
		}
	}
	logObj.send(senddata);
}

function editLogContent(content, client)
{
	var senddata="arg=phwyying4023255&sid="+sid+"&action=edit&line_id="+line_id+"&client="+client+"&content=" + dealphrase(content);
	logObj.open("POST","log_modify.php",false);
	logObj.setRequestHeader("Content-Length",senddata.length);
	logObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	logObj.onreadystatechange = function(){
		if ( logObj.readyState==4 ) {
			var recvdata = logObj.responseText;
			if (recvdata == 0){
				return;
			}
		}
	}
	logObj.send(senddata);
}

function closeClient(id){
	if(!id) Line.showHelpTips("还没有选中客户！");
	else{
		if(!confirm("你确定要中断会话？")) return;
		Line.clientDisconnect(id);
		Line.clientlist.remove(id);
		if(!$('clientlist').innerHTML) $('closeImg').style.display = 'none';
	}
}

function delphrase(id){
	if (!confirm(infos[58]))return;
	var phrase=$('phrase_words_'+id).innerText;
	var senddata="arg=phwyying4023255&sid="+sid+"&action=del&line_id="+line_id+"&IDIPM="+ipm_id+"&phrase=" + dealphrase(phrase);
	phraseObj.open("POST","phrase_modify.php",false);
	phraseObj.setRequestHeader("Content-Length",senddata.length);
	phraseObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	phraseObj.onreadystatechange = function(){ 
		if ( phraseObj.readyState==4 ) { 
			var recvdata = phraseObj.responseText;
			if (recvdata == 0){
				alert("操作失败！");
				return;
			}
			$("phrase"+id).style.display="none";
		}
	}
	phraseObj.send(senddata);
}

function editphrase(id){
	var phrase = $('phrase_words_'+id).innerText;
	var phrase_all = prompt(infos[57],phrase);
	if (phrase_all == null||phrase_all.trim() == "") return;
	var senddata="arg=phwyying4023255&sid="+sid+"&action=edit&line_id="+line_id+"&phrase1=" + dealphrase(phrase_all) + "&phrase2=" + dealphrase(phrase);
	phraseObj.open("POST","phrase_modify.php",false);
	phraseObj.setRequestHeader("Content-Length",senddata.length);
	phraseObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	phraseObj.onreadystatechange = function(){ 
		if ( phraseObj.readyState==4 ) { 
			var recvdata=phraseObj.responseText;
			if (recvdata == 0){
				alert("操作失败！");
				return;
			}
			var phrase_pinyi = recvdata;
			$("phrase_pinyin_"+phrase_id).innerText = phrase_pinyi;
			$("phrase_words_"+id).innerText=phrase_all;
			$("phrase_title_"+id).title=phrase_all;
			$("phrase_title_"+id).onclick=function(){
				sendphrase(id);
			}
			$("phrase_title_"+id).innerText=_substring(phrase_all.replace(/(\n)/gi," "),14);
			$("edit_"+id).onclick=function(){
				editphrase(id);
			}
		}
	}
	phraseObj.send(senddata);
}

function addphrase(){
	var phrase=prompt(infos[57],"");
	if (phrase==null||phrase.trim()=="")return;
	var senddata="arg=phwyying4023255&sid="+sid+"&action=add&line_id="+line_id+"&IDIPM="+ipm_id+"&phrase="+dealphrase(phrase);
	phraseObj.open("POST","phrase_modify.php",false);
	phraseObj.setRequestHeader("Content-Length",senddata.length);
	phraseObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	phraseObj.onreadystatechange = function(){ 
		if ( phraseObj.readyState == 4 ) { 
			var recvdata=phraseObj.responseText;
			//alert(recvdata);
			//var recvdata=recvdata.split("&");
			if (recvdata == 0){
				alert("操作失败！");
				return;
			}
			var phrase_pinyi = recvdata;
			var phrase_id = window.phrase_id = window.phrase_id + 1;

			var li="	<div class=\"font_php\" id=\"phrase"+phrase_id+"\">";
			li+="		<span id=\"phrase_title_"+phrase_id+"\" onclick=\"sendphrase("+phrase_id+");\"></span>";
			li+="<span id=\"phrase_words_"+phrase_id+"\" style=\"display:none\"></span>";
			li+="<span id=\"phrase_pinyin_"+phrase_id+"\" style=\"display:none\"></span>";
			li+="<input type=\"image\" class=\"phrase_edit\" src=\"images/edit.gif\" onclick=\"editphrase("+phrase_id+")\" id=\"edit_"+phrase_id+"\"/>";
			li+="<input type=\"image\" class=\"phrase_del\" src=\"images/del.gif\" onclick=\"delphrase("+phrase_id+")\"/>";
			li+="	</div>";
			$("phrase_li").innerHTML += li;
			$("phrase_title_"+phrase_id).title = phrase;
			$("phrase_title_"+phrase_id).style.cursor = "pointer";
			$("phrase_title_"+phrase_id).innerText =_substring(phrase.replace(/(\n)/gi," "),14);
			$("phrase_words_"+phrase_id).innerText = phrase;
			$("phrase_pinyin_"+phrase_id).innerText = phrase_pinyi;
		}
	}
	phraseObj.send(senddata);
}

function getPhraseList()
{
	var keyword = $("message").value;
	var arr = new Array();
	
	for(var i=0;i<=window.phrase_id;i++)
	{
		if(typeof ($("phrase_words_"+i).innerText) == "undefined")continue;
		if($("phrase"+i).style.display=="none") continue;
		var phrase = $("phrase_words_"+i).innerText;
		var phrase_pinyin = $("phrase_pinyin_"+i).innerText;
		if(phrase == keyword) continue;
		if(keyword == phrase.substr(0, keyword.length))	arr.push(phrase);
		else if(keyword.toLowerCase() == phrase_pinyin.substr(0, keyword.length).toLowerCase()) arr.push(phrase);
	}
	return arr;
}

function toinsertlink(){
	$("link_div").style.display=$("link_div").style.display==""?"none":"";
	clearLinking = window.setInterval(function(){window.clearInterval(clearLinking);clearLinking=null;}, 10);
}

function insertlink(linkurl,linktext){
	if (linkurl==null || linkurl.trim()=="") return;
	if (linktext.trim()=="")linktext=linkurl;
	if (linkurl.substring(0,4).toLowerCase()!="http"){
		linkurl="http://"+linkurl;
	}
	var html="[URL="+linkurl+"]"+linktext+"[/URL]";
	$("message").value += html;
	$("message").focus();
	toinsertlink();
}

function insertimg(imagePath){
	if (imagePath==null||imagePath.trim()==""||imagePath.trim()=="http://")return;
	$("img_div").style.display="none";
	if (imagePath==null||imagePath.trim()==""||imagePath.trim()=="http://")return;
	var html="[IMG]"+imagePath+"[/IMG]";
	$("message").value+=html;
}

function toinsertsmile(){
	$("face_div").style.display=$("face_div").style.display==""?"none":"";
	clearFaceing = window.setInterval(function(){window.clearInterval(clearFaceing);clearFaceing=null;}, 10);
}

function insertsmile(smilename){
	$("face_div").style.display="none";
	$("message").value+=smilename;
}

function upload_file(){
	if($("upload_div").style.display!='none'){
		$("upload_div").style.display='none';
		return;
	}
	$("upload_iframe").src="upload.php";
	$("upload_div").style.display='';
	clearuploading = window.setInterval(function(){window.clearInterval(clearuploading);clearuploading=null;}, 10);
}

function closeUpload(){
	$("upload_div").style.display="none";
}

function uploadEnd(fileName,realName){
	if(!realName) realName = fileName;
	if(!fileName && !realName) {closeUpload();return;}
	$("message").value = "[URL=http://"+upHost+"/data/IPM/" + fileName + "]"+ realName + "[/URL]";
	if(Line.sendMessage()){
		Line.write("<font color=\"green\">文件发送成功</font>");
	} 
	closeUpload();
}

function updateSession(){
	var senddata="";
	sessionObj.open("POST","updateSession.php",false);
	sessionObj.setRequestHeader("Content-Length",senddata.length);
	sessionObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	sessionObj.onreadystatechange = function(){ 
		if ( sessionObj.readyState == 4 ) { 
			var recvdata=sessionObj.responseText;
			return;			
		}
	}
	sessionObj.send(senddata);
}

function sendphrase(id){
	$("message").value = $("phrase_words_"+id).innerText;
}

function dealphrase(phrase){
	phrase=phrase.replace(/\+/g,":cbaplusabc:");
	phrase=escape(phrase);
	return phrase;
}

function toinsertimg(){
	$("img_div").style.display=$("img_div").style.display==""?"none":"";
	clearImging = window.setInterval(function(){window.clearInterval(clearImging);clearImging=null;}, 10);	
}

function showme(show){
	if(show=='center'){
		 $('browser_div').style.display='none';
		 $('center').style.display=''
	}
	else{
		 $('browser_div').style.display='';
		 $('center').style.display='none'
	}
}   

function autoReply(){
	if(isAutoReply && window.confirm("确定取消自动回复？")){
		isAutoReply = 0;
		$('button-12').id= 'button-11';
		return;
	}
	autoReplyMessage =window.prompt("请输入自动回复与语句",autoReplyMessage||'')||autoReplyMessage;
	if(!autoReplyMessage)return;
	$('button-11').id= 'button-12';
	isAutoReply=1;
}

function setUsername(name){
	alert(name);
}

document.onkeydown =  function(event){
	event = window.event || event;
	if(!event.altKey || event.keyCode!=65)return;
	showUnreadMessage();
}

function showUnreadMessage(){
	var clientArray = new Array();
	clientArray = Line.getClientArr();
	if(!clientArray)return;
	var id ='';
	try{
		while(id = clientArray.shift()){
			if($('client_img_offline_move_'+id).style.display =='' ||$('client_img_move_'+id).style.display ==''){
				$("client_button_"+id).click();
				break;
			}
		}
	delete clientArray;
	}catch(e){}
}

 window.setInterval("updateSession()",600000);