/* this function initiates the chat; it executes when the chat page loads */
function init(){
        checkUsername();
}

// function that ensures that the username is never empty and if so 
// a random name is generated
function checkUsername(){
        var oUser=document.getElementById("nick");
        if(oUser.value == "")
          oUser.value = "Guest " + Math.floor(Math.random() * 1000);
}
$("#nick").blur(function(){
        checkUsername();
});
$("#nick").mouseover(function(){
        checkUsername();
});

$(document).ready(function(){
	//global vars
	var inputUser = $("#nick");
	var inputMessage = $("#message");
	var loading = $("#loading");
	var messageList = $(".scroll-pane");
        var reload = $("#reload");
                           	
	//update chat
        function updateShoutbox(){
		//just for the fade effect
		messageList.hide();
		loading.fadeIn();
		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "http://fast-const.ru/infusions/chat_panel/shoutbox.php", data: "action=update",
			complete: function(data){
				loading.fadeOut();
				messageList.html(data.responseText);
				messageList.fadeIn(1000);
			}
                });
	}

	//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();
        $("#reload").click(function(){
                        updateShoutbox();
        });
        
	//on submit event
	$("#form").submit(function(){
		if(checkForm()){
			var nick = inputUser.attr("value");
			var message = inputMessage.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: "http://fast-const.ru/infusions/chat_panel/shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message,
				complete: function(data){
					messageList.html(data.responseText);
					updateShoutbox();
					//reactivate the send button
					$("#send").attr({ disabled:false, value:"" });
				}
			 });
		}
		else alert("Please fill all fields!");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
});