/**
 * @author vincent voyer
 * vincent.voyer@gmail.com
 */
(function($){
	$.fn.ajaxShout = function(params){
		
		var params = $.extend({
			refresh:30
		},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("/shout/write.php", { //this is the url of your server side script that will handle the write function <--------------*
							msg: message
						}, function(data){
							input.removeAttr("disabled");
							input.focus();
							if (data) 
								$.getJSON("/shout/read.php", function(data){	// Re-read the DB to get ours and other message
									$.each(data, function(i,msg){
										// console.log("Return from read = " + data);
										chat.append('<p>'+msg.username+': <strong>'+msg.msg+'</strong></p>');
									});
									setTimeout(readMessages,params.refresh*1000);
								});	
							ajaxStatus.hide();
						}, 'json');
					}
					
					return false;
				});
			}
			
			// handle the read messages function
			var readMessages = function(){
				$.getJSON("/shout/read.php", function(data){	// this is the url of your server side script that will handle the read function <--------------*
					$.each(data, function(i,msg){
						// console.log("Return from read = " + data);
						chat.append('<p>'+msg.username+': <strong>'+msg.msg+'</strong></p>');
					});
					setTimeout(readMessages,params.refresh*1000);
				});
			}
			
			
			activateKeyboard();
			readMessages();
		}
		
		return this.each(function(){
			chat($(this));
		});	
		
	};
})(jQuery)