var i18n = {
	'fr' : {
		'your-comment' : "Votre commentaire"
	},
	'en' : {
		'' : "",
	}
	
};

function previewComment() {
	$('commentForm').request({
		parameters: {act:'preview'},
		onSuccess: function(result) {
			json = result.responseText.evalJSON();
			check = json.check.toArray();
			
			preview = '<p class="chapeau" id="comment"><img src="/media/images/comment.png" /> ' + json.msg.comment + '</p>';
			if(check.length > 0) {
				preview += '<div class="message">' + json.msg.error + '</div>';
				updateErrors(check);
			} else {
				preview += createComment(json.comment, json.msg);
				resetFields();
			}
			
			$('previewComment').innerHTML = preview;
		}
	});
}

function postComment() {
	$('cBis').value = $('fAuthor').value;
	
	$('commentForm').request({
		parameters: {act:'submit'},
		onSuccess: function(result) {
			json = result.responseText.evalJSON();
			check = json.check.toArray();
			
			if(check.length > 0) {
				msg = '<p class="chapeau" id="comment"><img src="/media/images/comment.png" /> ' + json.msg.comment + '</p>';
				msg += '<div class="message">' + json.msg.error + '</div>';
				$('previewComment').innerHTML = msg;
				updateErrors(check);
			} else {
				
				if($('commentList')) {
					// there are already comments
					content = createComment(json.comment, json.msg);
					$('nbComment').innerHTML = parseInt($('nbComment').innerHTML) + 1;
				} else {
					// first comment
					content = '<p class="chapeau" id="comment"><img src="/media/images/comment.png" /> ' + json.msg.oneComment + '</p>';
					content += createComment(json.comment, json.msg);
				}
				
				$('previewComment').innerHTML = content;
				$('commentForm').reset();
				resetFields();
			}
		}
	
	});
	
	return false;
}

function createComment(comment, msg) {
	
	str = '<div id="comment-preview" style="margin: 20px 0 20px 0;">';
	str += '<p class="meta">' + msg.on + ' <a href="' + location.href + '#comment-preview">' + msg.date + '</a>, ';
	str += msg.by + ' <cite><a href="' + comment.authorUrl + '">' + comment.author + '</a></cite></p>';
	str += '<div class="content">' + comment.content + '</div>';
	str += '</div>';
	
	return str;
}

function resetFields() {
	// reset previous field
	['fAuthor', 'fUrl', 'fContent'].each(function(s) {
		$(s).parentNode.className = '';
	});
}

function updateErrors(fields) {
	resetFields();
	
	// set new class if the field contains an error
	for(var i=0;  i < fields.length; i++) {
		fieldName = 'f'+fields[i].charAt(0).toUpperCase()+fields[i].substr(1);
		$(fieldName).parentNode.className = 'erroneousField';
	}
	
}

