/**
 * @author Paul Price
 */

APE.EsenAPE = DUI.Class.create(APE.Client.prototype, {
	// set default options
	options:{
		debug: false
	},
	
	init: function(core, options){
		this.core = core;
		this.options = options;
		
		// when a user joins, update the user list
		this.addEvent('userJoin', this.createUser);

		// when a user leaves, destroy them with mighty thunder!
		this.addEvent('userLeft', this.deleteUser);
		
		// this is when we receive a new SMS from Esendex via RPC.php
		this.onRaw('receivedsms', this.receivedSMS);

		// start the session with a random name!
		var username = String((new Date()).getTime()).replace(/\D/gi,'');
		this.core.start(username);
	},
	
	createUser: function(user, pipe){
		if(this.options.debug)
			user.element = $("<span>" + user.properties.name + " has joined EsenAPE</span><br />").appendTo("#debug");
	},
	
	deleteUser: function(user, pipe){
		if(this.options.debug)
			$(user.element).text(user.properties.name + " has left EsenAPE").css({"color":"#CC0000", "opacity":"0.3"});
	},

	receivedSMS: function(json_params){
		// lets get that JSON into an object, son!
		var params = eval('(' + urldecode(json_params.datas.value) + ')');

		// New SMS recevied so lets update the UI and send a jGrowl notification
		$('.received_sms table').find('tbody').prepend($('<tr>')
			.append($('<td>')
				.text(params.originator)
			)
			.append($('<td>')
				.text(params.receivedAt)
			)
			.append($('<td>')
				.text(params.body)
			)
		).end().find('tfoot').fadeOut();

		$.jGrowl('New SMS from ' + params.originator, {life: 5000});
	}
});
