/**
 * @author Paul Price
 * Who needs MooTools' Class() method?
 */

var colorChanger = DUI.Class.create(APE.Client.prototype, {
	// set default options
	options:{
		debug: false,
		select: null
	},
	
	init: function(core, options){
		this.core = core;
		this.options = options;

		// do the following every time we get a new user
		this.addEvent('pipeCreate', this.setup);
		
		// 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);
		
		// when we want to send data
		this.onCmd('send', this.cmdSend);
		
		// and when we recieve data
		this.onRaw('data', this.rawData);

		// start the session with a random name!
		var username = prompt("Hey good lookin', what's your name?", String((new Date()).getTime()).replace(/\D/gi,''));
		this.core.start(username);
	},
	
	setup: function(type, pipe, options){
		// add an event listener on our selectbox
		this.options.select.change(function(){
			// get the select box value
			color = $("option:selected", this).val();
			
			// set the background of the document to the color chosen
			$("body").css("background-color", color);
			
			// send the new color to the APE server
			pipe.send(color);
		});
	},
	
	cmdSend: function(pipe, sessid, pubid, message){
		if(this.options.debug)
			$("<span>&nbsp;&nbsp;&nbsp;&nbsp;" + this.core.user.properties.name + " changed the bg color to " + message + "</span><br />").prependTo("#debug");
	},
	
	rawData: function(raw, pipe){
		if(this.options.debug)
			$("<span>&nbsp;&nbsp;&nbsp;&nbsp;" + raw.datas.sender.properties.name + " changed the bg color to " + raw.datas.msg + "</span><br />").prependTo("#debug");
		
		// set the selectboxes value to match
		this.options.select.val(raw.datas.msg);
		
		// set the color
		$("body").css("background-color", raw.datas.msg);
	},
	
	createUser: function(user, pipe){
		user.element = $("<span>" + user.properties.name + " has joined bgColor</span><br />").prepend("<img src='bullet_green.png' />").prependTo("#debug");
	},
	
	deleteUser: function(user, pipe){
		$(user.element).text(user.properties.name + " has left bgColor").css("color", "#666666").prepend("<img src='bullet_red.png' />");
	}
});
