var socketVoice = []; //websocket对象数组
var getTimeStringVoice = new Date().getTime().toString();
var objNew ={}

//创建socket连接功能函数  
function connectVoice(wsobj) {
	//浏览器支持？
	if("WebSocket" in window) {
		var extno = $.cookie("extno")
		if(!extno){
			return
		}
//		var extno = "1001"
		var host = huayi.config.translation_socket+"/"+extno
		console.log(host)
		socketVoice = new WebSocket(host);
		try {
			//连接事件
			socketVoice.onopen = function(msg) {
				console.log(wsobj + ":连接已建立！")
				$("#clickElementVoice").show()
//				videoReqExten()
			};
			//错误事件	
			socketVoice.onerror = function(msg) {
				console.log("错误：" + msg.data)
			}
			//消息事件
			socketVoice.onmessage = function(msg) {
       			 //最后转回json对象
      			data = eval('(' + msg.data + ')');
      			console.log(msg.data)
      			console.log(data.event,data.data.label,data.data.content);
      			switch (data.event.toLowerCase()) {
					case "translation":
                        translationBack(data);
                        break; //签入
                }
//				console.log(wsobj+"消息接收:"+data.data)
			};
			//关闭事件
			socketVoice.onclose = function(msg) {
				connectVoice(1)
				console.log(wsobj + ":socket closed!")
			};
		} catch(ex) {
			log(ex);
		}
	} else {
		// 浏览器不支持 WebSocket
		alert("您的浏览器不支持 WebSocket!");
	}

}
//申请注册的分机
 function videoReqExten() {
// 	objNew.Type = "VideoReqExten";
// 	objNew.AgentID = getTimeStringVoice.substring(getTimeStringVoice.length-9);
//	objNew.AgentExten = "111";
   	SendVoice()
 }
 //发送
function SendVoice() {
    if (socketVoice.readyState != socketVoice.OPEN) {
        reconnect();
    }
    if (socketVoice.readyState ==socketVoice.OPEN) {
        console.log(new Date() + "  send  " + JSON.stringify(objNew));
        socketVoice.send(JSON.stringify(objNew));
        objNew.Type = "";
    }
}

function translationBack(data) {
	if(data.data.label === "坐席"){
		$('<div class="serviceChat"><img src="img/kefuTx.png"><div class="serviceChatText">'+
			data.data.content+'</div></div>').appendTo($(".voiceToTextContext"))
	} else if (data.data.label === "客户") {
		$('<div class="clientChat"><img src="img/youkeTx.png"><div class="clientChatText">'+
			data.data.content+'</div></div>').appendTo($(".voiceToTextContext"));
	}
	scrollTopFn("scrollVoice")
}
