﻿$(function() {
	//global vars
	var inputUser = $("#nick");
	var inputMessage = $("#message");
	var loading = $("#loading");
	var action_mid = $("#action_mid");
	var messageList = $("#gblist > ul");
	var postspeed = 30;
	setInterval(function(){
		postspeed ++;
	},1000);
	function updateShoutbox(){
		var actionmid = action_mid.attr("value");
		//just for the fade effect
		messageList.hide();
		loading.fadeIn();
		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "shoutbox.php", data: "action=update&action_mid=" + actionmid,
			complete: function(data){
				loading.fadeOut();
				messageList.html(data.responseText);
				messageList.fadeIn(2000);
				$('#gblist').scrollbar();
			}
		});
	}
	//check if all fields are filled
	function checkForm(){
		if(inputUser.attr("value") && inputMessage.attr("value"))
			return true;
		else
			return false;
	}
	
	//Load for the first time the shoutbox data
	updateShoutbox();
	
	//on submit event
	$("#form").submit(function(){
		
		if(checkForm()){
			if(postspeed > 30){
				var nick = inputUser.attr("value");
				var message = inputMessage.attr("value");
				var actionmid = action_mid.attr("value");
				//we deactivate submit button while sending
				$("#send").attr({ disabled:true, value:"處理中..." });
				$("#send").blur();
				//send the post to shoutbox.php
				$.ajax({
					type: "POST", url: "shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message + "&action_mid=" + actionmid,
					complete: function(data){
						messageList.html(data.responseText);
						updateShoutbox();
						postspeed = 0;
						inputUser.val("");
						inputMessage.val("");
						//reactivate the send button
						$("#send").attr({ disabled:false, value:"送出" });
					}
				 });
			}
			else alert("請在" +(30 - postspeed)+ "秒後再送出發表內容!!");
		}
		else alert("請輸入所有欄位暱稱與發表內容!!");

		//we prevent the refresh of the page after submitting the form
		return false;
	});
});
