
(function($){
	$.fn.ajaxChat = function(params){
		
		var params = $.extend({
			refresh:1
		},params);
		
		var chat = function (jElt) {
			//jElt is the jQuery object where the function starts
			var chatContainer=jElt.find('.chat');
			var chat=chatContainer.find('div'); // this is div containing the messages
			var writeInput=jElt.find('.writeInput');
			var ajaxStatus=jElt.find('.ajaxStatus');

			// handle the submit message function
			var activateKeyboard = function(){
				writeInput.submit(function(){
					var input = $(this).find(':input');
					var message = input.val();
					
					if ($.trim(message).length > 0) { // need to have something to say !
						ajaxStatus.show();
						
						input.val('');
						input.blur();
						input.attr("disabled", "disabled"); // we have to this so there'll be less spam messages
						$.post("/website/general/chat_fonctions.php", { //this is the url of your server side script that will handle write function
							chat_fonction: "write",
							msg: message
						}, function(data){
							input.removeAttr("disabled");
							input.focus();
							readMessages();
							ajaxStatus.hide();
						}, 'json');
					}
					
					return false;
				});
			}
			
			// handle the read messages function
			
			var readMessages = function(){
				$.getJSON("/website/general/chat_fonctions.php", {
					chat_fonction: "read"
				}, function(data){
					$.each(data, function(i,msg){
						chat.append('<p><small>('+ msg.date +')</small> '+msg.pseudo+' : <strong>'+msg.message+'</strong></p>');
					});
				});
			}
			
			var boucle = function() {
				readMessages();
				setTimeout(boucle,params.refresh*1000);
			}
			
			activateKeyboard();
			boucle();
		}
		return this.each(function(){
			chat($(this));
		});
	};
})(jQuery)