var JetztTextView = Class.create(JetztAjax,{

  initialize: function(textid, timestampOfOldestDisplayedComment) {
    this.textid = textid;
    this.timestampOfOldestDisplayedComment = timestampOfOldestDisplayedComment;
  },
  getMoreComments: function() {
	  this.post('/ajax/Kommentare/getCommentsBulk',
			    {textid: this.textid, olderThan: this.timestampOfOldestDisplayedComment},
		        function(transport) {
				      comments = transport.responseText.evalJSON();
				      if (comments.length < 10) {
                          $('moreCommentsButton').replace('<p class="noMoreComments">Keine weiteren Kommentare.</p>');
				      }
					  comments.each(function(comment){
						  $('commentlist').insert(this.generateCommentHtmlElement(comment));
						  this.timestampOfOldestDisplayedComment = comment.created;
					  }.bind(this));
			    }.bind(this));
  },
  addComment: function() {
	  var commenttext = $F('comment');
	  if(commenttext.blank() || commenttext == 'Bitte loggen Sie sich ein, um einen Kommentar zu verfassen.') {
		  alert('Bitte geben Sie einen Kommentar ein.');
		  return;
	  }
	  Form.reset('commentform');
	  this.post('/ajax/Kommentare/addComment',
			  {textid: this.textid, comment: commenttext},
			  this.reloadComments.bind(this),
			  this.processCommentAjaxError.bind(this, commenttext));
	  
  },
  reloadComments: function() {
	  this.post('/ajax/Kommentare/getCommentsBulk',
			  {textid: this.textid},
			  function(transport) {
	      comments = transport.responseText.evalJSON();
		  $('commentlist').update('');
		  comments.each(function(comment){
			  $('commentlist').insert(this.generateCommentHtmlElement(comment));
			  this.timestampOfOldestDisplayedComment = comment.created;
		  }.bind(this));
    }.bind(this));
  },
  delComment: function(commentId) {
	  $('comment_'+commentId).hide();
	  this.post('/ajax/Kommentare/delComment',
			  {commentId: commentId});
  },
  generateCommentHtmlElement: function(comment) {
	  var html = '<li><div class="commentmetadata">'+comment.meta+'</div>';
	  html += '<div class="commentdata"><span class="commentautor pc">'+comment.author+'</span>';
	  html += comment.text;
	  html += '</div><div style="display: block; clear: both;"></div></li>';
	  return html;
  },
  processCommentAjaxError: function(originalComment, request) {
	  // restore comment
	  $('comment').value = originalComment;
	  var message = request.responseText;
      if (message === "") {
          message = "Es ist ein Fehler aufgetreten.";
      }
      alert(message);
  }
});
