var socket;
if (!window.WebSocket) {
	window.WebSocket = window.MozWebSocket;
}
//if (window.WebSocket) {
//	start();
//} else {
//	alert("Your browser does not support Web Socket.");
//}

function send(message) {
	if (!window.WebSocket) { return; }
	if (socket.readyState == WebSocket.OPEN) {
		socket.send(message);
	} else {
//		alert("The socket is not open.");
	}
}

var retry = 0;

function reconnect(nofId, wsurl) {
	let to = setTimeout(function(){
		if(retry>3) {
			//sessionLogout();
			clearTimeout(to);
		} else {
			retry++;
			start(nofId, wsurl)
		}
	}, 5000);
}

function start(nofId, wsurl){
	//var socketUrl = "ws://"+wsurl+"/websocket";

	var socketUrl;
	if (window.location.protocol !== 'https:') {
	    socketUrl = "ws://"+wsurl+"/websocket";
	} else {
		socketUrl = "wss://"+wsurl+"/websocket";
	}

	socket = new WebSocket(socketUrl);
	socket.onmessage = function(event) {
		processWs(nofId, wsurl, event.data);
	};
	socket.onopen = function(event) {
//		console.log("Web Socket opened! notificationId===="+nofId);
		send(nofId);
	};
	socket.onclose = function(event) {
//		console.log("Web Socket closed!");
		reconnect(nofId, wsurl)
	};
}

function processWs(nofId, wsurl, data){
	if(location.host.includes('demolx2.com')) {
		let status = data.status;
		if (status && status == 10) {
			reconnect(nofId, wsurl);
			return;
		}

		processWsData(JSON.parse(data) || data);
		return;
	}
	// console.log("processWs data==="+data)
	if(data=="-1"){
		//sessionLogout();
	}

	if (data.indexOf('[]') == 0) {
		//console.log('in empty');
		return false;
	}
	else if (data.indexOf('[[') != -1) {
		//console.log('in list');
		data = jQuery.parseJSON(data);
		for ( var i = 0; i < data.length; i++) {
			var obj = data[i];
			processWsData(obj);
		}
	}
	else {
		//console.log('in single');
		data = jQuery.parseJSON(data);
		processWsData(data);
	}
}
