var posting = false;

/*
 *
 *	jQuery Timer plugin v0.1
 *		Matt Schmidt [http://www.mattptr.net]
 *
 *	Licensed under the BSD License:
 *		http://mattptr.net/license/license.txt
 *
 */
$.timer = function (interval, callback)
{
	var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
};

// Function to Disable/Enable input fields
function input_disable(type)
{
	disableThis = document.getElementsByTagName('input');
	for (i = 0; i < disableThis.length; i++)
		disableThis[i].disabled = type;
}

// Request function to get possible new messages
function get_messages()
{
	//alert('get_messages');
	var args = 'last_msg='+LastMsg;
	$.ajax({
		type: 'GET',
		url: chatbox_get,
		data: args,
		success: function(msg) {
			handleResponse(msg);
		}
	});
}

// Request function to send new message
function send_message()
{
	var req_msg = encodeURIComponent($('#reqChatboxMsg').val());

	// Send message
	var args = 'last_msg='+LastMsg+'&req_msg='+req_msg;
	$.ajax({
		type: 'POST',
		url: chatbox_post,
		data: args,
		success: function(msg) {
			handleResponse(msg);
		}
	});

	// Disable input fields while posting
	input_disable(true);
	// Let the script know that we're trying to post
	posting = true;
}

// Request function to delete message
function delete_message(delete_link)
{
	if (!confirm('Voulez-vous vraiment supprimer ce message ?'))
		return false;

	var reg = /[0-9]+$/;
	var resultat = reg.exec(delete_link);
	var id = resultat[0];
	$('#chatboxmsg'+id).addClass('highlight');
	$('#chatboxmsg'+id).fadeOut('slow', function() {
		$.get(delete_link);
	});

	// Disable input fields while posting
	input_disable(true);
	// Let the script know that we're trying to post
	posting = true;
}

// Request function to edit message
function edit_message(edit_link)
{
	$('#autoscroll:checked').attr('checked', false);
	var reg = /[0-9]+$/;
	var resultat = reg.exec(edit_link);
	var id = resultat[0];

	// Get message
	var args = 'req_msg=true';
	$.ajax({
		type: 'GET',
		url: edit_link,
		data: args,
		success: function(msg) {
			var value = $('#chatboxmsg'+id+' .chatboxmsg').html();
			$('#chatboxmsg'+id+' .chatboxmsg').html('<script type="text/javascript">var value = \''+value+'\';</script><textarea cols="28" rows="6" id="chatboxmsgedit'+id+'" style="margin-bottom:2px;">'+msg+'</textarea><br /><input type="button"value="Ok" onclick="_edit_message(\''+edit_link+'\', $(\'#chatboxmsgedit'+id+'\').val()); return false;" />&nbsp;<a href="'+edit_link+'" onclick="$(\'#chatboxmsg'+id+' .chatboxmsg\').html(edit_message_cancel(this.href)); return false;">Annuler</a>');
		}
	});
}
function _edit_message(edit_link, msg)
{
	var reg = /[0-9]+$/;
	var resultat = reg.exec(edit_link);
	var id = resultat[0];
	var req_msg = encodeURIComponent(msg);

	// Send message
	var args = 'message='+req_msg;
	$.ajax({
		type: 'POST',
		url: edit_link,
		data: args,
		success: function(msg) {
			$('#chatboxmsg'+id+' .chatboxmsg').html(msg);
		}
	});

	// Disable input fields while posting
	input_disable(true);
	// Let the script know that we're trying to post
	posting = true;
}

// Annuler l'édition du message
function edit_message_cancel(edit_link)
{
	var message = '';
	var get_link = edit_link.replace('modifier', 'get');

	// Get message
	$.ajax({
		type: 'GET',
		url: get_link,
		async: false,
		success: function(msg) {
			message = msg;
		}
	});

	return message;
}

// Get the response server
function handleResponse(request)
{
	var LastMsgInfo = '';

	// We're getting a valid response, first get the latest timestamp
	LastMsgInfo = request.substring(0, 10);

	// If error, we display error message
	if (LastMsgInfo == 'error:chat')
	{
		error = request.substring(10, request.length);
		$('#chatbox').append(error) + '\n';
	}
	// If it's a posted response we get message(s)
	else if (LastMsgInfo == 'PostedInDB')
		get_messages();
	// If Response TimeStamp != Send TimeStamp we display new message
	else if (LastMsgInfo != LastMsg)
	{
		LastMsg = LastMsgInfo;
		messages = request.substring(10, request.length);
		// Add all new message(s)
		$('#chatbox').append(messages) + '\n';
	}
	// If we was posting !
	if (posting == true)
	{
		// Re-enable input fields after posting but we need min 500ms beetween each post for good timestamp order
		setTimeout('input_disable(false)', 500);
		// If no error, we delete "req_msg" value
		if (LastMsgInfo != 'error:chat')
			$('#reqChatboxMsg').val('');
		// Put focus in the input message box
		$('#reqChatboxMsg').focus();
		// Let the script know that we're not trying to post.
		posting = false;
	}

	// Auto Scroll chatbox if is checked
	var checked = $('#autoscroll:checked').attr('checked');
	if (checked)
		$('#chatbox').scrollTop($('#chatbox').attr('scrollHeight'));
}

