/*
 * Copyright rphaven.com
 * Not for modification or use elsewhere 
 */
convertNL = function(replace) {
	var i = 0;
	return function (str) {
		i++
		return i < 5 ? replace : str
	}
};

two = function(x) {return ((x>9)?"":"0")+x};
msToReadable = function(ms) {
	var sec = Math.floor(ms/1000);
	var min = Math.floor(sec/60);
	sec = sec % 60;	
	var hr = Math.floor(min/60);
	min = min % 60;
	hr = hr % 60;
	
	t = hr + ":" + two(min) + ":" + two(sec);
	
	return t;
};

makeTimestamp = function(unixtime) {
	var date = unixtime ? new Date(unixtime * 1000) : new Date();
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var seconds = date.getSeconds();
	return hours + ':' + two(minutes) + ':' + two(seconds);
};

APE.Chat = DUI.Class.create(APE.Client.prototype, {
	options:{
		name: null,
		access: null,
		color: null,
		/*bgcolor: null,*/
		userid: null,
		accid: null
	},
	
	init: function(core, options){
		that = this;
		that.core = core;
		this.options = options;
		that.currentPipe = null;
		that.currentPMPipe = null;
		that.currentPubid = null;
		that.currentPM = null;
		that.currentChannel = null;
		that.currentPMPubid = null;
		that.currentRoom = null;
		that.selfPubid = null;
		this.els = {};
		that.globalRooms = {};
		that.userLocation = {};
		that.buddyList = {};
		that.buddyList.onlines = {"properties": {"name":"Buddies", "nusers":0, "users":{}}};
		that.buddyList.offlines = {"properties": {"name":"Offline", "nusers":0, "users":{}}};
		that.buddyList.ignores = {"properties": {"name":"Blocked", "nusers":0, "users":{}}};
		that.PMs = {};
		that.ISs = {};
		that.buttons.initAll();
		
		$("#jquery_jplayer").jPlayer({
			ready: function () {
				this.element.jPlayer("setFile", "sounds/imsound.mp3");
			}
		});
		
		$("#jplayer_boop").jPlayer({
			ready: function () {
				this.element.jPlayer("setFile", "sounds/boop.mp3");
			}
		});
		
		this.addEvent('load', this.login.prompt);
		//this.addEvent('ready', this.setup); // basic chat stuff on start.		
		this.addEvent('uniPipeCreate', this.createPM);
		this.addEvent('multiPipeCreate', function(pipe, options){
			if (pipe.name.charAt(0) != '*')	that.createChannel(pipe, options);
		});
		//this.addEvent('uniPipeDelete', this.closePM);
		this.addEvent('multiPipeDelete', this.leaveChannel);
		this.addEvent('userJoin', this.roomJoin);
		this.onRaw('gjoin', function(raw)	{
			var roomname = raw.data.user.properties.roomname;
			var username = raw.data.user.properties.name;
			if (!that.globalRooms[roomname]) {
				that.globalRooms[roomname] = {'ops':[], 'owners':[], "properties": {"name":roomname, "nusers":0, "users":{}}};
			}
			var room = that.globalRooms[roomname];
			room.properties.users[username] = {"casttype":"uni", "pubid":raw.data.user.pubid, "properties":{"name":username, "status":raw.data.user.properties.status,"hex":raw.data.user.properties.hex}};

			if(raw.data.user.properties.access) {
				room.properties.users[username].properties.access = raw.data.user.properties.access;
				if(raw.data.user.properties.access == "1")
					room.owners.push(username);
				else if(raw.data.user.properties.access == "2")
					room.ops.push(username)
			}
			
			var user = room.properties.users[username];
			
			that.userLocation[username] = roomname;
			this.globalJoin(user, room);
		});
		this.onRaw('gleft', function(raw)	{
			var roomname = raw.data.user.properties.roomname;
			var username = raw.data.user.properties.name;
			
			var room = that.globalRooms[roomname];
			var user = room.properties.users[username];
			
			this.globalLeave(user, room);
			
			that.userLocation[username] = null;
		});
		this.onRaw('userlist', function(raw)	{
			$.each(raw.data.users, function() {
				var roomname = this.properties.roomname;
				var username = this.properties.name;
				if (!that.globalRooms[roomname]) {
			 		that.globalRooms[roomname] = {'ops':[], 'owners':[], "properties": {"name":roomname, "nusers":0, "users":{}}};
				}
				var room = that.globalRooms[roomname];
				room.properties.users[username] = {"casttype":"uni", "pubid":this.pubid, "properties":{"name":username, "status":this.properties.status, "hex":this.properties.hex}};
					
				if(this.properties.access) {
					room.properties.users[username].properties.access = this.properties.access;
					if(this.properties.access == "1")
						room.owners.push(username);
					else if(this.properties.access == "2")
						room.ops.push(username);
				}
				
				var user = room.properties.users[username];
				
				that.userLocation[username] = roomname;
				that.globalJoin(user, room);
		    });
		});
		this.onRaw('onlinebuddies', function(raw)	{
			$.each(raw.data.buddies, function() {
				var raw = {"data":{"casttype":"uni", "pubid":this.pubid, "name":this.name, "status":"none", "hex":"000000"}};
				that.setOnline(raw);
		    });
		});
		this.onRaw('kicked', function(raw, pipe){ that.kickMsg(raw.data, raw.data.from, pipe); } );
		this.onRaw('banned', function(raw, pipe){ that.banMsg(raw.data, raw.data.from, pipe); } );
		this.onRaw('updateaccess', this.updateAccess);
		this.onRaw('newstatus', this.updateStatus);
		this.onRaw('newcolor', this.updateColor);
		this.onRaw('signout', this.setOffline);
		this.onRaw('signin', this.setOnline);
		this.onRaw('typingstart', this.msg.typing.start);
		this.onRaw('typingstop', this.msg.typing.stop);
		this.onRaw('addrequest', this.buttons.buddyList.receive_add_request);
		this.onRaw('addaccept', this.buttons.buddyList.add_accepted);
		this.onRaw('adddeny', this.buttons.buddyList.add_denied);
		this.onRaw('addrequesterror', this.buttons.buddyList.errors);
		this.onRaw('sharerequest', this.imageshare.receive_request);
		this.onRaw('sharestart', this.imageshare.start);
		this.onRaw('sharedeny', this.imageshare.denied);
		this.onRaw('sharecurview', this.imageshare.others_current_img);
		this.onRaw('shareaddimg', this.imageshare.receive_img);
		this.onRaw('shareremoveimg', this.imageshare.receive_delete);
		this.onRaw('sharestop', this.imageshare.receive_end);
		this.onRaw('massmessage', this.massMessage);
		this.onRaw('idlestart', this.msg.idle.start);
		this.onRaw('idleend', this.msg.idle.stop);
		this.onRaw('idletime', this.msg.idle.time);
		this.addEvent('userLeft', this.roomLeave);
		this.addEvent('restoreEnd',this.restoreEnd);
		this.onCmd('send', this.msg.cmdSend);
		this.onRaw('data', this.msg.rawData);
		this.onRaw('clist', this.channels.addChannels);
		this.onRaw('banlist', this.populateBans);
		this.onRaw('err', this.errorHandler);
		this.onRaw('login', this.setup);
		this.onRaw('ident', function(raw){ that.selfPubid = raw.data.user.pubid});
		//this.addEvent('apeDisconnect', this.disconnected);
		
		/*if(!this.options.name && !this.core.options.restore){
			this.login.prompt();
		} else {
			this.core.start({'name':that.options.name});
			this.core.start(that.options.name);
		}*/
	},
	
	login: {
			prompt: function(error){
				$("#loginDialog").dialog({
					bgiframe: true, autoOpen: true, height: 280, modal: true,
					open: function(event, ui) {
						$("div#loginDialog .innerbg").css("height", $("div#loginDialog").height() - $("div#loginDialog .ui-dialog-buttonpane").height() - 14);
					},
					resize: function(event, ui) {
						$("div#loginDialog .innerbg").css("height", $("div#loginDialog").height() - $("div#loginDialog .ui-dialog-buttonpane").height() - 14);
					},
					buttons: {
						'Login': function(ev) {
							$(this).find('button').attr('disabled', true);
							$("#loginDialog form").submit();
						},
						'Register': function(ev) {
							ev.preventDefault();
							window.open('http://www.rphaven.com/register.php');
						}
					}
				});
				$("#loginDialog form").submit(function(ev){
					if( $(this).hasClass('disabled') )
						return false;
					ev.preventDefault();
					that.login.postAjax($(this));
				});

			},
			
			postAjax: function($this){
				$this.addClass('disabled');
				$.ajax({
					type: "POST", url: 'ajax_chat.php?login', dataType: 'json', 
					data: "username=" + $("#username").val() + "&password=" + hex_md5($("#password").val()),
					success : function (json) {
						if (json.error == 'true') {
							$this.removeClass('disabled');
							$("#loginDialog div.ui-state-highlight").removeClass("ui-state-highlight").addClass("ui-state-error");
					 		$("#loginDialog").find("p").replaceWith('<p class="ui-state-error ui-corner-all" style="padding: 1em .7em;"><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span><strong>Error:</strong>' + json.msg + '</p>');
						} else {
							$("#loginDialog").find("p").replaceWith('<p style="padding: 1em 0.7em;" class="ui-state-highlight ui-corner-all"><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-info"></span> Logging in...</p>');
							that.options.name = encodeURIComponent(json.msg);
		 					that.options.access = json.access;
							that.options.userid = json.userid;
							that.options.accid = json.accid;
							that.options.color = '000000';
							that.cookie.get(that.options.name);
							that.buddiesArray = [];
							that.ignoresArray = [];
							
							if(json.access == '1'){
								that.make_admin_toolbar();
							}
							if(json.buddies)
								$.each(json.buddies, function() {
									var username = this;
									that.buddyList.offlines.properties.users[username] = {/*"casttype":"uni", "pubid":this.pubid, */"properties":{"name":username, "status":"none", "hex":"000000"}};
									var user = that.buddyList.offlines.properties.users[username];
									that.populateOfflines(user);
								});
							if(json.ignores)
								$.each(json.ignores, function() {
									var username = this;
									that.buddyList.ignores.properties.users[username] = {/*"casttype":"uni", "pubid":this.pubid, */"properties":{"name":username, "status":"none", "hex":"000000"}};
									var user = that.buddyList.ignores.properties.users[username];
									
									that.buttons.populateIgnores(user);
								});
							if(json.groups)
								$.each(json.groups, function() {
									var groupname = this.name;
									if (that.buddyList[groupname] == null) {
								 		that.buddyList[groupname] = {"properties": {"name":groupname, "nusers":0, "users":{}}};
									}
									var group = that.buddyList[groupname];
									$.each(this.users, function() {
										var username = this;
										group.properties.users[username] = {/*"casttype":"uni", "pubid":this.pubid, */"properties":{"name":username, "status":"none", "hex":"000000"}};
										var user = group.properties.users[username];
										
										that.populateGroups(user, group);
										//that.userLocation[username] = roomname;
									});
								});
							var sendLogin = function(){
								that.core.start({'name':json.msg,
											'password':hex_md5($("#password").val()),
											'version':111000,
											'color':that.options.color});
								$this.removeClass('disabled');
							};
							setTimeout(sendLogin,1500);
							that.buttons.colorPicker.hexToSliders(that.options.color);
							that.buttons.topBar.setName();
							that.buttons.topBar.setUserCount( parseInt(json.numusers) );
						}
					}
				});
			},
			
			nickUsed: function(){
				$("#loginDialog").find("p").replaceWith('<p class="ui-state-error ui-corner-all" style="padding: 1em .7em;"><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span><strong>Error:</strong>Name is in use.  It\'s either still logged on, or hasn\'t been timed-out yet.  For the latter, wait 30 seconds and try again.</p>');
			}
	},
	
	setup: function(type, pipe, options){
		$("#loginDialog").dialog('close');
		$("textarea[name=chatInput]")
			.keydown(function(event){
				if (event.keyCode == 13)
					event.preventDefault();
				if (event.keyCode == 13 && event.ctrlKey == false && $(this).val() != '') {
					if(that.currentPipe != null) {
						var newMessage = $(this).val();
						var pipe = that.getCurrentPipe();
						pipe.send(newMessage);
						$(this).val('');
						that.msg.writeLog(pipe.properties.name, newMessage, 'multi');
					}
					else{
						$("#mainChat > dl").append('<p class="subAlert">You are not in a room, so you can\'t talk.></p>');
					}
				}
				else if (event.keyCode == 13 && event.ctrlKey == true && $(this).val() != '') {
					$(this).val( $(this).val() + '\n' );
				}
			});
			
		$('textarea.expand').TextAreaExpander({
			onResize: function(){
		  		resizeCHATtextdiv();
				that.scrollMsg($("#mainChat"), true);
			}
		});
		
		$.idleTimer(600000);
		
		$(document).bind("idle.idleTimer", function(){
			that.core.request.send('SENDIDLE', {"pubid":that.core.user.pubid});
		});
		$(document).bind("active.idleTimer", function(){
			that.core.request.send('SENDIDLEEND', {"pubid":that.core.user.pubid});
		});
		
		that.channels.init();
		that.channels.openRoomlist();
	},
	
/* Functions used by commands. */
	setPipeName: function(pipe, options){
		if(options.name){
			pipe.name = options.name;
			return;
		}
		if(options.from){
			pipe.name = options.from.properties.name;
		} else {
			pipe.name = options.pipe.properties.name;
		}
	},
	
	isSelf: function(pubid){
		if(pubid == that.selfPubid)
			return true;
		else
			return false;
	},
	
	getCurrentPipe: function(){
		return that.currentPipe;
	},
	
	getCurrentPMPipe: function(){
		return that.currentPMPipe;
	},
	
	notify: function(PM){
		PM.els.tab.addClass('newMessage')
			.animate({ opacity: 0.30 }, 350 ).animate({ opacity: 0.90 }, 350 ).animate({ opacity: 0.50 }, 350 ).animate({ opacity: 0.90 }, 350 ).animate({ opacity: 0.70 }, 350 ).animate({ opacity: 0.95 }, 350 ).animate({ opacity: 0.80 }, 425 ).animate({ opacity: 1.0 }, 500 );
	},
	
	scrollMsg: function(target, force){
		if(target.scrollTop() > target[0].scrollHeight - target.height() - 200) {
			var scrollSize = target[0].scrollHeight;
			target.scrollTop(scrollSize);
		}
		if(force)
		{
			var scrollSize = target[0].scrollHeight;
			target.scrollTop(scrollSize);
		}
	},
	
	setCurrentPipe: function(pubid, save){
		save = !save;
		if(that.currentChannel){
			if(that.currentChannel.els)
				$(that.currentChannel.els.userlist).hide();
		}
		that.currentPubid = pubid;
		that.currentPipe = that.core.getPipe(pubid);
		var roomname = that.currentPipe.properties.name;
		that.currentChannel = that.globalRooms[roomname];
		
		$(that.currentChannel.els.userlist).show();
		//if (save)
			//this.core.setSession({'currentPipe':this.currentPipe.getPubid()});
		return that.currentPipe;
	},
	
	setCurrentPMPipe: function(pubid, save){
		save = !save;
		if(that.currentPMPipe){
		 	$(that.currentPM.els.tab).removeClass('newMessage').removeClass('active').removeClass('ui-state-focus');
			$(that.currentPM.els.container).hide();
			$(that.currentPM.els.input).hide();
			$(that.currentPM.els.topButtons).hide();
		}

		that.currentPMPubid = pubid;
		that.currentPMPipe = that.core.getPipe(pubid);
		that.currentPM = that.PMs[pubid];
		
		$("#pmDialog").dialog('option', 'title', 'Conversing with ' + $(that.currentPM.els.tab).find('a').html());
		$(that.currentPM.els.tab).addClass('active').addClass('ui-state-focus');
		$(that.currentPM.els.container).show();
		$(that.currentPM.els.input).show();
		$(that.currentPM.els.topButtons).show();
		that.scrollMsg(that.currentPM.els.container.parent(), true);
		resizePMtextdiv();
		//if(save) that.core.setSession('currentPipe',that.currentPipe.getPubid());
		return that.currentPMPipe;
	},
	
	createPM: function(pipe, options){
		that.setPipeName(pipe, options);
		var pubid = pipe.pipe.pubid;
		var user = that.core.users.get(pubid);
		
		that.core.request.send('SUBSCRIBE', {"pubid":pubid});
		
		that.PMs[pubid] = {"properties": {"name":pipe.properties.name,"pubid":pubid}};
		that.PMs[pubid].active = true;
		that.PMs[pubid].els = {};
		that.PMs[pubid].els.container = $('<div />').html('<p>&nbsp;</p>').hide().appendTo('#pmChat');
		that.PMs[pubid].els.tab = $('<div class="pmTab ui-corner-all" />').appendTo('#pmTabs');
		var buttonsHTML = "";
		buttonsHTML += "<li class='add-usr'>Add</li>";
		buttonsHTML += "<li class='view-prof'>Profile</li>";
		buttonsHTML += "<li class='imgshare'>Image-Share</li>";
		buttonsHTML += "<li class='closepm IconBtn ui-corner-all ui-icon ui-icon-closethick' title='Close PM' style='float: right;'>close</li>";
		buttonsHTML += "<li class='block-usr' title='Block User' style='float: right;'>B</li>";
		that.PMs[pubid].els.topButtons = $(buttonsHTML).hide()
			.appendTo("#pmHeader");
		var buttonList = that.PMs[pubid].els.topButtons;
		buttonList.filter(".add-usr")
				.bind("click", function(){ that.buttons.buddyList.request_add(pubid); });
		buttonList.filter(".view-prof")
			.bind("click", function(){ window.open("http://www.rphaven.com/profile.php?user="+ pipe.name); });
		buttonList.filter(".imgshare")
			.bind("click", function(){
				that.imageshare.request_share(pubid);
			});
		buttonList.filter(".closepm")
			.bind("click", function(){ that.closePM(pipe, pubid); });
		buttonList.filter(".block-usr")
			.bind("click", function(){ that.dropdown.action(user, "Block"); });
			
		$('<a href="#" />')
			.text(decodeURIComponent(pipe.name))
			.click(function(event){
				event.preventDefault();
				that.setCurrentPMPipe(pipe.getPubid());
			}).rightClick( function(e) {
				alert(decodeURIComponent(pipe.name));
			})
			.appendTo(that.PMs[pubid].els.tab);
		
		that.PMs[pubid].els.input = $('<textarea name="pmInput" />').hide()
			.css("color", "#"+that.options.color)
			.keydown(function(event){
				//submit on enter, unless pressing Ctrl
				if (event.keyCode == 13)
					event.preventDefault();
				if (event.keyCode == 13 && event.ctrlKey == false && $(this).val() != '') {
					if(that.PMs[pubid].active === true){
						if($(this).val().length <= 800){
							var newMessage = $(this).val();
							var pipe = that.getCurrentPMPipe();
							pipe.send(newMessage);
							$(this).val('');
							that.msg.writeLog(pipe.properties.name, newMessage, 'uni');
						}
						else {
							$(that.PMs[pubid].els.container).append("<p class='sys em bold'>Message too long.</p>");
						that.scrollMsg(that.PMs[pubid].els.container.parent());
						}
					}
					else{
						$(that.PMs[pubid].els.container).append("<p class='sys em bold'>" + decodeURIComponent(pipe.properties.name) + " is not online.  Your message has not been sent.  I'll add some leaving offline messages later, probably.</p>");
						that.scrollMsg(that.PMs[pubid].els.container.parent());
					}
				}
				else if (event.keyCode == 13 && event.ctrlKey == true) {
					$(this).val( $(this).val() + '\n' );
		   		}
			})
			.insertAfter('#notPMChat > ul');
			
		that.PMs[pubid].els.input.typeWatch({
			start: function startTyping(){
				if (that.PMs[pubid].active === true) {
					that.core.request.send('SENDTYPINGSTART', {"pubid":pubid});
				}
			},
			callback: function finishedTyping() {
				if (that.PMs[pubid].active === true){
					that.core.request.send('SENDTYPINGSTOP', {"pubid":pubid});
				}
			}
		});
	
		that.PMs[pubid].els.input.TextAreaExpander({
			onResize : function() {
  				resizePMtextdiv();
				that.scrollMsg(that.PMs[pubid].els.container.parent(), true);
			}
		});
		
		/*
		 * $('textarea.limited').maxlength({
            'feedback' : '.charsLeft' // note: looks within the current form
        });
		 * 
		 * <h1>maxlength</h1>
    <h2>By characters</h2>
    <form action="">
        <p>Characters left: <span class="charsLeft">10</span></p>

        <textarea maxlength="10" class="limited"></textarea>
    </form>
		 */
			
		if (!$("#pmDialog").dialog('isOpen')) {
			$("#pmDialog").dialog('open');
			that.setCurrentPMPipe(pipe.pipe.pubid);
			resizePMtextdiv();
		}
	},
	
	closePM: function(pipe, pubid){
		var pubid = pipe.pipe.pubid;
		
		if ( that.PMs[pubid].active = true )
			that.core.request.send('UNSUBSCRIBE', {"pubid":pubid});
		
		that.PMs[pubid].els.input.typeWatch({
			start: function startTyping(){},
			callback: function finishedTyping() {}
		});
		$.each(that.PMs[pubid].els, function(){
			$(this).remove();
		});
		delete that.PMs[pubid];
		
		//select the first PM to make active.
		for (var firstPM in that.PMs) {
			break;
		}
		if(firstPM == undefined){
			$("#pmDialog").dialog('close');
		}
		else {
			that.setCurrentPMPipe(firstPM);
		}
		
		that.core.delPipe(pubid);
	},
	
	msg: {
			writeLog: function(to, msg, type){
				if( type == 'uni' )
					var logType = 'histpm';
				else
					var logType = 'histc';
				
				$.ajax({
					type: "POST", url: 'ajax_chat.php?' + logType,
					data: "from=" + that.options.userid + "&to=" + to + "&msg=" + msg
				});
			},
			
			cmdSend: function(data, pipe){
				that.core.getPipe(pipe);
					that.msg.writeMessage(pipe, data.msg, that.core.user, pipe.type, 'self');
			},
			
			rawData: function(raw, pipe){
				//Is name not in ignores?
				if ($.inArray(decodeURIComponent(raw.data.from.properties.name), that.ignoresArray) == -1)
			  		that.msg.writeMessage(pipe, decodeURIComponent(raw.data.msg), raw.data.from, raw.data.pipe.casttype, 'other');
			},
			
			parseMessage: function(message, type){
				message = message.replace(/</g, '&lt;');
				message = message.replace(/>/g, '&gt;');
				message = message.replace(/\n/g, convertNL("<br />"));
				message = message.replace(/jesselicious/g, convertNL("banme"));
				message = message.replace(/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9\%])|www\d{0,3}[.]|(?:[a-z0-9\-_]+[.])+[a-z0[a-z]{2,4}\/?)(?:[^\s\(\)<>]+|\(([^\s\(\)<>]+|(\([^\s\(\)<>]+\)))*\))+(?:\(([^\s\(\)<>]+|(\([^\s\(\)<>]+\)))*\)|[^\s`\!\(\)\[\]\{\};:'"\.,<>\?«»“”‘’])?)/gi,function(url){
					var full_url = url;
					var extra = '';
					if( !full_url.match('^https?:\/\/') ) {
						full_url = 'http://' + full_url;
					}
					if( url.match(/\.(jpg|jpeg|png|gif)/i) ){
						extra = 'class="img-wrapper"';
					}
					else if( url.match(/\S*youtube\.com\S*v=([\w-]+)/i) ){
						extra = 'class="vid-wrapper"';
					}
					return '<a href="' + full_url + '" target="_blank" '+extra+'>' + url + '</a>';
				});
				/*var message = message.replace(/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9\%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s\(\)<>]+|\(([^\s\(\)<>]+|(\([^\s\(\)<>]+\)))*\))+(?:\(([^\s\(\)<>]+|(\([^\s\(\)<>]+\)))*\)|[^\s`\!\(\)\[\]\{\};:'"\.,<>\?«»“”‘’]))/i, '<a href="$1" target="_blank">$1</a>');*/
				
				if( type == 'multi' ){
					var origMessage = message;
					var myrg = new RegExp('('+decodeURIComponent(that.options.name)+')', 'ig');
					message = message.replace(myrg, '<span class="highlight">$1</span>');
					
					if( origMessage != message )
						$("#jplayer_boop").jPlayer("play");
				}
				
				return message;
			},
			
			writeMessage: function(pipe, message, from, type, sender){
				var name = decodeURIComponent(from.properties.name);
				var msg = that.msg.parseMessage(message, type);
				if( sender == 'other' )
					var color = from.properties.hex;
				else
					var color = that.options.color;
				if(type == 'uni') {
					var pubid = pipe.pipe.pubid;
					
				   	var msgEl = $("<p style='color:#"+ color +"'><span class='dull'>" + makeTimestamp() + "</span><b>" + name + ":</b> " + msg + "</p>")
						.appendTo(that.PMs[pubid].els.container);
						
					msgEl.find('.vid-wrapper').before(
							$('<a href="#" />').text('Open in dialog box').bind('click', function(ev){
								ev.preventDefault();
								var matched = msg.match(/http:\/\/\S*?\.youtube\.com\/\S*v=([\w-]+)/i)[1];
								$('<div class="innerbg smallBorders" style="padding:0 2px;height: 100%"><object width="450" height="365"><param name="movie" value="http://www.youtube.com/v/$1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+matched+'" type="application/x-shockwave-flash" wmode="transparent" width="456" height="355"></embed></object></div>').dialog({
			  						bgiframe: true, width: 460, title: 'Youtube'
								})
							}).add(
								$('<span />').text(' - ')
							)
						);
					msgEl.find('.img-wrapper').before(
							$('<a href="#" />').text('Open in dialog box').bind('click', function(ev){
								ev.preventDefault();
								var matched = msg.match(/(http:\/\/\S*\.(jpg|jpeg|png|gif))/i)[0];
								$('<div class="innerbg smallBorders" style="padding:0 2px;height: 100%"><img src="'+matched+'" /></div>').dialog({
			  						bgiframe: true, title: 'Image'
								})
							}).add(
								$('<span />').text(' - ')
							)
						);
							
					that.scrollMsg(that.PMs[pubid].els.container.parent());
					
					if( sender == 'other' ) {
						$("#jquery_jplayer").jPlayer("play");
						
						if ( !$("#pmDialog").dialog('isOpen') )
						$("#pmDialog").dialog('open');
						
						if( that.PMs[pubid].els.typing )
							that.PMs[pubid].els.typing.remove();
						
						if (that.getCurrentPMPipe().getPubid() != pipe.getPubid())
				   			that.notify(that.PMs[pubid]);
							
						if($.data(document,'idleTimer') == 'idle'){
							var idleMS = $.idleTimer('getElapsedTime');
							that.core.request.send('IDLERESPONSE', {"pubid":pubid,"time":idleMS});
						}
					}
					
			   	}
				else if(type == 'multi') {
					var msgEl = $("<dt>[" + makeTimestamp() + "]<span style='color: #" + color + ";' title='" + makeTimestamp() + '-'+ name +"'>" + name + "</span></dt><dd style='color: #" + color + ";'>" + msg + "&nbsp;</dd>")
						.appendTo(pipe.chatels.msgs);
						
					msgEl.find('.vid-wrapper').before(
							$('<a href="#" />').text('Open in dialog box').bind('click', function(ev){
								ev.preventDefault();
								var matched = msg.match(/http:\/\/\S*?\.youtube\.com\/\S*v=([\w-]+)/i)[1];
								$('<div class="innerbg smallBorders" style="padding:0 2px;height: 100%"><object width="450" height="365"><param name="movie" value="http://www.youtube.com/v/$1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+matched+'" type="application/x-shockwave-flash" wmode="transparent" width="456" height="355"></embed></object></div>').dialog({
			  						bgiframe: true, width: 460, title: 'Youtube'
								})
							}).add(
								$('<span />').text(' - ')
							)
						);
					msgEl.find('.img-wrapper').before(
							$('<a href="#" />').text('Open in dialog box').bind('click', function(ev){
								ev.preventDefault();
								var matched = msg.match(/(http:\/\/\S*\.(jpg|jpeg|png|gif))/i)[0];
								$('<div class="innerbg smallBorders" style="padding:0 2px;height: 100%"><img src="'+matched+'" /></div>').dialog({
			  						bgiframe: true, title: 'Image'
								})
							}).add(
								$('<span />').text(' - ')
							)
						);
					msgEl.find("span").rightClick( function(e) {
							that.dropdown.createDropdown(e, from, ["View Profile", "Open PM", "Block"]);
						}).bind("click", function(e){
							if( e.target == this )
								that.dropdown.action(from, "Open PM");
						});
					
					that.scrollMsg(pipe.chatels.container);
				}
			},
			
			typing: {
		 		start: function(raw){
					var pubid = raw.data.pubid;
					if( that.PMs[pubid].active = true ){
						$(that.PMs[pubid].els.container).append(
							that.PMs[pubid].els.typing = $("<p class='dull em'>" + decodeURIComponent(raw.data.name) + " is typing.</p>")
						);
				  		that.scrollMsg(that.PMs[pubid].els.container.parent());		
					}				
				},
				
				stop: function(raw){
					var pubid = raw.data.pubid;
					if ( that.PMs[pubid].active = true ) {
						if (that.PMs[pubid].els.typing) 
							that.PMs[pubid].els.typing.remove();
					}
				}
			},
			
			idle: {
		 		start: function(raw,pipe){
					var pubid = pipe.pipe.pubid;
					var name = decodeURIComponent(pipe.properties.name);
					$(that.PMs[pubid].els.container).append("<p class='sys em bold'>" + name + " has gone idle at " + makeTimestamp() + "</p>");
						that.scrollMsg(that.PMs[pubid].els.container.parent());
				},
				
				stop: function(raw,pipe){
					var pubid = pipe.pipe.pubid;
					var name = decodeURIComponent(pipe.properties.name);
					$(that.PMs[pubid].els.container).append("<p class='sys em bold'>" + name + " has returned from being idle at " + makeTimestamp() + "</p>");
						that.scrollMsg(that.PMs[pubid].els.container.parent());
				},
				
				time: function(raw,pipe){
					var pubid = pipe.pipe.pubid;
					var name = decodeURIComponent(pipe.properties.name);
					var addTenMins = raw.data.time + 600000;
					$(that.PMs[pubid].els.container).append("<p class='sys em bold'>" + name + " has been idle for " + msToReadable(addTenMins) + "</p>");
						that.scrollMsg(that.PMs[pubid].els.container.parent());
				}
			}
	},
	
	getRoomByName: function(name){
		var room = that.globalRooms[name];
		
		return room;
	},
	
	createChannel: function(pipe, options){
  		pipe.chatels = {};
		pipe.chatels.container = $("#mainChat");
		pipe.chatels.msgs = $("#mainChat > dl");
		
  		$('<dt>[' + makeTimestamp() + ']<span>*</span></dt><dd title="' + decodeURIComponent(pipe.properties.topic) + '">Topic for ' + decodeURIComponent(pipe.name) + ': ' + decodeURIComponent(pipe.properties.topic) + '</dd>')
			.appendTo(pipe.chatels.msgs);
		
		that.channels.closeRoomlist();
		
		var roomname = pipe.name;
		if (that.globalRooms[roomname] == null) {
	 		that.globalRooms[roomname] = {"owners":[],"ops":[],"properties": {"name":roomname, "nusers":0, "users":{}}};
			var room = that.getRoomByName(roomname);
		
			that.createListHeader(room, "room");
		}
		that.setCurrentPipe(pipe.getPubid());
	},
	
	leaveChannel: function(pipe){
		$("<dt>[" + makeTimestamp() + "]<span>*</span></dt><dd>You have left " + decodeURIComponent(pipe.name) + "</dd>")
			.appendTo(pipe.chatels.msgs);
			
		that.currentPubid = null;
		that.currentChannel = null;
	},
	
	roomJoin: function(user, pipe){
		//that.core.getPipe(pipe);
		var $html = $("<dt>[" + makeTimestamp() + "]<img src='bullet_green.png' /></dt><dd><span class='clickable'>" + decodeURIComponent(user.properties.name) + "</span> has joined " + decodeURIComponent(pipe.name) +"</dd>")
			.appendTo(pipe.chatels.msgs);
		$html.find('.clickable').rightClick(function(ev) {
			that.dropdown.createDropdown(ev, user, ["View Profile", "Open PM", "Block"]);
		});
			
		that.scrollMsg(pipe.chatels.container);
	},
	
	roomLeave: function(user, pipe){
		var $html = $("<dt>[" + makeTimestamp() + "]<img src='bullet_red.png' /></dt><dd><span class='clickable'>" + decodeURIComponent(user.properties.name) + "</span> has left</dd>")
			.appendTo(pipe.chatels.msgs);
		$html.find('.clickable').rightClick(function(ev) {
			that.dropdown.createDropdown(ev, user, ["View Profile"]);
		});
		
		that.scrollMsg(pipe.chatels.container);
	},
	
	createListHeader: function(room, type){
		if( type == "room" )
			var appendee = "#userlist > ul";
		else
			var appendee = "#buddylist > ul";
		room.els = {};
		room.els.room = $('<li class="headItem" />')
			.html(
				$('<span class="headText emboss-lgrey"><a>' + decodeURIComponent(room.properties.name) + '</a></span>')
				.find("a").prepend(
					room.els.usercount = $('<span />')
				).end()
				.add(
					room.els.userlist = $('<ul class="userListContainer" />').hide()
				)
			).appendTo(appendee);
			
		$(room.els.room)
			.toggle(function(event){
				if( !$(event.target).closest('ul').hasClass('userListContainer') ) {
					room.els.userlist.show();
				}
			}, function (event) {
	      		if( !$(event.target).closest('ul').hasClass('userListContainer') ){
					room.els.userlist.hide();
			}
	      }
		);
	},
	
	getBuddyUser: function(username){
		var user = that.buddyList.offlines.properties.users[username];
		
		return user;
	},
	
	setOnline: function(raw){
		var username = decodeURIComponent(raw.data.name);
		if ($.inArray(decodeURIComponent(username), that.buddiesArray) != -1){
			var user = that.getBuddyUser(username);
			that.buddyList.onlines.properties.nusers+=1;
			that.buddyList.offlines.properties.nusers-=1;
			$("#listOnlines > .headText > span").text(that.buddyList.onlines.properties.nusers + '-');
			$("#listOfflines > .headText > span").text(that.buddyList.offlines.properties.nusers + '-');
			user.pubid = raw.data.pubid;
			user.casttype = "uni";
			user.els.name.appendTo("#listOnlines > ul");
			$("#listOnlines > ul").children('li').each(function(){
				if($(this).text() > decodeURIComponent(user.properties.name)){
					return !user.els.name.insertBefore(this);
				}
			});
			user.els.name.bind("click", function(e){
			  		if (e.target == this)
			  			that.dropdown.action(user, "Open PM");
			  	}).rightClick(function(e){
					that.dropdown.createDropdown(e, user, ["View Profile", "Open PM", "Block"]);
			 	})
					.append(
							user.els.status = $('<span class="user-status" />').html('&nbsp')
						);
			if(user.properties.status != 'none') {
				user.els.status.text('(' + decodeURIComponent(user.properties.status) + ')');
				user.els.status.attr('title', decodeURIComponent(user.properties.status));
			}
		}
		that.buttons.topBar.updateUserCount('up');
	},
	
	setOffline: function(raw){
		var username = decodeURIComponent(raw.data.name);
		if(that.core.pipes.has(raw.data.pubid)){
			var pubid = raw.data.pubid;

			that.PMs[pubid].els.tab.addClass('offline');
			
			$(that.PMs[pubid].els.container).append("<p class='sys em bold'>" + decodeURIComponent(raw.data.name) + " has logged off at "+makeTimestamp()+".</p>");			
			that.scrollMsg(that.PMs[pubid].els.container.parent());
			
			that.PMs[pubid].active = false;
		}
		if ($.inArray(decodeURIComponent(username), that.buddiesArray) != -1){
			var user = that.getBuddyUser(username);
			that.buddyList.onlines.properties.nusers-=1;
			that.buddyList.offlines.properties.nusers+=1;
			$("#listOnlines > .headText > span").text(that.buddyList.onlines.properties.nusers + '-');
			$("#listOfflines > .headText > span").text(that.buddyList.offlines.properties.nusers + '-');
			user.els.name.appendTo("#listOfflines > ul");
			$("#listOfflines > ul").children('li').each(function(){
				if($(this).text() >= decodeURIComponent(user.properties.name)){
					user.els.name.insertBefore($(this));
					return false;
				}
			});
			//$("#listOfflines > ul").alphabeticalList().alphabeticalList("add",user.els.name)
			/*$("#listOfflines > ul").children('li').each(function(){
				if(window.console) console.log($(this).text() + ' compare to ' + user.properties.name);
				if($(this).text() > decodeURIComponent(user.properties.name)){
					user.els.name.insertBefore(this);
					return false
				}
			});
			if(!user.els.name)
				user.els.name.appendTo("#listOfflines > ul");*/
			
			user.els.name.unbind();
		}
		that.buttons.topBar.updateUserCount('down');
	},
	
	populateOfflines: function(user, type){
		that.buddiesArray.push(decodeURIComponent(user.properties.name));
		that.buddyList.offlines.properties.nusers+=1;
		$("#listOfflines > .headText > span").text(that.buddyList.offlines.properties.nusers + '-');
		user.els = {};		
		user.els.name = $('<li style="color:#' + user.properties.hex + ';" />').text(decodeURIComponent(user.properties.name));		
		user.els.name.appendTo("#listOfflines > ul");
		/*group.els.userlist.children('li').each(function(){
			if($(this).text() > decodeURIComponent(user.properties.name)){
				return !user.els.name.insertBefore(this);
			}
		});*/

		user.els.name.rightClick(function(e){
		  		that.dropdown.createDropdown(e, user, ["View Profile", "Block"]);
				e.stopPropagation();
		 	});
	},
	
	populateGroups: function(user, group){
		if (group.els == null)
			this.createListHeader(group, "group");
		
		group.properties.nusers+=1;
		$(group.els.usercount).text(group.properties.nusers + '-');
		
		user.els = {};		
		user.els.name = $('<li style="color:#' + user.properties.hex + ';" />').text(decodeURIComponent(user.properties.name));		
		user.els.name.appendTo( group.els.userlist );
		/*group.els.userlist.children('li').each(function(){
			if($(this).text() > decodeURIComponent(user.properties.name)){
				return !user.els.name.insertBefore(this);
			}
		});*/

		user.els.name.bind("click", function(e){
		  		if (e.target == this)
		  			that.dropdown.action(user, "Open PM");
		  	}).rightClick(function(e){
				that.dropdown.createDropdown(e, user, ["View Profile", "Block"]);
		 	})
				.append(
						user.els.status = $('<span class="user-status" />').html('&nbsp')
					);
					
		if(user.properties.status != 'none') {
			user.els.status.text('(' + decodeURIComponent(user.properties.status) + ')');
			user.els.status.attr('title', decodeURIComponent(user.properties.status));
		}
	},
	
	globalJoin: function(user, room){
		if (room.els == null)
			this.createListHeader(room, "room");
		
		room.properties.nusers+=1;
		$(room.els.usercount).text(room.properties.nusers + '-');
		
		user.els = {};		
		user.els.name = $('<li style="color:#' + user.properties.hex + ';" />').text(decodeURIComponent(user.properties.name));		
		user.els.name.appendTo( room.els.userlist );
		room.els.userlist.children('li').each(function(){
			if($(this).text() > decodeURIComponent(user.properties.name)){
				return !user.els.name.insertBefore(this);
			}
		});

		user.els.name.bind("dblclick", function(e){
		  		if ( e.target == this )
		  			that.dropdown.action(user, "Open PM");
		  	}).rightClick(function(e){
				var stopper = false;
				if( that.isRoomOwner(room) ) {
					stopper = true;
					//make sure you aren't clicking yourself if an op or owner, just return normal menu for that
					if(!user.properties.access)
						that.dropdown.createDropdown(e, user, ["View Profile", "Open PM", "Block", "HR", "Make Operator", "HR", "Kick", "Ban"]);
					else if(user.properties.access == "2")
						that.dropdown.createDropdown(e, user, ["View Profile", "Open PM", "Block", "HR", "Remove Ops", "HR", "Kick", "Ban"]);
					else
						stopper = false;
				}
				else if( that.isRoomOp(room) ) {
					stopper = true;
					if(!user.properties.access)
						that.dropdown.createDropdown(e, user, ["View Profile", "Open PM", "Block", "HR", "Kick", "Ban"]);
					else
						stopper = false;
				}
				if (stopper == false)
					that.dropdown.createDropdown(e, user, ["View Profile", "Open PM", "Block"]);
		 	});

		that.setUserStatus(user);
		that.setRoomAccess(user);
		that.setRoomOptions(user);
	},
	
	setUserStatus: function(user){
		if( !user.els.status )
			user.els.name.append(
					user.els.status = $('<span class="user-status" />').html('&nbsp')
				);
		if( user.properties.status != 'none' ) {
			user.els.status.text('(' + decodeURIComponent(user.properties.status) + ')');
			user.els.name.attr('title', decodeURIComponent(user.properties.status));
		}
		else {
			user.els.status.html('&nbsp');
		}
	},
	
	isRoomOwner: function(room){
		if( $.inArray(that.options.name, room.owners) >= 0  )
			return true;
		else
			return false;
	},
	
	isRoomOp: function(room){
		if( $.inArray(that.options.name, room.ops) >= 0 )
			return true;
		else
			return false;
	},
	
	setRoomAccess: function(userDOM){
		userDOM.els.name.removeClass('owner op');
		userDOM.els.name.find('.owner, .op').remove();
		if(userDOM.properties.access){
			if(userDOM.properties.access == '1'){
				$('<span class="owner" title="Room creator/owner">').prependTo(userDOM.els.name);
				userDOM.els.name.addClass('owner');
			}
			if(userDOM.properties.access == '2'){
				$('<span class="op" title="Room Operator">').prependTo(userDOM.els.name);
				userDOM.els.name.addClass('op');
			}
		}
	},
	
	setRoomOptions: function(userDOM){
		var loc = that.userLocation[userDOM.properties.name];
		var room = that.getRoomByName(loc);
		if( that.isRoomOp(room) || that.isRoomOwner(room) & !room.els.opsButton ){
			$target = room.els.room.find('.headText');
			if( !room.els.opsButton ) {
				room.els.opsButton = $('<button style="float:right;">Manage</button>').button().prependTo($target);
				room.els.opsButton.click(function(ev){
					that.openRoomOptions();
					ev.stopPropagation();
				});
			}
		}
	},
	
	kickMsg: function(data, user, pipe){		
		$("<dt>[" + makeTimestamp() + "]<img src='bullet_red.png' /></dt><dd><span class='bold'>" + decodeURIComponent(user.properties.name) + "</span> kicked <span class='highlight'>" + decodeURIComponent(data.victim) + "</span> from " + decodeURIComponent(pipe.properties.name) + " ( Reason: " + decodeURIComponent(data.msg) + " )</dd>")
			.appendTo(pipe.chatels.msgs);
		
		that.scrollMsg(pipe.chatels.container);
	},
	
	banMsg: function(data, user, pipe){
		$("<dt>[" + makeTimestamp() + "]<img src='bullet_red.png' /></dt><dd><span class='bold'>" + decodeURIComponent(user.properties.name) + "</span> banned <span class='highlight'>" + decodeURIComponent(data.victim) + "</span> from " + decodeURIComponent(pipe.properties.name) + " ( Reason: " + decodeURIComponent(data.msg) + " )</dd>")
			.appendTo(pipe.chatels.msgs);
		
		that.scrollMsg(pipe.chatels.container);
	},
	
	updateAccess: function(raw){
		var user = that.core.users.get(raw.data.pubid);
		var username = user.properties.name;
		var loc = that.userLocation[username];
		var room = that.getRoomByName(loc);
		if( room != undefined ) {
			var user = room.properties.users[username];
			if( raw.data.access ) {
				user.properties.access = raw.data.access;
				
				if( raw.data.access = 2 )
					room.ops.push(username);
			}
			else {
				user.properties.access = null;
				var arrPos = $.inArray(username, room.ops);
				if( arrPos > 0 )
					delete room.ops[arrPos];
			}
			
			that.setRoomAccess(user);
			that.setRoomOptions(user);
			
		}
	},
	
	updateStatus: function(raw){
		var location = that.userLocation[raw.data.name];
		var room = that.globalRooms[location];
		if( room != undefined) {
			var user = room.properties.users[raw.data.name];
			user.properties.status = raw.data.status;
			that.setUserStatus(user);
		}
	},
	
	updateColor: function(raw){
		var room = that.globalRooms[that.userLocation[raw.data.name]];
		if( room ) {
			var user = room.properties.users[raw.data.name];
		
			user.els.name.css('color', '#'+raw.data.hex);
		}
	},
	
	globalLeave: function(user, room){
		room.properties.nusers-=1;
		
		if( user != undefined )
			user.els.name.remove();
		delete user.els;
		delete room.properties.users[user.properties.name];
		if(room.properties.nusers <= 0)	{
			room.els.room.remove();
			delete room.els;
			delete that.globalRooms[room.properties.name];
		}
		else
			$(room.els.usercount).text(room.properties.nusers + '-');
	},
	
	massMessage: function(raw){
		if(raw.data.type == '1' || raw.data.type == '2')
			var modalVar = false;
		if(raw.data.type == '3' || raw.data.type == '4')
			var modalVar = true;
		if(raw.data.type == '1' || raw.data.type == '3')
			var titleVar = 'Admin Alert from ' + raw.data.name;
		if(raw.data.type == '2' || raw.data.type == '4')
			var titleVar = 'Admin Alert';
		$('<div />').append('<div class="innerbg smallBorders" style="height:100%"><div class="ui-state-highlight ui-corner-all" style="padding: 1em .7em;"><p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>'+decodeURIComponent(raw.data.msg)+'</p></div>').dialog({
			bgiframe: true,
			title: titleVar,
			autoOpen: true,
			modal: modalVar,
			height: 300,
			width: 350
		});
	},
	
	openRoomOptions: function(raw){
		$("#manage-room").dialog('open');
		that.core.request.send('GETBANS', {'room':that.currentRoom});
		
		$('#change-topic').submit(function(ev){
			ev.preventDefault();
			var topic = $("#changetopic").val();
			that.core.request.send('SETTOPIC',{"name":that.currentRoom,"topic":topic});
		});
	},
	
	populateBans: function(raw){
		var $bantable = $('#banslist');
		$bantable.find('tr:gt(0)').remove();
		if( raw.data.length == 0 ){
			$('<tr><td colspan="3">No one has been banned.  Maybe you should ban people. :3</td></tr>')
				.appendTo($bantable);
		}	else	{
			raw.data.each(function(i){				
				var html = '<tr>' +
							'<td class="clickable">'+ decodeURIComponent(i.name) +'</td>' +
							'<td>To be implemented</td>' +
							'<td>To be implemented</td>' +
							'</tr>';
				var $line = $(html).appendTo($bantable);
				
				$line.rightClick(function(ev){
					that.dropdown.createDropdown(ev, {'properties':{'name':i.name}}, ["View Profile", "Unban"]);
				});
			});
		}
	},
	
	imageshare: {
			request_share: function(pubid) {
				that.core.request.send('REQUESTSHARE',{'pubid':pubid});
				that.PMs[pubid].els.addRequest = $("<p class='sys em bold'>You have sent an image-share request.</p>")
					.appendTo(that.PMs[pubid].els.container);
			},
			accept: function(pubid) {
				that.core.request.send('ACCEPTSHARE',{'pubid':pubid});
			},
			deny: function(pubid) {
				that.core.request.send('DENYSHARE',{'pubid':pubid});
			},
			denied: function(raw,pipe) {
				var pubid = pipe.pipe.pubid;
				if(raw.data.name != undefined)
					that.PMs[pubid].els.addRequest.text("The image-share request has been denied.");
			},
			receive_request: function(raw, pipe) {
				var pubid = pipe.pipe.pubid;
				that.PMs[pubid].els.addRequest = $("<p class='sys em bold'><b style='"+pipe.properties.hex+"'>" + pipe.properties.name + ":</b> has sent you an image-share request.  You may </p>")
					.append(
						$('<a href="#" />').text('Accept').click(function(ev){
							ev.preventDefault();
							that.imageshare.accept(pubid);
						})
						.add('<span> or </span>')
						.add(
							$('<a href="#" />').text('Deny').click(function(ev){
								ev.preventDefault();
								that.imageshare.deny(pubid);
							})
						)
					)
						.appendTo(that.PMs[pubid].els.container);
			},
			upload_response: function(json) {
				var pubid = json.pubid;
				var img = json.image;
				var type = 'upload';
				that.core.request.send('SHAREADDIMG',{'type':type,'url':json.image,'pubid':pubid});
				that.imageshare.add_img(pubid, img, type);
			},
			receive_img: function(raw, pipe) {
				var pubid = pipe.pipe.pubid;
				var img = raw.data.url;
				var type = raw.data.type;
				
				that.imageshare.add_img(pubid, img, type);
			},
			add_img: function(pubid, image, type) {
				var thumb = '';
				if( type = 'upload'){
					thumb = 'temp/th_'+image;
					image = 'temp/'+image;
				}
				else
					thumb = image;
				
				var $img = $('<img src="'+image+'" />')
					.appendTo(that.ISs[pubid].els.imgWindow);
				var $thumbContainer = $('<div />')
					.appendTo(that.ISs[pubid].els.thumbsScroller);
				var $thumb = $('<li class="ui-corner-all"><img src="'+thumb+'" /></li></li>')
					.appendTo($thumbContainer);
				$img.hide();
				var $deleteBtn = $('<button class="delete"><span class="ui-corner-all ui-icon ui-icon-closethick" title="Close PM">close</span></button>').button().appendTo($thumbContainer);
				$thumb.button();
				$thumbContainer.hover(function(ev){
						$deleteBtn.show();
					}, function(ev){
						$deleteBtn.hide();
					}
				);
				
				if( that.ISs[pubid].els.imgWindow.children().length <= 1 ){
					var pos = $thumbContainer.index();
					that.imageshare.set_current_img(pubid, pos);
				}
				if( that.isSelf(pubid) ){
					var pos = $thumbContainer.index();
					that.imageshare.set_current_img(pubid, pos);
				}				
				$thumb.click(function(ev){
					var pos = $thumbContainer.index();
					that.imageshare.set_current_img(pubid, pos);
				});
				$deleteBtn.click(function(ev){
					var pos = $(this).parent().index();
					that.core.request.send('SHAREREMOVEIMG',{'pubid':pubid,'position':pos});
					that.imageshare.delete_img(pubid, pos);
				});
			},
			set_current_img: function(pubid, pos){
				that.ISs[pubid].els.imgWindow.find('img').eq(pos).show();
				that.ISs[pubid].els.imgWindow.find('img').not(':eq('+pos+')').hide();
							
				that.core.request.send('SHARECURVIEW',{'pubid':pubid,'position':pos});
			},
			others_current_img: function(raw,pipe){
				var pos = raw.data.position;
				var pubid = pipe.pipe.pubid;
				var img = that.ISs[pubid].els.thumbsScroller.find('img').eq(pos).attr('src');
				
				that.ISs[pubid].els.curImg.find('img').attr('src', img);
				
				that.ISs[pubid].els.curImg.click(function(ev){
					that.imageshare.set_current_img(pubid, pos);
				});
			},
			receive_delete: function(raw,pipe){
				var pos = raw.data.position;
				var pubid = pipe.pipe.pubid;
				
				that.imageshare.delete_img(pubid, pos);
			},
			delete_img: function(pubid, pos){
				that.ISs[pubid].els.imgWindow.find('img').eq(pos).remove();
				that.ISs[pubid].els.thumbsScroller.find('div').eq(pos).remove();
			},
			receive_end: function(raw, pipe){
				var pipe = pipe.pipe;
				var pubid = pipe.pubid;
				
				$("<p class='sys em bold'><b style='"+pipe.properties.hex+"'>" + pipe.properties.name + ":</b> has closed their image-share.</p>")
					.appendTo(that.PMs[pubid].els.container);
			},
			start: function(raw,pipe){
				var pipe = pipe.pipe;
				var pubid = pipe.pubid;
				
				if( $('#imgshare'+pubid).length ) {
					$('#imgshare'+pubid).dialog('open');
					return false;
				}
				that.PMs[pubid].els.addRequest.remove();
				that.ISs[pubid] = {"properties": {"name":pipe.properties.name,"pubid":pubid}};
				that.ISs[pubid].active = true;
				that.ISs[pubid].els = {};
				
				var $imageShareDialog = $('<div id="imgshare'+pubid+'" />');
				var $topContainer = $('<div class="innerbg smallBorders share-imgs" style="padding:0 2px;" />').appendTo($imageShareDialog);
				that.ISs[pubid].els.imgWindow = $('<div />').appendTo($topContainer);
				
				var $botContainer = $('<div class="innerbg smallBorders" style="padding:0 2px; height: 88px; margin-top:3px;" />').appendTo($imageShareDialog);
				
				that.ISs[pubid].els.thumbsScroller = $('<ul class="share-thumbs" />').appendTo($botContainer);
				that.ISs[pubid].els.curImg = $('<ul class="smallBorders current-image"><li class="ui-corner-all"><img width="60" height="60" src="temp/dafault.png" />Others View</li></ul>').appendTo($botContainer);
				var addThumb = function(){
					var $thumb = $('<li class="ui-corner-all"><img width="60" height="60" src="http://weblogs.wxmi.com/news/traffic/dirty-windshield/US-31-logo-75x75.jpg" /></li>');
					$thumb.appendTo(that.ISs[pubid].els.thumbsScroller);
				};
				var resizeImgWindow = function($this){
					$topContainer.css('height', $this.height() - $botContainer.outerHeight(true) );
				};				
				var resizeThumbsWindow = function($this){
					that.ISs[pubid].els.thumbsScroller.css('width', $this.innerWidth(true) - that.ISs[pubid].els.curImg.outerWidth(true) -5 );
				};
				var resizeImgContainer = function() {
					that.ISs[pubid].els.imgWindow.css('height', $topContainer.height() - $imgButtons.height());
				}
				
				var $iframe = $('<iframe name="uploadTarget" />').appendTo('body');
				$iframe.hide();
				var buttonsHtml = '<ul id="pmHeader" class="horiBtns">';
				buttonsHtml += '<li class="upload">Add new image</li>';
				buttonsHtml += '<li><form action="ajax_chat.php?upload&pubid='+pubid+'&userid='+that.options.userid+'" enctype="multipart/form-data" method="POST" style="position:absolute; left: 0; opacity: 0;" target="uploadTarget">';
				buttonsHtml += '<input name="image" type="file" name="image" size="0" style="cursor:pointer;height:18px;" />';
				buttonsHtml += '</form></li>';
				buttonsHtml += '</ul>';
				var $imgButtons = $(buttonsHtml).prependTo($topContainer);
				var $uploadLink = $imgButtons.find('.upload');
				var $uploadBtn = $imgButtons.find('input[name=image]');
				var $uploadForm = $imgButtons.find('form');				
				$uploadBtn.change(function(ev){
			        $uploadForm.submit();
				});
				
				$imageShareDialog.dialog({
			  		bgiframe: true, title: 'Image share with ' + pipe.properties.name,
					width: 550, height: 425, position: 'right',
					resize: function(event, ui) {
						resizeImgWindow( $(this) );
						resizeThumbsWindow( $botContainer );
						resizeImgContainer();
						//that.ISs[pubid].els.imgWindow.find('img')
					},
					beforeclose: function(event, ui) {
						that.core.request.send('SHARESTOP',{'pubid':pubid,'position':'REMOVE ME SOON'});
					}
				});
				resizeImgWindow( $imageShareDialog );
				resizeThumbsWindow( $botContainer );
				resizeImgContainer();
	 		}
 	},
	
	channels:{
			init: function(){
				$("#createRoom").submit(function(ev){
					ev.preventDefault();
					
					if($("#roomname").val() != '')
						that.channels.joinChannel();
				});
			},
			
			openRoomlist: function(){
				$("#roomDialog").dialog('open');
				$("#roomlist-container").css("height", $("div#roomDialog").height() - $("div#roomDialog .innerbg:last").height() - $("div#roomListMsg").height() - 35);
				that.channels.listChannels();
			},
		
			listChannels: function(){
				$('dl#roomList > dt:first, dl#roomList > dd:first').addClass('ui-state-default');
				
				that.core.request.send('CLIST');
			},
			
			joinChannel: function(){
				var roomname = $("#roomname").val();
				var topic = $("#topicname").val();
					
				if ( roomname.replace(/[^a-zA-Z0-9]+/g,'') === roomname && roomname.length <= 32 ) {
					var wait = 0;
					if (that.currentPubid != null) {
						var leavepipe = that.core.getPipe(that.currentPubid);
						that.core.request.send('LEFT', {"channel": decodeURIComponent(that.core.pipes.get(that.currentPubid).name)});
						that.core.delPipe(that.currentPubid);
						that.currentPipe = null;
						that.currentPubid = null;
						var wait = 300;
					}
					var delayJoin = function() { that.core.join(roomname); };
					setTimeout(delayJoin,wait);
					if ( topic.length != 0 ){
						var delayTopic = function() { that.core.request.send('SETTOPIC',{"name":roomname,"topic":topic}); };
						setTimeout(delayTopic,600);
					}
					that.currentRoom = roomname;
				}
				else {
					that.errorPopup('Only a-Z and 0-9 is allowed for room names.  Max name length is 32.');
				}
			},
			
			addChannels: function(raw){
				$('dl#roomList > dt:gt(0), dl#roomList > dd:gt(0)').remove();
				if( raw.data == 0 ){
					$("<span>No rooms created.  Create one below.</span>")
				}	else	{
					raw.data.each(function(i){
						$("<dt><span>" + i.properties.nusers + "</span>" + decodeURIComponent(i.properties.name) + "</dt><dd>" + decodeURIComponent(i.properties.topic) + "</dd>")
							.bind("click", function(){
								$("#roomname").val(decodeURIComponent(i.properties.name));
								$("#topicname").val('');
							})
							.bind("dblclick", function(){
			      			that.channels.joinChannel();
			    			})
							.appendTo('dl#roomList');
					});
				}
			},
			
			closeRoomlist: function(){
				$("#roomDialog").dialog('close');
				$("#roomname").val('');
				$("#topicname").val('');
			}
	},
	
	buttons: {
			initAll: function(){
				that.buttons.buddyList.init();
				that.buttons.colorPicker.init();
			},
			
			topBar: {
				setName: function(){
					$('#logout').bind('click', function(event){
						that.quit();
					});
					$('#login-name').text(decodeURIComponent(that.options.name));
				},
				
				setUserCount: function(numusers){
					that.buttons.topBar.count = numusers;
					that.buttons.topBar.header = $('.header');
					that.buttons.topBar.header.text(numusers + ' RP\'ers online.');
				},
				
				updateUserCount: function(direction){
					numusers = that.buttons.topBar.count;
					if( direction == 'up')
						that.buttons.topBar.count = numusers+1;
					if( direction == 'down')
						that.buttons.topBar.count = numusers-1;
					that.buttons.topBar.header.text(that.buttons.topBar.count + ' RP\'ers online.');
				}
			},
			
			
			populateIgnores: function(user){
				that.buddyList.ignores.properties.nusers+=1;
				$("#listIgnores > .headText > span").text(that.buddyList.offlines.properties.nusers + '-');
				
				that.ignoresArray.push(decodeURIComponent(user.properties.name));
				user.ignoredElement = $('<li />').text(decodeURIComponent(user.properties.name))
					.rightClick( function(e) {
						that.dropdown.createDropdown(e, user, ["View Profile", "Unblock"]);
					})
					.appendTo("#listIgnores > ul");
			},
			
		 	buddyList: {
			 		init: function(){
			 			$(".createRoom").click(function(event){
			 				event.preventDefault();
							that.channels.openRoomlist();
			 			});
						
						$(".colorPick").click(function(e){
							that.buttons.colorPicker.move(this);
							e.stopPropagation();
						});
						
						$("#setstatus").submit(function(event){
							event.preventDefault();
							var newStatus = $("#setstatus input").val();
							if( newStatus == '')
								newStatus = 'none';
							that.buttons.buddyList.set_status(newStatus);
						});
			 		},
					set_status: function(newStatus) {
						that.core.request.send('STATUS',{'status':newStatus});
					},
					request_add: function(pubid) {
						that.core.request.send('REQUESTADD',{'pubid':pubid});
						that.PMs[pubid].els.addRequest = $("<p class='sys em bold'>You have sent a buddy request.</p>")
							.appendTo(that.PMs[pubid].els.container);
					},
					accept_add: function(pubid) {
						that.core.request.send('ACCEPTADD',{'pubid':pubid});
					},
					deny_add: function(pubid) {
						that.core.request.send('DENYADD',{'pubid':pubid});
					},
					add_denied: function(raw,pipe) {
							that.PMs[pubid].els.addRequest.text("Add request denied.  Future buddy requests from this user will be blocked for 24-48 hours.");
					},
					add_accepted: function(raw,pipe) {
						var pubid = pipe.pipe.pubid;
						var username = pipe.properties.name
						that.PMs[pubid].els.addRequest.text("You and "+username+" are now buddies!");
						
						that.buddyList.offlines.properties.users[username] = {"casttype":"uni", "pubid":pubid, "properties":{"name":username, "status":"none", "hex":"000000"}};
						var user = that.buddyList.offlines.properties.users[username];
						that.populateOfflines(user);
						
						var raw = {"data":{"casttype":"uni", "pubid":pubid, "name":pipe.properties.name, "status":"none", "hex":"000000"}};
						that.setOnline(raw);
					},
					receive_add_request: function(raw, pipe) {
						var pubid = pipe.pipe.pubid;
						that.PMs[pubid].els.addRequest = $("<p class='sys em bold'><b style='"+pipe.properties.hex+"'>" + pipe.properties.name + ":</b> has sent you a request to add you to their buddylist.  You may </p>")
							.append(
								$('<a href="#" />').text('Accept').click(function(ev){
									ev.preventDefault();
									that.buttons.buddyList.accept_add(pubid);
								})
								.add('<span> or </span>')
								.add(
									$('<a href="#" />').text('Deny').click(function(ev){
										ev.preventDefault();
										that.buttons.buddyList.deny_add(pubid);
									})
								)
							)
								.appendTo(that.PMs[pubid].els.container);
					},
					errors: function(raw,pipe) {
						var pubid = pipe.pipe.pubid;
						if( raw.data.error = 101)
							$("<p class='sys em bold'>Unresponded request was already sent.</p>")
								.appendTo(that.PMs[pubid].els.container);
						if( raw.data.error = 102)
							$("<p class='sys em bold'>You are buddied with "+pipe.properties.name+" already.</p>")
								.appendTo(that.PMs[pubid].els.container);
						if( raw.data.error = 103)
							$("<p class='sys em bold'>Add request was already denied!</p>")
								.appendTo(that.PMs[pubid].els.container);
					}
		 	},
			
			colorPicker: {
					init: function() {
						$("#red, #green, #blue").slider({
							orientation: 'horizontal',
							range: "min",
							max: 165,
							value: 20,
							slide: that.buttons.colorPicker.refreshSwatch,
							change: that.buttons.colorPicker.refreshSwatch
						});
					},
					hexFromRGB: function(r, g, b) {
						var hex = [
							r.toString(16),
							g.toString(16),
							b.toString(16)
						];
						$.each(hex, function (nr, val) {
							if (val.length == 1) {
								hex[nr] = '0' + val;
							}
						});
						return hex.join('').toUpperCase();
					},					
					refreshSwatch: function() {
						var red = $("#red").slider("value")
							,green = $("#green").slider("value")
							,blue = $("#blue").slider("value")
							,hex = that.buttons.colorPicker.hexFromRGB(red, green, blue);
						$("#swatch").css("background-color", "#" + hex);
						$("textarea").css("color", "#" + hex);
						that.options.color = hex;
					},					
					hexToSliders: function(hexcolor) {
						var r = parseInt(hexcolor.slice(0,2), 16);
						var g = parseInt(hexcolor.slice(2,4), 16);
						var b = parseInt(hexcolor.slice(4,6), 16);
					
						$("#red").slider("value", r);
						$("#green").slider("value", g);
						$("#blue").slider("value", b);
					},
					rgbFromCSS: function(rgbcss) {
						var _rgb = rgbcss.match(/\d+/g);
						r = parseInt(_rgb[0], 10);
						g = parseInt(_rgb[1], 10);
						b = parseInt(_rgb[2], 10);
						
						var hex = that.buttons.colorPicker.hexFromRGB(r, g, b);
						return hex;
					},
					move: function(target){
						$("#colorPicker").show().prependTo(target);
						
						$(document).unbind('click');
						$(document).bind('click', function(e){
							that.buttons.colorPicker.set_color(that.options.color);
							$("#colorPicker").hide();	
							$(document).unbind('click');						
						});
					},
					set_color: function(newHex) {
						that.core.request.send('COLOR', {'hex': newHex});
						that.cookie.set();
					}
			}
	},
	
	dropdown: {
			createDropdown: function(clickPos, userDOM, list){
				var html = '<ul class="ui-widget ui-widget-content ui-corner-all" style="z-index: 9999; width: 125px; padding: 2px;">';
				html += '<li style="padding: 2px;">';
				html += '<ul class="innerbg smallBorders" />';
				html += '</li>';
				html += '</ul>';
				var buttonhtml = '<li class="listBtn ui-corner-all">Placeholder</li>';
				
				var menu = $(html).appendTo("body");
				menu.position({
				    my: "left top", of: clickPos, offset: "3 -3", collision: "flip"
				});
				var menuList = menu.find('ul');
				
				$.each(list, function(index, tag) { 
					that.dropdown.addListItem(menuList, userDOM, tag);
				});
				menuList.append('<li class="clear" />');
					
				$(document).bind("click", function(ev){
					if( ev.target != clickPos.target)
						menu.remove();
				});
			},
			
			addListItem: function(el, userDOM, tag){
				if( tag == "HR"){
					$('<hr style="margin: 3px 0;"/>')
						.appendTo(el);
					return false;
				}
				var buttonhtml = '<li class="listBtn ui-corner-all">' + tag + '</li>';
				$(buttonhtml).bind("click", function(){
					that.dropdown.action(userDOM, tag);
				}).hover(function(){ 
						$(this).addClass("ui-widget-header");
					},	function(){ 
						$(this).removeClass("ui-widget-header");
					})
						.appendTo(el);
			},

			action: function(userDOM, action){
				switch (action) {
					case "View Profile":{
						window.open("http://www.rphaven.com/profile.php?user="+ decodeURIComponent(userDOM.properties.name));						
						break;
					}
					case "Open PM":{
						if(!that.core.getPipe(userDOM.pubid)){
							userDOM.pipe = {pubid:userDOM.pubid,properties:userDOM.properties};
							var pipe = that.core.newPipe('uni', userDOM);
							that.setCurrentPMPipe(pipe.getPubid());
						}
						if (!$("#pmDialog").dialog('isOpen')) {
							$("#pmDialog").dialog('open');
							resizePMtextdiv();
						}
						break;
					}
					case "Block":{
						$.ajax({
							type: "POST", url: 'ajax_chat.php?ignore', dataType: 'json', 
							data: "user=" + decodeURIComponent(userDOM.properties.name) + "&accid=" + that.options.accid,
							success : function (json) {
								if (json.error == 'true') {
									that.errorPopup(json.msg);
								}
							}
						});
						that.buttons.populateIgnores(userDOM);
						break;
					}					
					case "Unblock":{
						$.ajax({
							type: "POST", url: 'ajax_chat.php?unignore', dataType: 'json', 
							data: "user=" + decodeURIComponent(userDOM.properties.name) + "&accid=" + that.options.accid
						});
						var ignoresArrayPosition = $.inArray(decodeURIComponent(userDOM.properties.name), that.ignoresArray);
						delete that.ignoresArray[ignoresArrayPosition];
						userDOM.ignoredElement.remove();						
						break;
					}					
					case "Make Operator":{
						that.core.request.send('MAKEOP',{'room':that.userLocation[userDOM.properties.name],'name':decodeURIComponent(userDOM.properties.name)});
						break;
					}					
					case "Remove Ops":{
						that.core.request.send('REMOVEOP',{'room':that.userLocation[userDOM.properties.name],'name':decodeURIComponent(userDOM.properties.name)});
						break;
					}					
					case "Kick":{
						html = '<div class="innerbg smallBorders" style="height:100%"><form><label for="reason">Reason</label><input type="text" placeholder="Reason for kicking" id="reason" class="text ui-widget-content ui-corner-all" /></form></div>';
						$('<div />').append(html).dialog({
							bgiframe: true,
							title: "Confirm Kick",
							height: 300,
							width: 350,
							buttons: {
								'Kick': function(event) {
									var msg = $(this).find('input').val();
									that.core.request.send('KICK',{'msg':msg,'room':that.userLocation[userDOM.properties.name],'name':decodeURIComponent(userDOM.properties.name)});
									$(this).dialog('close');
								},
								'Cancel': function(event) {
									$(this).dialog('close');
								}
							}
						});
						break;
					}					
					case "Ban":{
						html = '<div class="innerbg smallBorders" style="height:100%"><form><label for="reason">Reason</label><input type="text" placeholder="Reason for banning." id="reason" class="text ui-widget-content ui-corner-all" /></form>Note:  This will ban their whole account.</div>';
						$('<div />').append(html).dialog({
							bgiframe: true,
							title: "Confirm Ban",
							height: 300,
							width: 350,
							buttons: {
								'Ban': function(event) {
									var msg = $(this).find('input').val();
									that.core.request.send('BAN',{'msg':msg,'room':that.userLocation[userDOM.properties.name],'name':decodeURIComponent(userDOM.properties.name)});
									$(this).dialog('close');
								},
								'Cancel': function(event) {
									$(this).dialog('close');
								}
							}
						});
						break;
					}					
					case "Unban":{
						that.core.request.send('UNBAN',{'room':that.currentRoom,'name':decodeURIComponent(userDOM.properties.name)});
						break;
					}
				}
			}
	},
	
	cookie: {
			set: function(){
				var tocookie = encodeURIComponent($.toJSON(that.options));
				$.cookie(that.options.name, tocookie, { path: '/', expires: 60 });
			},
			
			get: function(username){
				var cookie = $.cookie(username);
				if(cookie != null) {
					cookieJSON = $.evalJSON(decodeURIComponent(cookie));
					that.options.color = cookieJSON.color;
					/*that.options.bgcolor = cookieJSON.bgcolor;*/
				}
			}
	},
	
	errorPopup: function(message){
		$("#errorDialog").dialog('open');
		$("#errorDialog").find("p").replaceWith('<p class="ui-state-error ui-corner-all"><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>' + message + '</p>');
	},
	
	disconnected: function(){
		that.errorPopup('Your connection has been lost.<br />You must refresh to reestablish a connection and log in.<br />You can close this window to copy text before refreshing.');
	},
	
	/*restoreEnd: function(){
		$(that).bind(that.core.getSession('currentPipe',function(resp){
			if(resp.raw=='SESSIONS') that.setCurrentPipe(resp.data.sessions.currentPipe);
			})
		);
	}*/
	restoreEnd: function(){
		$(that).bind(that.core.request.setOptions({
				'callback':function(resp){
					if(resp.raw=='SESSIONS' && resp.data.sessions.currentPipe) that.setCurrentPipe(resp.data.sessions.currentPipe);
				}
			})
		);
		this.core.getSession('currentPipe');
	},
	
	errorHandler: function(raw) {
		if(raw.data.code != 004 && raw.data.code != 005 && raw.data.code != 250 && raw.data.code != 301 && raw.data.code != 310 && raw.data.code != 320 && raw.data.code != 321 && raw.data.code != 330 && raw.data.code != 999)	{
			$("#mainChat > dl").append('<p class="subAlert">Unspecified error: ' + raw.data.code + ' ' + raw.data.value + '.  The error isn\'t an issue if things are still working fine.  If things aren\'t working fine, or the error keeps repeating, then just refresh.  If you can reproduce the problem, post it on the support blog.  Make sure it isn\'t already posted first though!</p>');
		}
		else {
			if(raw.data.code == 004)
				that.errorPopup('Your connection has been lost.<br />You must refresh to reestablish a connection and log in.<br />You can close this window to copy text before refreshing.');
			if(raw.data.code == 005)
				that.login.nickUsed();
			if(raw.data.code == 310)
				that.errorPopup('You do not have ownership rights to that room.');
			if(raw.data.code == 301)
				that.errorPopup('Topic too long.');
			if(raw.data.code == 320)
				that.errorPopup('Status message must be 20 chars or less.  Donating will increase the limit to 100.  Some characters(spaces, commas) are escaped and count as 2-3 characters.');
			if(raw.data.code == 321)
				that.errorPopup('Status message must be 100 chars or less. Some characters(spaces, commas) are escaped and count as 2-3 characters.');
			if(raw.data.code == 999)
				that.errorPopup('Only donators can use this feature.');
			
			if(raw.data.code == 330)	
				$("#loginDialog").find("p").replaceWith('<p class="ui-state-error ui-corner-all" style="padding: 1em .7em;"><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span><strong>Error:</strong>Your version of the chat is too old .  You must clear your browsers cache and refresh before you may log in.</p>');
		}
	},
	
	make_admin_toolbar: function(){
		$('#top p').prepend(
				$('<a />').text('Admin').click(function(e){
					e.preventDefault();
					$("#adminDialog").dialog('open');
					$("#mass-message").submit(function(e){
						e.preventDefault();
						var msg = $("#mass-message input").val();
						var type = $("#mass-message select").val();
						
						that.core.request.send('MASS', {'msg':msg,'type':type});
					});
				})
			);
	},
	
	quit: function(){
		this.core.quit();
		this.core.initialize(that.core.options);
		this.login.prompt();
	},
	
	reset: function(){
		if (that.core.status != 0) {
			that.core.clearSession();
			that.core.initialize(that.core.options);
			that.login.prompt();
		}
	}
});
