var bdir = './backends/';
var userListBox = 'chat_session_id';
var rooms = [];

function handleSuccess(transport){$('chat_block').show()}
function startChatListCheck(){new Ajax.PeriodicalUpdater(userListBox, bdir + 'get_user_list.php', {frequency: 15, decay: 1.5, onSuccess: handleSuccess})}
function handleInviteSuccess(transport){
	var response = transport.responseJSON;
	if(response.error){alert(response.error);return}
	if(response.msg){alert(response.msg);return}
}
function sendInvitation(sid){
	var msg; 
	if(msg = prompt('Wpisz treść zaproszenia (zostanie ona także użyta jako nazwa pokoju)', 'olala!')){
		new Ajax.Request(bdir + 'invite.php', {onSuccess: handleInviteSuccess, parameters: {'session_id':sid, 'msg' : msg}})
	}
	return false
}

function handleInvSuccess(transport){
	var response = transport.responseJSON;
	var msg = null;
	if(msg = response[0].msg){ // user/guest has an invitation!
		new Ajax.Request(bdir + 'inv_response.php', {parameters: {'accept':(confirm(msg)-0),'room_id':response[1].room_id}})
	}
}
function startChatInvtCheck(){new Ajax.PeriodicalUpdater('blocker', bdir + 'check_invs.php', {frequency: 10, decay: 1.5, onSuccess: handleInvSuccess})}
function handleChatCheckSuccess(transport){
	var response = transport.responseJSON;
	for(var i = 0; i < response.length; i++){
		var room = response[i];
		if(room.room_id && room.name){ // DAMN! We have to open the chat window!
			rooms.push(room);
		}
	}
	if(rooms.length > 0){generateRooms()}
}
function startChatCheck(){new Ajax.PeriodicalUpdater('blocker', bdir + 'chat_check.php', {onSuccess: handleChatCheckSuccess, frequency: 12, decay: 1.5, })}
function initChat(){
	startChatListCheck();
	setTimeout('startChatInvtCheck()', 1500);
	setTimeout('startChatCheck()', 3000);
}
function generateRooms(){
	var generated = 0;
	for(var i = 0; i < rooms.length; i++){
		var id = 'chat_window_' + rooms[i].room_id;
		if($(id) && $(id).src){continue}
		var ifr = new Element('iframe', {'id' : id, 'src' : 'chat_room.php?room_id=' + rooms[i].room_id, 'border': 1, 'frameborder' : 0, 'class' : 'chat_iframe' });
		Object.extend(ifr.style, {'width':'275px', 'height':'275px', 'position' : 'fixed', 'bottom' : '0px', 'right' : (280 * generated ) +'px', 'border' :'1px solid silver'});
		Element.insert(document.body, {'bottom': ifr});
		generated++;
	}
}
Event.observe(window, 'load', initChat);
