$(document).ready(function(){
	//global vars
	//var i = setInterval(function() { updateShoutboxAftur() }, 5000);
	var inputUser = $("#nick");
	var inputMessage = $("#message");
	var loading = $("#loading");
	var messageList = $(".statusar > div#shout");
	//functions
	function updateShoutbox(){
		//just for the fade effect
		messageList.hide();
		loading.fadeIn();
		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "/shoutbox2/update", data: "",
			complete: function(data){
				loading.fadeOut();
				messageList.html(data.responseText);
				messageList.fadeIn(500);
				
			}
		});
	}
	
	function updateShoutboxAftur(){

		//send the post to shoutbox.php
		$.ajax({
			type: "POST", url: "/shoutbox2/update", data: "",
			complete: function(data){

				messageList.html(data.responseText);

				
			}
		});
	}
	
	//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()){
			var nick = inputUser.attr("value");
			var message = inputMessage.attr("value");
			//we deactivate submit button while sending
			$("#send").attr({ disabled:true, value:"Sendi..." });
			$("#send").blur();
			//send the post to shoutbox.php
			$.ajax({
				url: "/shoutbox2/insert/" + nick + "/" + encodeURIComponent(message),
				complete: function(data){
					messageList.html(data.responseText);
					console.log(nick + "/" + message);
					updateShoutbox();
					//reactivate the send button
					$("#send").attr({ disabled:false, value:"Senda" });
				}
			 });
		}
		else alert("Vinsamlegast fylltu í alla reiti!");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
});
