// TodaysMeet
// Contains functions to read and write a room via the TodaysMeet API.

/**
 * array  room_read ( str room [, int timestamp] )
 *
 * @arg string room the name of the room
 * @arg int timestamp a unix timestamp
 * @return array messages an array of messages
 */
function room_read ( _room, _max_id, _timestamp, _callback )
{
	// Store the results
	var _messages = [];
	/**
	 * Run ajax query. Currently uses Prototype
	 */
	new Ajax.Request('/'+_room+'/messages.json',
					 {method:'get',
					 parameters:{'since':_timestamp,'since_id':_max_id},
					 requestHeaders:{'If-Modified-Since':_timestamp},
					 evalJSON:'force',
					 onSuccess: function(a,data) {
						 Interactive(false);
						 
						 if ( !data ) {
							 try {
								 data = a.responseText.evalJSON();
							 } catch ( e ) {
								 Error("There was a problem processing the messages.<br />Please refresh the page.");
								 clearInterval(window.updater);
								 return;
							 }
						 }

						 window.lastChecked = parseInt(data.retrieved);
						 var maxId = parseInt(data.max_id);
						 if (maxId > 0) window.maxId = maxId;

						 for(var i=0;i<data.messages.length;i++){
							var m = new Message;
							m.id      = data.messages[i].id;
							m.name    = data.messages[i].sender_name;
							m.created = parseInt(data.messages[i].created);
							m.message = linkFilter(data.messages[i].content);
							m.source  = data.messages[i].source;
							_messages[i] = m;
						 }
						 
						 Interactive(false);
						 _callback(_messages);
					 },
					 onFailure: function () {
						Error("Could not read messages."); 
					 }}
					 );
}

/**
 * linkFilter turns http:// ... into a link
 *
 * @param string string
 * @return string
 */
var linkRegex = /((?:http:|https:|ftp:|mailto:)\/\/[\w\.\/,\-_]+[^\.,])/gi;
var linkReplace = '<a href="$1" rel="nofollow" target="_blank">$1</a>';
function linkFilter ( string )
{
	return string.replace(linkRegex, linkReplace);
}

/**
 * bool  room_post ( str room, obj message )
 * 
 * @arg string room the room to post
 * @arg obj message a Message object (see below)
 * @return bool status
 */

/**
 * Message
 *
 * A prototype for the "Message" object, fed to
 * room_post and returned from room_read.
 */
function Message () {}
Message.prototype.name = null;
Message.prototype.message = null;
Message.prototype.created = null;
Message.prototype.id = null;
Message.prototype.source = {'name':'web','website':''};
