dojo.provide("parus.statusModelNoteDialog");

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.SimpleTextarea");

dojo.require("parus.parus8");
dojo.require("parus.dialog");
dojo.require("parus.gridData");

dojo.declare("parus.statusModelNoteDialog", [parus.Dialog], {

  RN: null,
  event: null,
  eventTypeRN: null,
  noteHeader: null,
  note: null,

  postCreate: function() {
    this.inherited(arguments);

    this.loadNoteHeaderStore(this.eventTypeRN);
    if (this.RN) this.noteHeaderEdit.attr("disabled", true);
    if (this.note) this.noteEdit.attr("value", this.note);
  },

  loadNoteHeaderStore: function(eventTypeRN) {
    this.noteHeaderEdit.attr("store", new parus.gridData({
      asJson: true,
      persistent: true,
      identityFieldName: "CODE",
      _data: parus.database.queryObject("BalanceStatusModelTypeNotes", {
        EVENT: eventTypeRN
      }),
      onComplete: dojo.hitch(this, function(store, items, keywordArgs) {
        if (!keywordArgs.query || !keywordArgs.query.justLoaded) return;

        if (items.length > 0) {
          this.noteHeaderEdit.attr("value", this.noteHeader != null ? this.noteHeader : store.getValue(items[0], "CODE"));
        }
      })
    }));

    this.noteHeaderEdit.store.query({
      justLoaded: true
    });
  },

  noteEditChange: function() {
    if (!this.noteEdit.attr("value")) {
      dijit.showTooltip("Это обязательное значение", this.noteEdit.domNode);
      dojo.addClass(this.noteEdit.domNode, "dijitError")
    }
    else {
      dojo.removeClass(this.noteEdit.domNode, "dijitError");
      dijit.hideTooltip(this.noteEdit.domNode);
    }
  },

  validate: function() {
    var valid = this.dialog.validate();
    if (!this.noteEdit.attr("value")) dojo.addClass(this.noteEdit.domNode, "dijitError")
    else dojo.removeClass(this.noteEdit.domNode, "dijitError");

    if (valid && !this.noteEdit.attr("value")) {
      dijit.showTooltip("Это обязательное значение", this.noteEdit.domNode);
      return false;
    };
    dijit.hideTooltip(this.noteEdit.domNode);
    return valid;
  },

  close: function() {
    dijit.hideTooltip(this.noteHeaderEdit.domNode);
    dijit.hideTooltip(this.noteEdit.domNode);
    return this.inherited(arguments);
  },

  _onShow: function() {
    this.validate();
    this.inherited(arguments);
  },

  insertNote: function() {
    var response = parus.database.execute("insertStatusModelNote", {
      EVENT: this.event,
      NOTE_HEADER: this.noteHeaderEdit.attr("value"),
      NOTE: this.noteEdit.attr("value")
    });

    if (response) return parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN");
  },

  updateNote: function() {
    var response = parus.database.execute("updateStatusModelNote", {
      RN: this.RN,
      NOTE: this.noteEdit.attr("value")
    });

    return !!response;
  }

});