window.addEvent('domready', function() {
  $$('#apps li .notes.editable .btn').addEvent('click', function() {
    var app = this.getParent('li');
    var parentCell = this.getParent('td');
    var text = this.getPrevious('.text') || (new Element('div', { 'class': 'text' })).inject(parentCell, 'top');
    var textarea = new Element('textarea', { text: text.get('text') });
    var button = new Element('button', {
      type: 'button',
      text: 'сохранить комментарий',
      events: {
        click: function() {
          var notesText = textarea.get('value').trim();
          new Request({
            url: '/save-app-notes',
            data: {
              app_id: app.get('id').substr(3).toInt(),
              notes: notesText
            },
            useSpinner: true,
            spinnerTarget: app,
            onSuccess: function() {
              if (notesText) {
                text.set('text', notesText).removeClass('hidden');
                var lastEdit = parentCell.getElement('.last_edit strong');
                if (lastEdit) lastEdit.set('text', 'только что');
              } else {
                text.destroy();
                var lastEdit = this.getNext('.last_edit');
                if (lastEdit) lastEdit.destroy();
              }
              this.getNext('.btn').set('text', notesText ? 'редактировать комментарий' : '+ добавить комментарий').removeClass('hidden');
              textarea.destroy();
              this.destroy();
            }.bind(this)
          }).send();
        }
      }
    });
    
    text.addClass('hidden');
    this.addClass('hidden');
    textarea.inject(parentCell, 'top').focus();
    button.inject(textarea, 'after');
  });
  
  if ($('balance')) {
    var balance = $('balance').getElement('strong').get('text').replace(/([^0-9])/g,'').toInt();
    $$('#apps li .actions form').addEvent('submit', function() {
      var price = this.getElement('.app_price').get('text').replace(/([^0-9])/g,'').toInt();
      if (balance < price) {
        alert('У вас на балансе недостаточно денег для покупки этой заявки!');
        return false;
      }
    });
  }
});

