function ircSetNick() {
	//var nick = getThingy('chatnick');

	window.nick = window.htirc.nick;
}

function userJoined(user, chan) {
	var message;
	var frame = window.htirc.frames.get(chan);

	if(insEqual(user, this.nick.get())) {
		message = '--> You are now talking on ' + chan;
		frame.activate();
	}
	else {
		message = '--> ' + user + ' has joined ' + chan;
		frame.nl.add(user);
	}

	frame.append(message);
}

function userLeft(user, chan, kicker, pmsg) {
	var message;
	
	// Don't recreate the frame if we just destroyed it.
	if(!window.htirc.frames.exists(chan)) { return; }

	var frame = window.htirc.frames.get(chan);
	
	if(insEqual(user, this.nick.get())) {
		if(kicker) {
			message = '<-- You have been kicked out of ' + chan + ' by ' + kicker;
		} else {
			message = '<-- You have left ' + chan;
		}
		frame.nl.clear();
	}
	else {
		if(kicker) {
			message = '<-- ' + user + ' has been kicked out of ' + chan + ' by ' + kicker;
		} else {
			message = '<-- ' + user + ' has left ' + chan;
		}
		frame.nl.del(user);
	}
	
	if(pmsg) {
		message += ' (' + pmsg + ')';
	}
	
	frame.append(message);
}

function ircCommand(text) {
	if(text.substr(0, 1) == '/') {
		var command;
		if(command = /^\/(.*?) (.*)$/.exec(text)) {
			if(command[1] == 'me' || command[1] == 'action') {
				//XXX FIXME
				appendChatLine('* ' + this.nick.get() + ' ' + command[2], window.htirc.frames.current.id);
				serverSendText('PRIVMSG ' + window.htirc.frames.current.id + ' :\001ACTION ' + command[2] + '\001');
			}
			else if(command[1] == 'eval') {
				eval(command[2]);
			}
			else {
				serverSendText(text.substring(1));
			}
		}
	}
	else if(text == '') {
		/* do nothing */
	}
	else {
		ircPrivMsg(window.htirc.frames.current.id, text);
	}
}

function ircPrivMsg(dst, text) {
	appendChatLine('<' + this.nick.get() + '> ' + text, dst);
	serverSendText('PRIVMSG ' + dst + ' :' + text);
}

function openQuery(target) {
	var f = window.htirc.frames.get(target);
	f.activate();
	f.append('--> Starting private conversation with ' + target);
}

function maskGetNick(mask) {
	return mask.split('!')[0];
}

function insEqual(a, b) {
	return(a.toLowerCase() == b.toLowerCase());
}

window.onunload = function () {
	serverSendText('QUIT :');
}
