﻿$(document).ready(function(){
	//global vars
	var aidValue = $("#aid");
	var suserValue = $("#suser");
	var inputMessage = $("#message");
	var loading = $("#loading");
	var messageList = $(".content");
	//functions
	function updateShoutbox(){
		messageList.hide();
		loading.fadeIn();
		var aid = aidValue.attr("value");
		var suser = suserValue.attr("value");
		$.ajax({
			type: "POST", url: "comments.php", data: "action=update&aid=" + aid + "&suser=" + suser,
			complete: function(data){
				loading.fadeOut();
				messageList.html(data.responseText);
				messageList.fadeIn(10);

			}
		});
	}
	//check if all fields are filled
	function checkForm(){
		if (inputMessage.attr("value"))
			return true;
		else
			return false;
	}
	
	//Load for the first time the shoutbox data
	//updateShoutbox();
	loading.fadeOut();
	//on submit event
	$("#form").submit(function(){
		if(checkForm()){
			var message = inputMessage.attr("value");
			var aid = aidValue.attr("value");
			var suser = suserValue.attr("value");
			//we deactivate submit button while sending
			$("#send").attr({ disabled:true, value:"Sending..." });
			$("#send").blur();
			//send the post to shoutbox.php
			$.ajax({
				type: "POST", url: "comments.php", data: "action=insert&message=" + message + "&aid=" + aid + "&suser=" + suser,
				complete: function(data){
					messageList.html(data.responseText);
					updateShoutbox();
					//reactivate the send button
					$("#send").attr({ disabled:false, value:"Post Comment" });
				}
			 });
		}
		else alert("Please fill all fields!");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
});