var g_Posting = false;
//------------------------------------------------------
// Function to Disable/Enable input fields
//------------------------------------------------------
function DisableInput(type)
{
	disableThis = document.getElementsByTagName("input");
	for (i=0; i< disableThis.length; i++)
	{
		disableThis[i].disabled = type;
	}
}

//------------------------------------------------------
// Request function for get possible new messages
//------------------------------------------------------
function GetMessages()
{
	var myRequest = new Request(
	{
		url: 'chatbox.php',
		method: 'get',
		data:
		{
			'ajax': '1',
			'last_msg': LastMsg
		},
		onSuccess: RequestResponse
	}).send();
	$('loading').setStyle('display', '');
}

//------------------------------------------------------
// Request function for send new message
//------------------------------------------------------
function SendMessage()
{
	var myRequest = new Request(
	{
		url: 'chatbox.php',
		method: 'post',
		data:
		{
			'ajax': '1',
			'last_msg': LastMsg,
			'form_user': $('form_user').value,
			'req_username': $('req_username').value,
			'req_email': $('req_email').value,
			'email': $('email').value,
			'req_message': $('req_message').value
		},
		onSuccess: RequestResponse
	}).send();
	$('loading').setStyle('display', '');

	DisableInput(true);
	g_Posting = true;
}

//------------------------------------------------------
// Get the response server
//------------------------------------------------------
function RequestResponse(Response)
{
	$('loading').setStyle('display', 'none');
	var LastMsgInfo = '';
	LastMsgInfo = Response.substring(0, 10);

	if( LastMsgInfo == 'error:chat' )
	{
		error = Response.substring(10, Response.length);
		var chatbox = $('chatbox');
		chatbox.innerHTML = chatbox.innerHTML + error + '\n';
	}
	else if( LastMsgInfo == 'PostedInDB' )
	{
		GetMessages();
	}
	else if( LastMsgInfo != LastMsg )
	{
		LastMsg = LastMsgInfo;
		messages = Response.substring(10, Response.length);
		var chatbox = $('chatbox');
		chatbox.innerHTML = chatbox.innerHTML + messages + '\n';
	}
	
	if( g_Posting == true )
	{
		( function() { DisableInput(false); } ).delay(500);
		if (LastMsgInfo != 'error:chat')
			$('req_message').value = '';

		document.formulaire.req_message.focus();
		g_Posting = false; 
	}

	if( $('autoscroll').checked == true ){$('chatbox').scrollTop = $('chatbox').scrollHeight;}
}

