function updatePage( )
{
	var f = window.location.href;
	var start = f.lastIndexOf( '/' ) + 1;
	var id = f.substr( start );
	var last = $( '.textline:last' ).attr( 'id' );
	$.post( '/chat/' + id + '/updateroom', {lastSeen: last}, updatePageResp, 'json' );
}

function updatePageResp( resp )
{
	var users = resp.users,
	    msgs = resp.msgs;

	// Update User List
	var userlist = $( '#user-list' );
	userlist.empty( );
	var append = '';
	    i = 0,
	    user = users[i];

	while( user )
	{

		append += '\n<li class="';
                if( 1 == user.isgm )
                {
                        append += 'gm';
                }
                append += '" id="u' + user.uid + '">';
                append += '<span class="username" id="su' + user.uid + '">';
                append += user.username;
                append += '</span> - <span class="charname" id="sc' + user.cid + '">';
                if( 1 == user.isgm )
                {
                        append += 'Game Master';
                } else {
                        if( user.cname )
                        {
                                append += user.cname;
                        }
                }
                append += '</span></li>';

		user = users[++i];
	}

	userlist.append( append );
	append = '';
	
	// Update Chat Room
	var chat = $( '#chat-room' );
	append = '';
	i = 0;
	var msg;

	if( msgs )
	{
		msg = msgs[i];
	}

	while( msg )
	{
		append = '<div class="textline" id="' + msg.id + '">';
                append += '<span class="time">' + msg.timesent + '</span> ';
                if( 0 != msg.cid )
                {
                        append += '<span class="charname">' + msg.name;
                } else {
                        append += '<span class="username">' + msg.username;
                }
                if( 'whisper' === msg.type )
                {
                        append += ' whispers';
                        if( msg.gmid === msg.sid )
                        {
                                append += ' to ' + msg.wname;
                        }
                }
                append += '</span>';
                append += '<span class="' + msg.type + '">';
                if( 'action' !== msg.type )
                {
                        append += ':';
                }
                append += ' ' + msg.message + '</span></div>';

		msg = msgs[++i];
	}

	chat.append( append );

	// If at bottom of chat, scroll.
	// Else, do animation to show new message
	// DO NOT CHANGE SCROLL POSITION!

	setTimeout( updatePage, 500 );
}
