
$(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");
		$('#submit-loader').fadeIn();
		$('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 == 1) {
				// handling contribution separatly from others modules
				if(msg.module ==  'contribute') {
					$('<p class="confirmed">' + msg.html + '<\/p>').hide().insertBefore('#add-comment-form input.submitbut').slideDown();
					$('#cbody').val('');
					$('#ctitle').val('');
					
				} else {
					/* 
					/	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('');
					$('#ctitle').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);
				}
				$('#submit-loader').fadeOut();
			}
			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');

	});
	
});