/**
*
*	Gauze - Chat
*	Copyright (C) 2010 John Croucher
*	Last updated on 09/01/10
*	
*	http://www.sixlabrats.com
*	
*
*/

var cur_timeout = 1000;
var min_timeout = 1000;
var max_timeout = 35000;

var timeout_inc = 100;

var bytes 		 = 0;
var usrhash 	 = 0;

var current_room = "lobby";

var timeout;

var update_locked = false;

$(document).ready(function() {
	if( $('#chat_text').length != 0 )
	{
		$('#rm_lobby').css({color:'red'});
		update();
		send_message('/join');
	}

});

function join_room(room)
{

	if( current_room != room )
	{
		$("#rm_" + current_room).css({color:'#666'});
		$("#rm_" + room).css({color:'red'});

		send_message('/leave');

		$("#chat_text").append("<p><font class=\"chat_system_message\">Moving to room #" + room + "</font></p>");

		bytes	  = 0;
		usrhash = 0;
		cur_timeout = 1000;

		current_room = room;
		send_message('/join');

		send_message('/getroominfo');
	}

}

function update() 
{ 
	var have_data = false;

	$.post("/chat/", { mode: "update", room: current_room, bytes: bytes, usrhash: usrhash }, function(data)
		{
	
			if( bytes != data.BYTES )
			{
				$("#chat_text").append(data.DATA);

				if( data.USERLIST != '' )
					$("#chat_users").html(data.USERLIST);

				bytes = data.BYTES;
				usrhash = data.USRHASH;

				if( data.DATA != '' ) 
					cur_timeout = min_timeout;

				$("#chat_text").attr({ scrollTop: $("#chat_text").attr("scrollHeight") });

			}

	},"json");
  
	if( (cur_timeout + timeout_inc) < max_timeout )
		cur_timeout = cur_timeout + timeout_inc;
	
	$('#chat_stats').html('[Refresh: ' + cur_timeout + 'ms]');

	timeout = setTimeout('update()', cur_timeout);


}

function send_message(message_data)
{

	
	if( jQuery.trim($("#chat_message").val()) != '' )
	{

		message_data = $("#chat_message").val();

		$("#chat_message").val('');

	}

	if( message_data == '/clear' )
	{
		$("#chat_text").html('');
	}
	 else if( message_data != '' && message_data != undefined )
	{
		$.post("/chat/", { mode: "sendmessage", room: current_room, message: message_data }, function(data){

			clearTimeout(timeout);

			update();

			if(data.status != "success")
			{
				$("#chat_text").append("<p><font class=\"chat_system_message\">" + data.status + "</font></p>");
			}

		},"json");

	}

}


function chat_key_pressed(keycode)
{

	if( keycode == 13 )
		send_message();
}

