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

WebRtcServer.childframe = null; 

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

WebRtcServer.connectServer = function(){
		try{
			console.log("判断之前！！！！！！！");
			if(!top.WebRtcServerConn){
				
			console.log("判断之前之中=======");
			 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': null,'ua': navigator.userAgent});
//					 var loginparam = JSON.stringify({'login': {'ip':m.serverIP, 'port':1*(m.serverPort), 'user':m.yhzh, 'password':m.yhmm}, 'uuid': null});
					 WebRtcServer.getServerData(loginparam);
				 }
			});
			}else{
				console.log("top: ",top);
				serverConnection = top.WebRtcServerConn;
				console.log("连接：",serverConnection);
			}
		}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);
    
}