/**
 * @author absolute
 */
lockSubmitButton = function() {
	$('#write_comment_form input[type=submit]').attr('disabled', true);
};

unlockSubmitButton = function() {
	  $('#write_comment_form input[type=submit]').removeAttr('disabled');
};
  
$('#write_comment_form').ajaxForm({
	dataType: 'json',
	clearForm: true,
	target: '#form_response',
	beforeSubmit: function(arr, $form, options) {
		var retval = true;
		$('#comments_message').html('Submitting...');
		lockSubmitButton();
		$.each(arr, function(key, item) {
			var matches = item['name'].match(/comment\[([^\]]+)\]/i);
			if (matches) {
				switch(matches[1]) {
					case 'visitor_name':
					case 'visitor_email':	
					case 'content':
					case 'captcha':
						if (item['value'] == '') {
							$('#comments_message').html(matches[1] +' must not be empty');
							retval = false;
						}
						break;
				}
				if (retval) {
					switch(matches[1]) {
						case 'visitor_name':
	    					break;
						case 'visitor_email':	
	    					if (item['value'].length < 5) {
								$('#comments_message').html('Content should conatin at least 5 characters');
	        				}
	    					break;
						case 'content':
	    					if (item['value'].length < 5) {
								$('#comments_message').html('Content should not be shorter than 5 characters');
								retval = false;
	        				} else if (item['value'].length > 300) {
								$('#comments_message').html('Content should not be longer than 300 characters');
								retval = false;
	        				}
	    					break;
						case 'captcha':
							break;
					}
				}
			}
		});
		if (retval == false)
		{
			unlockSubmitButton();
		}
		return retval;
},
complete: function(request, status, message) {
	unlockSubmitButton();
	switch (status) {
		case 'parsererror':
			$('#comments_message').html('Form validation error. Please check your entries before submission.');
			break;
		case 'timeout':
			$('#comments_message').html('Form submission timed out.');
			break; 	 					
	}
},
success:    function(response, status, xhr, $form) {
	commentGetPage(1);
	if (response && response['status']) {
		switch(response['status']) {
			case 'COMMENT_CREATE_SUCCESSFUL':
				$('#comments_message').html('Thanks for your comment!');
				break;
			case 'FAILED':
				$('#comments_message').html('Unable to post comment. The server responded:<br/>'+response['error']);
				break;
		}
	}
},
});