﻿$(document).ready(function(){
	//global vars
	var inputMessage = $("#message");
	var shoutsNr = $("#shouts_nr");
	//var loading = $("#loading");
	var messageList = $(".shoutboxcontent > ul");
	
	//functions
	function updateShoutbox(){
		//just for the fade effect
		//messageList.hide();
		//loading.fadeIn();
		//send the post to shoutbox.asp
		$.ajax({
			type: "POST", url: "/home/shoutbox.asp", data: "action=update",
			complete: function(data){
				//loading.fadeOut();
				messageList.html(data.responseText);
				//messageList.fadeIn(1);
			}
		});
		
	}


	//check if all fields are filled
	function checkForm(){
		if(inputMessage.attr("value"))
			return true;
		else
			return false;
	}


	function wbr(str, num) { 
	  return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){
		return text + " " + char;
	  });
	}


	//Load for the first time the shoutbox data
	updateShoutbox();
	
	//on submit event
	$("#shoutboxform").submit(function(){
		if(checkForm()){
			var message = inputMessage.attr("value");
			//message = escape(message);
			//message = wbr(message, 30)
			message = encodeURIComponent(message);
			//we deactivate submit button while sending
			$("#send").attr({ disabled:true, value:"Sending..." });
			$("#send").blur();
			//send the post to shoutbox.asp
			$.ajax({
				type: "POST", url: "/home/shoutbox.asp", data: "action=insert&message=" + message,
				complete: function(data){
					messageList.html(data.responseText);
					updateShoutbox();
					//reactivate the send button
					$("#send").attr({ disabled:false, value:"Shout it!" });
				}
			 });
			 document.getElementById("message").value = "";
		}
		else alert("Please fill all fields!");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
});



	function updateShoutbox2(){

		var shoutsNr = $("#shouts_nr");
		var shoutsNr = shoutsNr.attr("value");
		
		//send the post to shoutbox.asp
		$.ajax({
			type: "POST", url: "/home/shoutbox.asp", data: "action=check",
			complete: function(data){
				if (data.responseText > shoutsNr) {
					updateShoutbox3();
					document.getElementById("shouts_nr").value = data.responseText;
				}
			}
		});
		
	}

	setInterval("updateShoutbox2()", 30000);

	function updateShoutbox3(){
		var inputMessage = $("#message");
		var messageList = $(".shoutboxcontent > ul");
		
		//send the post to shoutbox.asp
		$.ajax({
			type: "POST", url: "/home/shoutbox.asp", data: "action=update",
			complete: function(data){
				//loading.fadeOut();
				messageList.html(data.responseText);
				//messageList.fadeIn(1);
			}
		});
		
	}

	