function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

function dealphrase(phrase){
	phrase=phrase.replace(/\+/g,":cbaplusabc:");
	phrase=escape(phrase);
	return phrase;
}
var clearTypingClose = null;
function propertychange(){
	client.sendInput();
}

function popConfrimBeforUnload()
{
	if(client.status!='connect')
		return;
	else
		return true;
}

function rejuctVoice(){
	$('audio_span').innerHTML = lineName+'拒绝您的语音请求!';
	$('audio_span').id = 'audio_span_bak';
}
function acceptAudio(){
	$('audio_span').innerHTML = lineName+'接受你的语音请求';
	$('audio_span').id = 'audio_span_bak';	
}

function cancelAudio()
{
	$("audio_span").innerHTML = lineName+"已经取消语音请求!";
	$("audio_span").id = "audio_span_bak";
}

function cancelAudio_send()
{
	$("audio_span").innerHTML = "您取消语音请求!";
	$("audio_span").id = "audio_span_bak";
}


function showLeaveMessage(){
	if(client.status=="connect") {
		return;
	}
	$("leaveMessage_iframe").src="leaveMessage.php?line_id="+line_id+"&ipm_id"+ipm_id+"&client="+cid+"&refferer="+refferer;
	$("leaveMessage_div").style.display = 'block';
}

function leaveMessage(){
	alert("留言成功！窗口现在将会自动关闭。");
	window.close();
}

function closeLeaveMessage() {
	$("leaveMessage_div").style.display = "none";
	window.close();
}

function uploadEnd(fileName,realName){
	if(!realName) realName = fileName;
	if(!fileName && !realName) {closeUpload();return;}
	$("message").value = "[URL=http://"+upHost+"/data/IPM/" + fileName + "]"+ realName + "[/URL]";
	if(".gif.jpeg.jpg.bmp".indexOf(realName.substr(realName.length-3,3) )!=-1)
		$("message").value +="\r\n\r\n [IMG]http://"+upHost+"/data/IPM/"+fileName+"[/IMG]";
	client.sendMessage();
	client.write("<font color=\"green\">文件发送成功</font>");
	closeUpload();
}

function evalua_open(){
	if (client.evaluaable != true ) {
		alert("还没有建立连接，不能进行评分");
		return;
	}
	$("evalua_div").style.display = "";
	clearevaluaing = window.setInterval(function(){window.clearInterval(clearevaluaing);clearevaluaing=null;}, 10);
}

