
$(document).ready(function(){

	/* This flag will prevent multiple comment submits: */
	var working = false;

	/* Listening for the submit event of the form: */
	$('#add-comment-form').submit(function(e){

 		e.preventDefault();
		if(working) return false;
		
		working = true;
		$('#add-comment-form:submit').attr("disabled","disabled");
		$('p.error').remove();
		
		/* Sending the form fields to submit.php: */
		var posturl = mainURL + 'comment/_ajax_submit.php';
		$.post(posturl, $(this).serialize(),function(msg){

			working = false;
			$('#add-comment-form:submit').removeAttr("disabled");
			
			if(msg.status){
				/* 
				/	If the insert was successful, add the comment
				/	below the last one on the page with a slideDown effect
				/*/
				$(msg.html).hide().insertBefore('#add-comment').slideDown();
				$('#cbody').val('');
				
				// we update the comment counter
				$('#cc').text( parseInt($('#cc').text()) +1);
				
				// for files
				var target = 'a[href*="'+ $('#file_id').val() +'"] > span.cc';
				$(target).text( parseInt($(target).text()) +1);
			}
			else {
				/*
				/	If there were errors, loop through the
				/	msg.errors object and display them on the page 
				/*/				
				$.each(msg.errors,function(k,v){
					$('#add-comment-form').before('<p class="error">'+v+'</p>');
				});
			}
		},'json');

	});
	
});