var last = '0';
$(function() {
	$.ajaxSetup({type: 'POST', url: '/server.php', dataType: 'text'});
	function update_chat() {
		$.ajax({
			data: {last: last},
			success: function(o) {
				if (o) {
					o = o.split('\0');
					last = o[0];
					for (i = 1; i < o.length; i += 3) {
						x = $('<tr />').prependTo('#hist').attr('title', o[i]);
						$('<td />').text(o[i+1]).appendTo(x).attr({valign:'top',align:'right'}).css('font-style', 'italic');
						$('<td />').text(o[i+2]).appendTo(x).css('background', '#ffff80');
					}
				}
			},
			complete: function() { setTimeout(update_chat, 1000); }
		});
	}
	$('#msg').keypress(function(e) { if (e.keyCode == 13) $('#go').click(); });
	$('#go').click(function() {
		$('#hist td').css('background', '');
		msg = $('#msg').val();
		if (msg == '') return;
		$.ajax({
			data: {user: $('#user').val(), msg: $('#msg').val()},
			success: function(o) {
				switch (o) {
					case '': $('#msg').val(''); break;
					case '1': alert('Error: IP address / username conflict.'); break;
					case '2': alert('Error: No real message to submit.'); break;
				}
			}
		});
	});
	$('#user').focus();
	update_chat();
});