function readCookie(name){
	var cookieValue = "";
	var search = name + "=";
	if(document.cookie.length > 0){ 
		offset = document.cookie.indexOf(search);
		if (offset != -1){ 
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
		if (end == -1) end = document.cookie.length;
			cookieValue = unescape(document.cookie.substring(offset, end))
		}
	}
	return cookieValue;
}

var currentUser = readCookie('username');

	function doChat() {
		var msg = document.getElementById('chat_input');
		if ($(msg).val().match(/^\/kick/i) || $(msg).val().match(/^\/topic/i) || $(msg).val().match(/^\/settopic/i)) { $.get('http://randomdrinking.com/chat/commands.php?cmd='+ msg.value +'', function(data) { addHistory('<span class=topic>'+ data +'</span>'); }); msg.value = ''; msg.focus(); } 
		if ($(msg).val().match(/^\/clear/i)) { $("div#history").empty(); msg.value = ''; msg.focus(); }
		if ($(msg).val().match(/^\/commands/i)) { addHistory('<span class=join-part><b>Available commands:</b><br />/clear - Clears the chat log.<br />/kick USER - Kicks the targeted user from the chat room.<br />/me MESSAGE - Action message<br />/settopic TOPIC - Changes the topic.<br />/topic - Gets the current topic.</span>'); msg.value = ''; msg.focus(); }
		else {
			if(!msg.value==''){ conn.publish('random', msg.value); }
			msg.value = '';
			msg.focus();
		}
	};
	
	function addHistory(txt) {
		var h = document.getElementById('history');
		h.appendChild(document.createElement('span')).innerHTML = txt;
		$("div#history").animate({ scrollTop: $("div#history").attr("scrollHeight") - $('div#history').height() });

	}
	
	function linkify(text){
		if( !text ) return text;
		text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){
			nice = url;
			if( url.match('^https?:\/\/') ) { nice = nice.replace(/^https?:\/\//i,'') } else
				url = 'http://'+url;			
			return '<a target="_blank" rel="nofollow" href="'+ url +'">'+ url +'</a>';
		});
		return text;
	}
	
	
	hookbox.logging.get('hookbox').setLevel(hookbox.logging.DEBUG);
	hookbox.logging.get('net.protocols.rtjp').setLevel(hookbox.logging.DEBUG);
	conn = hookbox.connect('http://randomdrinking.com:8000');
	conn.onSubscribed = function(channel_name, subscription) {
		SUB = subscription;
		
		var regex = new RegExp(currentUser, "i")
		subscription.onPublish = function(frame) {
			if (frame.payload.match(/^\/me/)) {
				addHistory('<span class="sender action">' + frame.user + '</span><span class="message action">' +  linkify(frame.payload.replace(/^\/me/,''))  + '</span>');
			}
			if (frame.payload.match(regex)){
				addHistory('<span class="highlight"><span class="sender">' + frame.user + '</span><span class="message">' + linkify(frame.payload) + '</span></span>');
			}
			else {
				addHistory('<span class="sender">' + frame.user + '</span><span class="message">' + linkify(frame.payload) + '</span>');
			}
		};

		
		subscription.onSubscribe = function(frame) {
			addHistory('<span class=join-part>' + frame.user + ' has joined the chat room.</span>');
		}
		
		subscription.onUnsubscribe = function(frame) {
			addHistory('<span class=join-part>' + frame.user + ' has left the chat room.</span>');
		}
		
		subscription.onFailure = function(msg) {
				alert('Error: ' + msg);
		}
		
		subscription.onState = function(frame) {
			addHistory("* Channel State Changed...");
		}
		
		for (var i = 0, item; item = subscription.history[i]; ++i) {
			var name = item[0];
			var frame = item[1];
			if (name == 'SUBSCRIBE') { subscription.onSubscribe(frame); }
			if (name == 'UNSUBSCRIBE') { subscription.onUnsubscribe(frame); }
			if (name == 'PUBLISH') { subscription.onPublish(frame); }
		}
		
	}
	
	conn.onUnsubscribed = function(sub, args) {
		addHistory('<span class=kick>You have been kicked from the chat room.</span>');
		$('input#chat_input').attr("disabled", true); 
	}
	
	conn.onError = function(frame) { alert("Error: " + frame.msg); }

