<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MWEB Chat</title>
<script language="JavaScript" src="/MWEB/resources/javascript/jquery-1.3.2.min.js"></script> 
<script language="JavaScript" src="/MWEB/resources/javascript/json2.js"></script> 
<script language="JavaScript" src="/MWEB/resources/javascript/mwebc2s.js"></script> 
<SCRIPT LANGUAGE="JavaScript">
//set up MWEB conenction

mwebc2s.registerChannelPacketCallback(
		function(from,channelName,data){
			console.log("received packet: "+data);
			var packet = JSON.parse(data);
			if (packet.action == "userJoin") {
				userJoin(packet.userName);
			} else if (packet.action == "userLeave") {
				userLeave(packet.userName);
			} else if (packet.action == "publicMessage") {
				publicMessage(from,packet.message);
			} else if (packet.action == "privateMessage") {
				privateMessage(from,packet.message);
			}
		}
);		

function userJoin(userName){
	var chatters = document.getElementById("chatters");
	chatters.options[chatters.options.length] = new Option(userName,userName, false,false);
}

function userLeave(userName){
	var chatters = document.getElementById("chatters");
	for(var i=0;i<chatters.options.length-1;i++){
		if (chatters.options[i].text == userName){
			chatters.remove(i);
		}
	}
}

function publicMessage(from,message){
	receiveMessage(from+": "+message);
}

function privateMessage(from,message){
	receiveMessage("Private from "+from+": "+message);
}

mwebc2s.connect(function(packet){
	console.log("connected CB >>>");
	$.post('ChatTestServlet',{'action':'joinChat'});
	console.log("connected CB <<<");
});
 

function sendPublicMessage(text){
	$.post('ChatTest',{'action':'publicMessage','message':text});
}

function sendPrivateMessage(to, text){
	$.post('ChatTest',{'action':'privateMessage','to':to,'message':text});
}

function receiveMessage (text) {
    document.getElementById("output").value  += text+"\n";
}


</script>
</head>
<body>
<FORM  NAME="chatBox" ACTION="" METHOD="GET">
<TEXTAREA id="output" NAME="outputbox" COLS="40" ROWS="8">
</TEXTAREA>
<SELECT id="chatters" name="ChattersBox" SIZE="8" WIDTH="40" style="width: 193px">
</SELECT>
<P>
Enter a message: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE="">
<INPUT TYPE="button" NAME="button" Value="SEND" onClick="sendMessage(this.form.inputbox.value)">

</FORM>

</body>
</html>