function editOffLineLogContent(content,cid){
	content += "<br>";
	var senddata="sid="+sid+"&action=edit&line_id="+line_id+"&client="+cid+"&content=" + dealphrase(content)+"&mode=unread";
	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="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 lastCursorPos() 
{
	cursorPos = getCursorPos('message');
}

function parseStr(str, name)
{
	var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
	if (reg.test(str)) return unescape(RegExp.$2.replace(/\+/g, " "));
	return "";
}

window.onfocus = function(){
	try{$("message").focus();}catch(e){}
}

function toinsertsmile(){
	if(client.status !="connect") {
		alert("还没有建立连接，不能发送表情");
		return;
	}
	$("face_div").style.display=$("face_div").style.display==""?"none":"";
	clearFaceing = window.setInterval(function(){window.clearInterval(clearFaceing);clearFaceing=null;}, 10);
}
function insertsmile(smilename){
	$("message").value+=smilename;
	$("img_url").value="http://";
	$("face_div").style.display="none";
}
function toinsertlink(){
	if(client.status !="connect") {
		alert("还没有建立连接，不能发送图片");
		return;
	}
	clearUrl=$("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 toinsertimg(){
	if(client.status !="connect") {
		alert("还没有建立连接，不能发送图片");
		return;
	}
	clearImg=$("img_div").style.display=$("img_div").style.display==""?"none":"";
	clearImging = window.setInterval(function(){window.clearInterval(clearImging);clearImging=null;}, 10);
}

function insertimg(imagePath){
	$("img_div").style.display="none";
	if (imagePath==null||imagePath.trim()==""||imagePath.trim()=="http://")return;
	var html="[IMG]"+imagePath+"[/IMG]";
	$("message").value+=html;
	$("message").focus();
}
function saveas() {
	try {
		var savestyle='<style type="text/css"> <!--body{margin: 0px; padding: 0px 0px 0px 0px; border: 0px;FONT-SIZE: 9pt; FONT-FAMILY: Tahoma;}td { font-family: Tahoma; font-size: 9pt; }p { margin-top:0px;margin-bottom:0px;FONT-SIZE: 9pt; FONT-FAMILY: Tahoma; }.dialog_content{ width:471px; height:276px;border:2px solid #e3ebf8; word-wrap: break-word; word-break: break-all; font-size:14px;padding-left:5px;padding-top:5px; text-align:left;}.receiver {	font-family: Geneva, Arial, Helvetica, sans-serif;	font-size: 12px;color:#009900;}.send {	font-family: Geneva, Arial, Helvetica, sans-serif;	font-size: 12px; 	color:#FF0000;}--></style>';
		var time=new Date();
		var filename=time.toLocaleDateString();
		filename=filename+" "+lineName+".htm";
		var winSave=window.open('about:blank','_blank','top=10000');
		winSave.document.open("text/html","gb2312");
		winSave.document.write("<html><head><base target=\"_blank\">"+savestyle+"</head><body><table width='300'>"+$("panels").innerHTML+"</table></body></html>");//outerHTML
		winSave.document.execCommand("SaveAs",true,filename);
		winSave.close();
	}
	catch(e){}
}

function closeEvalua(){
	$("evalua_div").style.display = "none";
}

function closeEditTel(tel){
	$("changetel_div").style.display="none";
	$("flashphoto").sendClientTelChange(tel);
}

function closeUpload(){
	$("upload_div").style.display="none";
}

function upload_file(){
	if (is_upload==1) {
		alert(infos[41]);
		return;
	}
	if (client.status != "connect" ) {
		alert(infos[40]);
		return;
	}
	if($("upload_div").style.display!='none') {
		$("upload_div").style.display='none';
		return ;
	}
	$("upload_div").style.display='';
	$("upload_iframe").src="upload.php";
	clearuploading = window.setInterval(function(){window.clearInterval(clearuploading);clearuploading=null;}, 10);
}

function editTel(){
	if (client.status != "connect" ) {
		alert(infos[60]);
		return;
	}
	clearTel=$("changetel_div").style.display=$("changetel_div").style.display==""?"none":"";
	clearTeling = window.setInterval(function(){window.clearInterval(clearTeling);clearTeling=null;}, 10);
}

function lineSwitch(switchLine)
{
	client.lineName = switchLine;
	client.showTips("&nbsp;与&nbsp;"+client.lineName+"&nbsp;交谈中");
	var senddata="arg=phwyying4023255&sid="+sid+"&action=lineInfo&line_id="+switchLine+"&IDIPM="+ipm_id;
	switchObj.open("POST","log_modify.php",false);
	switchObj.setRequestHeader("Content-Length",senddata.length);
	switchObj.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	switchObj.onreadystatechange = function(){ 
		if ( switchObj.readyState==4 ) { 
			var recvdata = switchObj.responseText;
			if (recvdata == 0){
				return;
			}
			$("chrName").innerHTML = parseStr(recvdata,"chrName");
			$("Email").innerHTML = parseStr(recvdata,"Email");
			$("Phone").innerHTML = parseStr(recvdata,"Phone");
			$("Mobile").innerHTML = parseStr(recvdata,"Mobile");
			$("MSN").innerHTML = parseStr(recvdata,"MSN");
			if(parseStr(recvdata,"Intro")) $("Intro").innerHTML = parseStr(recvdata,"Intro");
			lineName = parseStr(recvdata,"chrName");
			client.lineName = lineName;
			client.showTips("&nbsp;与&nbsp;"+client.lineName+"&nbsp;交谈中");
		}
	}
	switchObj.send(senddata);
	$('evalua').src = "evalua.php?ipm_id="+ipm_id+"&lineName="+switchLine+"&client="+cid;
	
}

client = {
	lineName:'', status:'',clearTyping:'',clearTypingHelp:null,cid:'',clearTypingClose:null,evaluaable:false,AStatus:false,
	colorArr:{
		error:"#ff0000"
	},
	
	initialize: function(lineName, id){
		this.lineName = lineName;
		this.cid = id;
	},
	
	_getAudioInviteTpls: function(){
		return "<span id='audio_span' name='audio_span'>"+this.lineName+"请求语音通话，<a href='#' onclick='client.acceptAudio()'>接受</a>\
				 或 <a href='#' onclick='client.rejectAudio()'>拒绝</a></span>";
	},
	
	_getSendTpls : function(){
		return "<font class='send'>我 &nbsp;" + getNowTime() + "</font><br/>";
	},

	_getLeaveMessageTpls : function(){
		return "<font class='send'>离线留言</font><br/>";
	},
	
	_getReceiverTpls: function(){
		return "<font class='receiver'>" + this.lineName + "&nbsp;" + getNowTime() + "</font><br/>";
	},
	
	buildMessage: function(str, item){
		for(var i in item)		{
			str = str.replace("{#" + i + "#}", item[i]);
		}
		return str;
	},
	
	connect: function(){
		this.showTips("正在连接请稍候");
	},
	
	onStatus: function(status){
		if(this.status != "reject") this.status = status;
		if(this.status == "connect"){
			this.showTips("与&nbsp;"+this.lineName+"&nbsp;交谈中");
		}
		else{
			this.showTips("连接已断开");
		}
	},
	
	sendMessage: function (){
		var InputMessage = $("message");
		var msg = InputMessage.value;
		msg=UBBEncode(msg);
		msg=UBBCode(msg.trim());
		if(msg == ""){
			this.showHelpTips("<font color=\"#ff0000\">不能发送空消息！</font>");
		}
		else if(msg.length >1000){
			this.showHelpTips("<font color=\"#ff0000\">每次最多只能发1000个字符!</font>");
		}
		else if(this.status == "close"){
			this.sendOffLineMessage(msg);	
		}
		else if(this.status == "reject"){
			var tips = "连接已断开，<br />请重新打开页面！";
			this.showHelpTips(tips);
		}
		else if(this.status == "connect"){
			$("flashPhoto").sendMessage(escape(msg));
			msg = this._getSendTpls() + msg;
			this.write(msg);
			this.saveChatLog();			
			InputMessage.value = "";
		}
		else if(this.status == "leaveMessage") {
			
			editOffLineLogContent(msg,this.cid); 
			InputMessage.value = "";
			this.status = "close";
		}
		InputMessage.focus();
	},

	sendOffLineMessage: function(message){
		$("flashPhoto").addLog("unread");
		message = this._getLeaveMessageTpls() + message;
		editOffLineLogContent("<p>"+message+"</p>",this.cid); 
		this.write(message);
		this.saveChatLog();		
		$("message").value="";
	},
	
	receiverMessage: function(message){
		playSound('msg');
		message = this._getReceiverTpls() + message;
        this.write(message);
		this.showLastMessageTimeTips();
		this.clearInput();
		focusMessageInput();
	},
	
	receiverAudioInvite: function(){
		var str = this._getAudioInviteTpls();
		this.write(str);
	},
	
	initAudio: function(flag){
		if(flag){
			$("flashPhoto").initAudio();
			this.write("您接受语音对话！")
		}
		$("flashPhoto").setInviteStatus("isAudio", flag);
	},
	
	acceptAudio: function(){
		this.AStatus = 'connect';
		$("flashPhoto").setInviteStatus(cid,"Accepted");
		$("audio_span").innerHTML = "您接受语音对话  ！";
		$("audio_span").id = "audio_span_bak";
		$("flashPhoto").initAudio();
	},
	
	closeVoice:function(){
		$("flashPhoto").closeVoice();
	},
	
	rejectAudio: function(){
		$("flashPhoto").setInviteStatus(cid,"Rejected");
		$("audio_span").innerHTML = "您拒绝语音对话！";
		$("audio_span").id = "audio_span_bak";
	},
	
	closeAudio:function(){
		$("flashPhoto").closeAudio();
		$("audio_span").innerHTML = "语音对话中断，如果您要退出会话，请直接关闭网页。";
		if(window.confirm("语音会话中断，你是否要关闭网页？")) {
			window.close();
		}
	},
	
	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);
	},
	
	/*
	sendAudioInvite: function(){
		$().sendAudioInvite();
	},
	*/
	sendVoiceInvite: function(){
		$('flashPhoto').sendVoiceInvite();
		this.write("<span id='audio_span'>发送语音请求成功,<a href='#' onclick='cancelAudio()'>取消</a>");
	},
	
	sendTips: function (tips){
		$("flashPhoto").sendTips(tips);
	},
	
	sendInput: function(){
		if($("message").value == "") return;
		$("flashPhoto").sendInput();
	},
	
	lineInput: function(){
		clearInterval(this.clearTyping);
		$("inputTips").style.display = "";
		this.clearTyping = window.setInterval(this.clearInput,5000);
	},
	
	clearInput: function(){
		clearInterval(this.clearTyping);
		$("inputTips").style.display = "none";
	},
	
	lineDisconnect: function(){
		//$("flashPhoto").addLog("unread");
		this.write("客服现已离线，请给我们留言。");
		this.status = "close";
		//window.setTimeout(showLeaveMessage(),100000);
	},
	
	acceptCall: function(){
		var message = "您好,有什么需要我帮忙的？";
		message = this._getReceiverTpls() + message;
		this.evaluaable = true;
		this.write(message);
		onlineSound();
	},
	
	showTips: function(tips){
		$("tips").innerHTML = tips;
	},

	showLastMessageTimeTips: function(){
		$("lastMessageTimeTips").innerHTML = "上一条消息收于 " + getNowTime();
	},

	claerContent: function(){
		$("message").value = "";
	},
	
	write: function(content){
		$("panels").innerHTML += unescape("<p>" + content + "</p>");
		$("panels").scrollTop = $("panels").scrollHeight - $("panels").clientHeight;
		window.focus();
	},
	
	clear: function(){
		$("panels").innerHTML = '';
	},
	
	close: function(){
	},
	saveChatLog:function(){
		chatLogArray = $("panels").innerHTML.split("</P>");
		len = chatLogArray.length;
		chatLog_last_six = "";
		if(len>10) {
			for(var i=(len-10);i<len;i++) {
				if(chatLogArray[i].indexOf("-----最近会话记录-----")==-1) 
				chatLog_last_six += chatLogArray[i]+"</P>";
			}
		}
		else {
			chatLog_last_six=$("panels").innerHTML;
		}
		writeCookie("chat_log"+line_id,chatLog_last_six,100);
	}
};
