$(function () {
	$.addValidation('input:text, textarea', '{0} is required', function (field) {
		return /\S/.test(field.value);
	});
});

$.fn.showCommentLink = function (article, webCommentsService) {
	
	var target = this;
	
	function alertError (request, status, error) {
		if (request.responseText && request.responseText.length > 0)
			alert(request.responseText);
		else if (status && status.length > 0)
			alert(status);
		else
			alert(error);
	}
	
	$.ajax({
		url: webCommentsService + '?article=' + article + '&action=getCommentLink',
		type: 'GET',
		dataType: 'text',
		cache: false,
		success: function (data) {
			$(target).append('<div id="comments" class="comments"/>').find('div:last').append(data).find('a').click(function () {
				$(this).remove();
				
				$.ajax({
					url: webCommentsService + '?article=' + article + '&action=getCommentList',
					type: 'GET',
					dataType: 'text',
					cache: false,
					error: function (request, status, error) {
						alertError(request, status, error);
					},
					success: function (data) {
						$('#comments').append(data).find('form').find('[name="commentPostRecaptchaPublicKey"]').each(function () {
							window.location.hash = '#comments';
							Recaptcha.create(this.value, null, {theme: 'custom'});
						}).end().submit(function () {
							var form = this;
							var name = form.commentPostName.value;
							var content = form.commentPostContent.value;
							var recaptchaChallenge = null;
							var recaptchaResponse = null;
							if (form.commentPostRecaptchaPublicKey) {
								recaptchaChallenge = Recaptcha.get_challenge();
								recaptchaResponse = Recaptcha.get_response();
							}
							
							if ($(form, target).validate({invalidClass: 'invalid', alertErrors: true, focus: true}).length == 0) {
								$(':submit', form).attr('disabled', 'disabled');
								var data = {name: name, content: content};
								if (form.commentPostRecaptchaPublicKey) {
									data.recaptchaChallenge = recaptchaChallenge;
									data.recaptchaResponse = recaptchaResponse;
								}
								$.ajax({
									url: webCommentsService + '?article=' + article + '&action=postComment',
									type: 'POST',
									data: data,
									dataType: 'text',
									cache: false,
									beforeSend: function () {
										$('#recaptcha_image', form).children().remove();
									},
									error: function (request, status, error) {
										alertError(request, status, error);
									},
									success: function (data) {
										$(form).parents('.commentSection').find('ul').append(data);
										$(':text, textarea', form).val('');
									},
									complete: function () {
										$(':submit', form).removeAttr('disabled');
										if (form.commentPostRecaptchaPublicKey)
											Recaptcha.reload();
									}
								});
							}
						});
					}
				});
			});
		}
	});
};