$(document).ready(function() {
	/*
	 * Messaging function for the comment system
	 *
	 * Types:
	 * 2 = Saved
	 * 1 = "Ajaxing"
	 * 0 = Error
	 */
	var commentMessage = function(msg, type) {
		$('#comment-message').show();

		if (type === 2) {
			$('#comment-message').removeClass('invalid');
			$('#comment-message').addClass('valid');
			$('#comment-message').html(msg);
		} else if (type === 1) {
			$('#comment-message').removeClass('invalid');
			$('#comment-message').removeClass('valid');
			$('#comment-message').html("<img src='images/ajax-load.gif' alt='' /><br />" + msg);
		} else {
			$('#comment-message').removeClass('valid');
			$('#comment-message').addClass('invalid');
			$('#comment-message').html(msg);
		}
	};

	$('#submit').click(function() {
		// Array that'll hold all error messages
		var errMsg = [];
		
		// Check if name is entered
		if ($('#form-name').val() === "") { errMsg.push('<p>No name entered.</p>'); }
		
		// Check if verification code is entered
		if ($('#form-verification').val() === "") { errMsg.push('<p>No verification code entered.</p>'); }
		
		// Check if any comments have been written
		if ($('#form-comment').val() === "") { errMsg.push('<p>No comment entered.</p>'); }

		// If there are any error messages, output them and return
		if (errMsg.length > 0) { commentMessage(errMsg.join(""), 0); return false; }
		
		// Start Ajax loading procedure
		commentMessage('<p>Saving Comment...</p>', 1);
		
		// Do Ajax call and try saving the new comment
		$.ajax({
			type: "POST",
			url: "inc-comments-process.php",
			data: "name=" + $('#form-name').val() +
				"&website=" + $('#form-website').val() +
				"&verification=" + $('#form-verification').val() +
				"&comment=" + $('#form-comment').val(),
			success: function(msg) {
				if (parseInt(msg, 10) === 0) { // Verification code failed
					commentMessage('<p>Verification code mismatch.</p>', 0);
					$('#captcha').attr('src', '/securimage/securimage_show.php?' + (new Date()).getTime());
				}
				else {
					setTimeout(function() {
						commentMessage('<p>Comment saved!</p>', 2);
						$('#comments-area').load('inc-comments.php?' + (new Date()).getTime());
						$("form")[0].reset();
					}, 500);
					
					setTimeout(function() {
						$('#comment-message').fadeOut('slow');
					}, 5000);
				}
			}
		});
	});
});
