function getComments() {
	 $.ajax({
	   type: "POST",
	   url: "meTV/includes/getComments.php",
	   data: "allow=access1",
	   success: function(response){
		 $(".commentTable").empty().html(response)
	   }
	 });
}

function enableSubmit() {
	$("#submitbutton").removeAttr("disabled");
}

function timerKill() {
	$("td.counter").fadeOut("slow");
}

function pageRefresh() {
	var auto_refresh = setInterval(
	function ()
	{
	$('.commentTable').load('meTV/includes/getComments.php?allow=access1').fadeIn("slow");
	}, 2500);
}

$(function() {
	$('#submitbutton').click(function(e) {
		if($("#commentfield").val() == "") {
			alert("what's yo comment?");
			$("#commentfield").focus();
			exit;
		}
		$(this).attr("disabled", "disabled");
		setInterval("enableSubmit()", 8000);
		var name="";
		var comment = "";
		var dataString = "";
		var name = $("#namefield").val();
		if($("#namefield").val() == "") {
			var name = "Anonymous";
		}
		var comment = $("#commentfield").val();
		var dataString = "name=" + name + "&comment=" + comment;
		$.ajax({
			type: "POST",
			url: "meTV/includes/action.php",
			data: dataString,
			success: function(d) {
				$("td.counter").html("<p>You can post again in <span id=\"countdown\"></span> seconds.</p>");
				countdown('countdown', 8);
				setInterval("timerKill()", 7200)
				$("#commentfield").val("");
				$("#counter").val("120");
				$("td.counter").fadeIn();
				getComments();
			}
		});
	});
	return false;
});

$(document).ready(function() {
	getComments();
	pageRefresh();
});

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}


/** Countdown timer **/

function countdown ( field, secs ) {
	var d = 0, h = 0, m = 0, s = 0;
	if ( secs > 0) {
		d = Math.floor ( secs / 86400 );
		h = Math.floor ( ( secs - ( d * 86400 ) ) / 3600 );
		m = Math.floor ( ( secs - ( d * 86400 ) - ( h * 3600 ) ) / 60 );
		s = secs - ( d * 86400 ) - ( h * 3600 ) - ( m * 60 );
		if ( h < 10 ) { h = '0' + h; }
		if ( m < 10 ) { m = '0' + m; }
		if ( s < 10 ) { s = s; }
		//alert ( d + "T " + h + ":" + m + ":" + s);
		$(document).ready(function() {
			var output = "";
			if ( d > 0 ) { output += d + " days "; }
			output += s
			$("#" + field).html( output );
		});
		secs--;
	}
	else
	{
		//$(document).ready(function() {
		//	$("#" + field).html( "0" );
		//});
	}
	window.setTimeout(function () {
   		countdown ( field, secs );
	}, 1000)
	
}