var RecaptchaOptions = {
	theme: 'custom',
	custom_theme_widget: 'reCaptcha'
}

var start = new Date();

jQuery(function(){
	checkUserStatus();
});

var commentCounter = function() {
	if (jQuery(this).val().length > maxCommentLength) {
		jQuery(this).val(jQuery(this).val().substring(0,maxCommentLength));
	} else {
		jQuery('#tx_tccomments_counter').html((maxCommentLength - jQuery(this).val().length));
	}
};

var checkUserStatus = function() {
	jQuery.getJSON(statusURI,{'timestamp':start.getTime()},function(data){
		switch(data.status) {
			case 'OK':
				var options = {
					success: responseHandler,
					dataType: 'json'
				};

				jQuery('.tccomments .commentForm form textarea').keydown(commentCounter).keyup(commentCounter);

				jQuery('.tccomments .commentForm form').submit(function(){
					jQuery(this).ajaxSubmit(options);
					
					return false;
				});

				jQuery('.tccomments .commentForm form').show();
				//Added by Jan-Erik	
				if(typeof(tccommentsonChange) == "function") {
					tccommentsonChange.call();				
				}
				break;
			case 'LOGON':
				jQuery('.tccomments .commentForm .notLoggedOn').show();
				break;
			case 'INCOMPLETE':
				jQuery('.tccomments .commentForm .incomplete').show();
				break;
		}
	});
};


var responseHandler = function(responseText,statusText) {
	if (responseText.errors == undefined) {
		jQuery(this).clearForm();
		jQuery('.tccomments .errorMsg').remove();
		jQuery('#tx_tccomments_counter').html(maxCommentLength);
		updateComments(1);
	} else {
		if (jQuery('.tccomments .commentForm .errorMsg').length < 1) {
			jQuery('.tccomments .commentForm').prepend(jQuery('<div></div>')
				.addClass('errorMsg')
				.append(jQuery('<h4></h4>')
					.html(lblErrHeading)
				)
				.append(jQuery('<ul></ul>'))
			);
		}
		
		
		if (jQuery('.tccomments .commentForm .errorMsg ul').children().length > 0) {
			jQuery('.tccomments .commentForm .errorMsg ul').empty();
		}
		
		var text = '';
		jQuery.each(responseText.errors,function(){
			switch(this.toString()) {
				case 'name':
					text = lblErrName;
					break;
				case 'email':
					text = lblErrEmail
					break;
				case 'captcha':
					text = lblErrCaptcha;
					break;
				case 'comment':
					text = lblErrComment;
					break;
				case 'post':
					text = lblErrPost;
					break;
			}
			
			

			jQuery('.tccomments .commentForm .errorMsg ul').append(jQuery('<li></li>')
					.html(text)
			);
			//Added by Jan-Erik	
			if(typeof(tccommentsonChange) == "function") {
				tccommentsonChange.call();				
			}
		});
	}
	
	Recaptcha.reload();
	
};