var ChatBox = {
lastId: null,
timeout: null,
requests: $A([]),
disabled: false,
names: ['you', 'other'],

effect_open_close: false,

open: function() {
	ChatBox.arrow_dirrect(true);
	if(!ChatBox.disabled)
	{
		return false;
	}
	if(ChatBox.effect_open_close)
	{
		setTimeout("ChatBox.open();", 700);
		return false;
	}
	ChatBox.effect_open_close=true;
	Effect.BlindDown('chatbox',
		{
			afterFinish: function(){
				ChatBox.init.bind(this);
				ChatBox.enable();
				ChatBox.effect_open_close=false;
				ChatBox.refresh();
			}
		}
	);
},
close: function() {
	ChatBox.arrow_dirrect(false);
	if(ChatBox.disabled)
	{
		return false;
	}
	if(ChatBox.effect_open_close)
	{
		setTimeout("ChatBox.close();", 700);
		return false;
	}
	ChatBox.effect_open_close=true;
	Effect.BlindUp('chatbox',
		{
			afterFinish: function(){
				ChatBox.disable();
				ChatBox.effect_open_close=false;
			}
		}
	);
},
toggle: function() {
	if(ChatBox.disabled)
	{
		ChatBox.open();
	}
	else
	{
		ChatBox.close();
	}
},
init: function() {
	var box = $('chatbox');
	['mouseover', 'keydown'].each(function(eid) { Event.observe(box, eid, ChatBox.mouseover, true); });
	Event.observe(box, 'mouseout', ChatBox.mouseout, false);
	Form.focusFirstElement($$('#chatbox form').first());
	this.scroll();
},
mouseover: function(ev) {
	$('chatbox').setOpacity(1);
},
mouseout: function(ev) {
	$('chatbox').setOpacity(.4);
},
dispose: function() {
	var box = $('chatbox');
	box.setOpacity(1);
	['mouseover', 'keydown'].each(function(eid) { Event.stopObserving(box, 'mouseover', ChatBox.mouseover, true); });
	Event.stopObserving(box, 'mouseout', ChatBox.mouseout, false);
},
send: function() {
	try {
		var input = $('chatinput');
		var txt = input.value;
		input.value = "";
		if(!/\S/.test(txt)){return;}
		//this.updateLog([[0, txt.escapeHTML(), Math.round(new Date().getTime() / 1000) ]]);
	} catch(ex) {}
	this.cancelUpdate();
	this.refresh(txt);
},
tmpad: function(n) {
	return n < 10 ? "0".concat(n) : n;
},
updateLog: function(lines, lastId) {
	lines = $A(lines);
	lastId = lines.last()[3] || false;
	var chatlog = $('chatlog');
	if(!this.lastId) {
		chatlog.innerHTML = "";
	} else {
		if(lastId) lines = lines.reject(function(l) { return l[3] && $('m' + l[3]); });
	}
	html = lines.map(function(l) {
		var idx = l[0];
		if (idx != 0){idx = 1;}
		var d = new Date(l[2] * 1000);
		var tm = this.tmpad(d.getHours()) + ":" + this.tmpad(d.getMinutes());
		var id = "m" + l[3];
		var name = l[4];
		if(name)
		{
			var res_name = name;
		}
		else
		{
			var res_name = this.names[idx];
		}

		return '<span id="'+id+'"><span class="'+'chat'+idx+'">'+res_name+': </span>'+l[1]+'</span><br \>';
	}.bind(this)).join('');

	if(html)
	{
		new Insertion.Bottom(chatlog, html);
		window.setTimeout(ChatBox.afterInsertion.bind(this), 0);
	}

	if(lastId)
	{
		this.lastId = lastId;
	}
},
afterInsertion: function() {
	var chatbox = $('chatbox');
	if(chatbox.visible())
	{
		chatbox.setOpacity(1);
		this.scroll();
	}
	else
	{
		this.open();
	}
},

scroll: function() {
	var chatlog = $('chatlog');
	var off = chatlog.scrollHeight - chatlog.offsetHeight;
	if(off >= 0) {
		chatlog.scrollTop = off;
	}
},

refresh: function(msg) {
	var parms = { c: 'chat', a: 'update' };
	if(this.lastId){parms['mid'] = this.lastId;}
	if(msg){parms['msg']=msg;}
	if(!parms['mid']){parms['mid'] = -1;}

	new Ajax.Request(location.pathname,
		{
			parameters: Hash.toQueryString(parms),
			onLoading: function(req) { ChatBox.requests.push(req) },
			onComplete: ChatBox.afterResponse.bind(this)
		}
	);
},

afterResponse: function(req) {
	this.requests = this.requests.without(req);
	this.cancelUpdate();
	this.timeout = window.setTimeout(function() { ChatBox.refresh() }, 3000);
	//this.scroll();
},

users: function() {
	var parms = { c: 'chat', a: 'users' };
	new Ajax.Request(location.pathname,
		{
			parameters: Hash.toQueryString(parms),
			onLoading: function(req) { ChatBox.requests.push(req) }
		}
	);
},

cancelUpdate: function() {
	if(this.timeout !== null){window.clearTimeout(this.timeout);}
	this.timeout = null;
},
abort: function() {
	this.cancelUpdate();
	var r;
	while(r = this.requests.pop()) r.abort();
},
reset: function() {
	this.abort();
	this.lastMsgId = null;
	$('chatlog').innerHTML = "";
},
disable: function() {
	this.abort();
//	this.reset();
	$('chatbox').hide();
	this.arrow_dirrect(false);
	this.disabled = true;
},
enable: function() {
	$('chatbox').show();
	this.arrow_dirrect(true);
	this.refresh();
	this.scroll();
	this.disabled = false;
},
arrow_dirrect: function(up) {
	if(up)
	{
		$('chat_link_href').innerHTML='&uarr;';
	}
	else
	{
		$('chat_link_href').innerHTML='&darr;';
	}
},
cansend: function(flag)
{
	if(flag)
	{
		$('sendrow').show();
		$('pleasebox').hide();
	}
	else
	{
		$('sendrow').hide();
		$('pleasebox').show();
	}
}
}
new Ajax.Updater('online', '/index.php?c=chat&a=users', {evalScripts: true});
new Ajax.PeriodicalUpdater('online', '/index.php?c=chat&a=users',
{
	method: 'get',
	frequency: 3,
	decay: 1
});
