
var BiobbleChat = new Class({
	frequency:0,
	hub_id:0,
	last_check:0,
	dom_title: 'chat_title',
	dom_content: 'chat_content',
	dom_user_msg: 'chat_user_msg',
	dom_msg_send: 'chat_send_button',
	onlink: false,

	initialize: function (hub_id, freq)
	{
	    var obj = this;
	    obj.frequency = freq;
	    obj.hub_id = hub_id;
	    obj.link = new Ajax ('/web/chat.php', {method:'post', onComplete:obj.updateComplete});
	    obj.periodical = obj.update.periodical(obj.frequency * 1000, obj);
	    $(obj.dom_msg_send).addEvent('click', obj.send);
	    $(obj.dom_user_msg).addEvent('keydown', obj.enterSend);
	},
	update: function ()
	{
	    biobbleChat.link.options.data = Object.toQueryString({last_check:biobbleChat.last_check,hub_id:biobbleChat.hub_id});
	    biobbleChat.onlink=true;
	    biobbleChat.link.request();
	},
	updateComplete:function (txt,xml)
	{
	    biobbleChat.onlink=false;
	    var r = new XML (xml).GetArray();
	    if (r.a == '0') {alert(r.msg); return;}
	    if (r.a == '1')
		{
		    if (r.warn)
			{
			    if (r.stop[0]) // stopping periodical check
				    $clear(biobbleChat.periodical);
			    biobbleChat.insertWarn(r.warn[0]);
			}
		    if (r.frequency[0])
			biobbleChat.frequency = r.frequency[0].toInt();
		    if (r.chattitle[0] && r.chattitle[0].length)
			$(biobbleChat.dom_title).setHTML(r.chattitle[0]);
		    if (r.chat)
			biobbleChat.updateChat(r.chat[0]);
		    biobbleChat.last_check = r.lastcheck[0];
		}
	    
	},
	updateChat: function(c)
	{
	    for (var i = 0; i < c.msg.length; i++)
	    {
		var li = new Element('li');
		new Element('b').setHTML(c.msg[i].username[0] +' ('+c.msg[0].date[0]+') : ').injectInside(li);
		li.appendText(c.msg[i].txt[0]);
		li.injectInside($(biobbleChat.dom_content));
	    }
	    new Fx.Scroll(biobbleChat.dom_content).toBottom();
	},
	insertWarn: function(m)
	{
	    var li = new Element('li');
	    new Element('b').setHTML(m).setStyle('color','red').injectInside(li);
	    li.injectInside($(biobbleChat.dom_content));
	    new Fx.Scroll(biobbleChat.dom_content).toBottom();
	},
	enterSend: function (e)
    {
	if (biobbleChat.onlink)
	    return;
	    var e = new Event(e);
	    if (e.key != 'enter')
		return;
	    if (!$(biobbleChat.dom_user_msg).value.length)
		return;
	    biobbleChat.link.options.data = Object.toQueryString({last_check:biobbleChat.last_check,hub_id:biobbleChat.hub_id,msg:$(biobbleChat.dom_user_msg).value});
	    $(biobbleChat.dom_user_msg).value = '';
	biobbleChat.onlink=true;
	    biobbleChat.link.request();
	},
	send: function()
	{
	    if (biobbleChat.onlink)
		return;
	    if (!$(biobbleChat.dom_user_msg).value.length)
		return;
	    biobbleChat.link.options.data = Object.toQueryString({last_check:biobbleChat.last_check,hub_id:biobbleChat.hub_id,msg:$(biobbleChat.dom_user_msg).value});
	    $(biobbleChat.dom_user_msg).value = '';
	    biobbleChat.onlink=true;
	    biobbleChat.link.request();
	}
});

/*
recep :
freq
warn
info
msg : username id txt date
title

*/