function FormComment() {
  this.formHandler = $('#message');
  this.acriveInserted = 'comment0';
  this.activeParent = $("input[name='reply_to']", this.formHandler).val();
  this.objectId = $("input[name='object']", this.formHandler).val();
  this.lock = false;
  this.move = function(elementId) {
    $('#fsUploadProgresscommenttext', this.formHandler).empty();
    if (this.acriveInserted == elementId) {
      if (this.acriveInserted == 'comment0') {
        $('textarea', this.formHandler).val('');
      }
      return false;
    }
    this.acriveInserted = elementId;
    var parent_id = elementId.match(/comment(.*)/)[1];
    this.activeParent = parseInt(parent_id);
    $("input[name='reply_to']", this.formHandler).val(this.activeParent);
    $('textarea', this.formHandler).val('');
    this.formHandler.remove().insertAfter('#'+elementId);
  }
  this.send = function() {
    var realSubmit = false;
    sendArray = this.getData();
    if (!sendArray.comment) {
      alert('Необходимо ввести текст комментария');
      return false;
    }
    if($("input[name='openid_identifier']", this.formHandler).length) {
        if ($("input[name='openid_identifier']", this.formHandler).val() == '') {
            alert('Для того, чтобы написать комментарий, введите свой OpenID');
            return false;
        }
        realSubmit = true;
    } else {
    sendArray.ajax = 1;
        $.ajax({
          type: "POST",
          url: "/comments/add/format/html",
          dataType: "html",
          data: sendArray,
          beforeSend: commentForm.setLock,
          success: commentForm.sendOk,
          complete: commentForm.setLock
        });
    }
    return realSubmit;
  }
  this.getData = function() {
    var fields = $(':input', this.formHandler).serializeArray();
    var sendArray = ({});
    $.each(fields, function(i, field){
        sendArray[field.name] = field.value;
    });
    return sendArray;
  }
  
  //@todo change on preview
  this.sendOk = function(data) {
    commentForm.insertPreview(data);
    commentForm.move('comment0');
  }
  
  this.prewiew = function() {
    var dataSend = commentForm.getData();
    var levelComent = '';
    if (commentForm.acriveInserted != 'comment0') {
      levelComent = $('#'+commentForm.acriveInserted).attr('class');
      levelComent = levelComent.match(/otstup(.*)/);
      if (!levelComent || !levelComent[1]) {
          levelComent = 0;
      } else {
          levelComent = parseInt(levelComent[1]);
      }
      levelComent = ++levelComent;
    }
    dataSend.level = levelComent;
    $.ajax({
      type: "POST",
      url: "/comments/preview/format/html",
      dataType: "html",
      data: dataSend,
      success: commentForm.insertPreview,
      beforeSend: commentForm.setLock,
      complete: commentForm.setLock
    });
  }
  
  this.insertPreview = function(htmlString) {
    $('#commentpreview').remove();
    $('a[name="commentpreview"]').remove();
    if (commentForm.acriveInserted != 'comment0') {
      $('#'+commentForm.acriveInserted).after(htmlString);
    } else {
      $('#'+commentForm.acriveInserted).before(htmlString);
    }
  }
  
  this.setLock = function() {
    commentForm.lock = !commentForm.lock;
    $(":input", this.formHandler).each(function() {
      this.disabled = commentForm.lock ? 'disabled' : '';
    });
  }
}

function comment() {
  this.active = false;
  this.remove = function(commentId, objId) {
      if (!objId) {
          objId = commentForm.objectId;
      }
      $.ajax({
      type: "POST",
      url: "/comments/del/format/json/id",
      dataType: "json",
      data: ({'id': commentId, 'object':objId}),
      success: commentM.changeText(commentId, '<strong>Комментарий был удален.</strong>')
    });
  }
  this.changeText = function(id, text) {
      $('#comment' + id + ' div.text_com').html(text);
  }
  this.vote = function(commentId) {
    this.active = commentId;
    $.ajax({
      type: "POST",
      url: "/vote/comment/format/json",
      dataType: "json",
      data: ({'id': commentId, 'object':commentForm.objectId}),
      success: commentM.changeVote
    });
  }
  this.changeVote = function(data) {
    if (data.result) {
      $('#comment'+commentM.active+' span.c-rat').html('&nbsp;+'+data.raiting+'&nbsp;');
      $('#comment'+commentM.active+' div.com_r').remove();
    } else if(data.desc) {
      alert(data.desc);
    } else {
      alert('Произошла ошибка');        
    }
    commentM.active = false;
  }
}

var commentForm;
var commentM;
jQuery(document).ready(function($) {
  commentForm = new FormComment();
  commentM = new comment();
});