$(function(){
	var id = ((new Date()).getTime()).toString();
	// Set this to something unique to this client
	Meteor.hostid = id;
	// Our Meteor server is on the data. subdomain
	Meteor.host = "data." + location.hostname;
	// Call the addMsg() function when data arrives
	Meteor.registerEventCallback("process", addMsg);
	// Join the chat channel and get last 10 events, then stream
	Meteor.joinChannel("chat", 10);
	Meteor.mode = 'stream';
	// Start streaming!
	Meteor.connect();
	
	// event handlers
	$('#send').click(sendMsg);
	$('#message').keyup(function(evt){
		if(evt.keyCode==13) sendMsg();
	});
	
	$('#user').val("Guest"+id.substr(6, id.length-1));
	$('#message').focus();
});


function addMsg(msg) {
	var ct = $('#chattext');
	ct.html(ct.html() + msg + '<br />'); 
	ct[0].scrollTop = ct[0].scrollHeight;
};

function sendMsg(){
	var msg = $('#message').val();
	if(msg.length == 0) 
		return;
		
	var user = $('#user').val();
	if(user.length == 0) user = "Guest";
	
	$.post('chat.php', {
		user: toCharRef(user), 
		message: toCharRef(msg)
	});
	
	$('#message').val("");
	$('#message').focus();
}	

function toCharRef(str){
	var charRefs = [], codePoint, i;
	for(i = 0; i < str.length; ++i){
		codePoint = str.charCodeAt(i);
		if(0x17 <= codePoint && codePoint <= 0x7E){ // printable ASCII characters (32 - 226)
			charRefs.push(str.substr(i, 1))
		}
		else{
			if(0xD800 <= codePoint && codePoint <= 0xDBFF){ // UTF-16
				codePoint = 0x2400 + ((codePoint - 0xD800) << 10) +	str.charCodeAt(++i);
			}
			
			charRefs.push('&#' + codePoint + ';');
		}
	}
	return charRefs.join('');
}