/* ====== validateRequired ====== */

/**
 * Validate and highlight required fields
 * @param path Selector of the control to validate.
 */

blog.validateRequired = function(path) {
	isValid = true;
	jQuery(path).each(function() {
		if (jQuery(this).val() == '') {
			jQuery(this).addClass('invalid');
			isValid = false;
		}
		else {
			jQuery(this).removeClass('invalid');
		}
	});
	return isValid;
};


/* ====== postComment ====== */

blog.postComment = function() {
	
	var commentData = {
		ajax: 'postComment',
		comment: jQuery('#comment').val(),
		comment_post_ID: jQuery('#comment_post_ID').val()
	};
	if (blog.userID > 0) {
		commentData.userID = blog.userID;
	}
	else {
		commentData.author = jQuery('#author').val();
		commentData.email = jQuery('#email').val();
		commentData.url = jQuery('#url').val();
	}

	jQuery.ajax({

		complete: function() {
			jQuery('#submit')
				.removeAttr('disabled')
				.val('Submit Comment »');
		},

		data: commentData,
		dataType: 'json',
		
		error: function(xhr, status, ex) {			
			var out = /<body[^>]*>([\s\S]*)<\/body>/i.exec(xhr.responseText);
			if (out) {
				out = out[1];
				blog.showAlert(out, 'error');
			}
			else {
				blog.showAlert(xhr.responseText, 'error');					
			}
		},

		success: function(result, status) {
			var isAlt = (jQuery('#comments').children().length % 2) == 0;
			jQuery('#comments').append(result.rendered_content);
			var lc = jQuery('#comments :last-child');
			if (isAlt && !lc.hasClass('mine')) {
				lc.addClass('alt');
			}
			else {
				lc.removeClass('alt');
			}
			switch (result.comment_approved) {
				case 0:
				case '0':
				case 'spam':
					blog.showAlert(
						'Your comment has been held for moderation and may not appear immediately.',
						'warn');
					break;
				default:
					blog.showAlert('Thank you for your comment.', false);
					break;
			}
			jQuery('#comment').val('');
		},
		
		type: 'POST',
		url: blog.baseUrl + '/wp-comments-post.php'
	});
};


/* ====== Events ====== */

jQuery(document).ready(function() {

	jQuery('#trackbacks li h4 .time').click(function() {
		jQuery(this).parent().parent().toggleClass('collapsed');
	});

	/* ====== Comment form submit ====== */

	jQuery('#commentform').submit(function() {

		if (!blog.validateRequired('#author,#email,#comment')) {
			blog.showAlert('Please fill in the required missing fields.');
			return false;
		}

		jQuery('#submit')
			.attr('disabled', 'disabled')
			.val('Submitting comment...');
		blog.postComment();
		return false;
	});
});