var serverConnection ,peerConnection, isConnected , connectCount=0 ,isLoginOn ,loginCount=0 ,monid,uuid ;
function WebRtcServer(){}

WebRtcServer.childframe = null; 

WebRtcServer.setReqPage=function(childframe){
	//console.log("WebRtcServer.setReqPage:" + childframe.location.href);
	WebRtcServer.childframe = childframe;
}

WebRtcServer.connectServer = function(){
		try{
			if(!top.WebRtcServerConn){
				
			
			 serverConnection = new WebSocket('ws://127.0.0.1:17070/knockknock');
			 //serverConnection = new WebSocket('ws://10.10.10.203:17070/knockknock');
			 serverConnection.onmessage = WebRtcRespone.handleResponse;
			 serverConnection.onopen = function(evt) {
				//console.log("top WebRtcServer:Connection ready.");
				 top.WebRtcServerConn = serverConnection;
			    isConnected=true;
			 };
			 serverConnection.onclose = function(evt) {
				isConnected=false;
				top.serverConnection = null ;
				//console.log("top WebRtcServer:Connection closed.");
			 }; 
			 $.ajax({
				 type:'post',
				 dataType : 'json',
				 url:'menuConfigAction!getDacLoginInfo.do',
				 success:function(m){
					//console.log(m.serverIP +":"+m.serverPort);
					 var loginparam = JSON.stringify({'login': {'ip':m.serverIP, 'port':1*(m.serverPort), 'user':m.yhzh, 'password':m.yhmm}, 'uuid': $.uniqueId(),'ua': navigator.userAgent});
//					 var loginparam = JSON.stringify({'login': {'ip':m.serverIP, 'port':1*(m.serverPort), 'user':m.yhzh, 'password':m.yhmm}, 'uuid': null});
					 // var loginparam = JSON.stringify({'login': {'ip':'10.10.10.203', 'port':8886, 'user':'imps', 'password':'7070'}, 'uuid': $.uniqueId()});
					 WebRtcServer.getServerData(loginparam);
				 }
			});
			}else{
				serverConnection = top.WebRtcServerConn;
			}
		}catch(e){
			console.error(e);
			$.showMsg("获取视频地址失败，请先配置！");
			return;	
		}
		
}

WebRtcServer.login = function(loginparam){
    serverConnection.send(loginparam);
}

WebRtcServer.getServerData = function(loginparam){
	var checkConnect = function(){
		if(connectCount>=10){
			$.showMsg("尝试连接服务器失败！");
			$("#rtc-container").html("<p class=\"alert-title\">尝试连接服务器失败！</p>");
			return ;
		}
		connectCount++;
		if(isConnected){
			WebRtcServer.login(loginparam);
			checkOpen();
			return;
		}
		//console.log("rtcServer: try Connecting WS server...." + connectCount );
		
		setTimeout(checkConnect,3000);
		
	}
	
	var checkOpen = function(){
		if(loginCount>10){
			$.showMsg("尝试登录平台失败！");
			$("#rtc-container").html("<p class=\"alert-title\">尝试登录平台失败！</p>");
			return ;
		}
		
		if(isLoginOn){
			return;
		}
		
		//console.log("rtcServer: try login pt ...." +  (++loginCount));
		
		setTimeout(checkOpen,3000);
	}
	
	checkConnect();
}

WebRtcServer.serverHeartbeat = function() {
	setInterval(function(){
		serverConnection && serverConnection.send(JSON.stringify({'heartbeat':'hello', 'uuid': $.uniqueId()}));
		console.log("serverHeartbeat..........................");
	},5000);
    
}