var g_lngCountMessages = 0;
var g_strInputText = "";

// RequestIDs
var GET_MESSAGES 	= 1;
var INSERT_MESSAGE 	= 2;
var CHECK_MESSAGES 	= 3;

/*
*	G E T   M E S S A G E
*/
// gets evry 500 milliseconds the messages from the database
function fctGetMessages( )
{
	sendRequest( 'includes/inc/chat_response.php', 'action=getMessages', REQUEST_POST, GET_MESSAGES );
}

function fctHandleResponseMessages( xmlHttp )
{
	var objDiv = document.getElementById( "messages" );
	var arrResponse = xmlHttp.responseText.split( "#%#" );
	// in arrResponse[ 0 ] are the messages, in arrResponse[ 1 ] the new count
	
	if( objDiv != null )
	{
		objDiv.innerHTML = arrResponse[ 0 ];
	}
	
	g_lngCountMessages = arrResponse[ 1 ];
}

/*
*	I N S E R T   M E S S A G E
*/
function fctInsertMessage( p_user_id )
{
	objField = document.getElementsByName( "txtmessage" )[ 0 ];
	
	if( objField != null )
	{
		g_strInputText = objField.value;
		//objField.value = "";
		objField.readOnly = true;
		sendRequest( 'includes/inc/chat_response.php', 'action=insMessage&value=' + g_strInputText + '&user_id=' + p_user_id, REQUEST_POST, INSERT_MESSAGE );
	}
}

function fctHandleResponseInsertMessage( xmlHttp )
{
	var objField = document.getElementsByName( "txtmessage" )[ 0 ];
	
	// wenn die nachricht nicht hinzugefügt werden konnte => text wieder rein schreiben
	if( xmlHttp.responseText == "error" )
	{
		if( objField != null )
		{
			objField.value = g_strInputText;
		}
	}
	else
	{
		if( objField != null )
		{
			objField.value = "";
		}
	}
	
	if( objField != null )
	{
		objField.readOnly = false;	
	}
}

/*
*	C H E C K   O N   N E W   M E S S A G E S
*/
function fctCheckOnNewMessges( )
{
	sendRequest( 'includes/inc/chat_response.php', 'action=checkMessages&count=' + g_lngCountMessages, REQUEST_POST, CHECK_MESSAGES );
	window.setTimeout( "fctCheckOnNewMessges( '' )", 500 );
}

function fctHandelCheckOnNewMessages( xmlHttp )
{
	if( xmlHttp.responseText != g_lngCountMessages )
	{
		fctGetMessages( );
	}
	else if( g_lngCountMessages == 0 )
	{
		if( document.getElementById( "messages" ) )
		{
			document.getElementById( "messages" ).innerHTML = "[ no messages available ]";	
		}
	}
}

function fctCheckChat( )
{
	// checks if there are new messages in the database
	if( document.chat )
	{
		fctCheckOnNewMessges( );
	}
}