var CommentForm = Class.create(PageForm, {
  initialize: function($super, formId, containerId) {
    $super();
    
    this.formId = formId;
    this.containerId = containerId;

    Event.observe($('showCommentFormButton'), 'click', this.showCommentForm.bind(this));

    Event.observe(this.formId, 'submit', this.saveComment.bind(this));

    $('commentsFormCommandButton').enable();
  },
  showCommentForm: function(event) {
    Event.stop(event);
    Effect.Appear(this.formId, {
      duration: 0.5,
      afterFinish: this.focusFirstElement.bind(this)
      });
    Effect.Fade('addCommentButtonContainer');
  },
  focusFirstElement: function() {
    $(this.formId).focusFirstElement();
  },
  saveComment: function(event) {
    Event.stop(event);

    this.clearErrors();
    $(this.containerId).update();
    this.validate();

    if (this.hasErrors()) {
      this.showErrors(this.containerId);
    }
    else {
      $(this.formId).disable();

      var params = {
        advantageId: $F('commentAdvantageId'),
        author: $F('commentAuthorName'),
        content: $F('commentContent'),
        command: 'addComment',
        key: $F('commentKey')
      };

      new Ajax.Request('modules/advantage/add_comment.php', {
        parameters: $H(params).toQueryString(),
        onSuccess: this.fetchCommentResponse.bind(this)
      });
    }
  },
  validate: function() {
    if ($F('commentContent').strip() == '') {
      this.addError('Sisesta kommentaarile sisu');
    }
  },
  fetchCommentResponse: function(transport) {
    var response = transport.responseJSON;

    if (!response) {
      return;
    }

    if (response.success) {
      Effect.Fade('commentsForm', {duration: 0.5, afterFinish: function() {
        window.location.reload();
      }});
    }
    else {
      this.addError(response.message);
      this.showErrors(this.containerId);
      $(this.formId).enable();
    }
  }
});

Event.observe(window, 'load', function() {
  if ($('commentsForm')) {
    new CommentForm('commentsForm', 'commentMessagesContainer');
  }
});

