dojo.provide("parus.gridSettingsDialog");

dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.data.ItemFileWriteStore");

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

dojo.require("dijit.form.NumberSpinner");
dojo.require("dijit._editor._Plugin");
dojo.require("dijit._editor.plugins.AlwaysShowToolbar");
dojo.require("dijit._editor.plugins.FontChoice");
dojo.require("dijit._editor.plugins.TextColor");

dojo.require("dojox.grid.cells.dijit");

dojo.require("parus.parus8");
dojo.require("parus.dialog");
dojo.require("parus.UpDown")
dojo.require("parus.customIconsPalette");
dojo.require("parus.gridFormatConditionDialog");
dojo.require("parus.richEditDialog");

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

  sourceGrid: null,

  sourceMenu: null,

  sourceCatalogTree: null,

  additions: null,

  userProcsUnitCode: null,

  userReportsUnitCode: null,

  userAppsUnitCode: null,

  onShow: function() {

    this._colorConditions = [];

    if (this.sourceGrid) {

      if (this.sourceGrid.abonentFieldsNeeded) {
        var structure = this.columnsGrid.structure;
        structure[0].cells[0][1].width = "300px";
        structure[0].cells[0][4].hidden = false;
        this.columnsGrid.setStructure(structure);

        var structure = this.actionsGrid.structure;
        structure[0].cells[0][0].width = "268px";
        structure[0].cells[0][3].hidden = false;
        this.actionsGrid.setStructure(structure);

        var structure = this.userAppsGrid.structure;
        structure[0].cells[0][0].width = "430px";
        structure[0].cells[0][2].hidden = false;
        this.userAppsGrid.setStructure(structure);

        var structure = this.userProcsGrid.structure;
        structure[0].cells[0][0].width = "430px";
        structure[0].cells[0][2].hidden = false;
        this.userProcsGrid.setStructure(structure);

        var structure = this.userReportsGrid.structure;
        structure[0].cells[0][0].width = "430px";
        structure[0].cells[0][2].hidden = false;
        this.userReportsGrid.setStructure(structure);

      }

      this.columnsGrid.setStore(this.columnsStore());

      if (this.sourceGrid.colorConditions) dojo.forEach(this.sourceGrid.colorConditions, dojo.hitch(this, function(condition) {

        var title;

        this.columnsGrid.store.fetch({
          onItem: dojo.hitch(this, function(item) {
            if (condition.field == this.columnsGrid.store.getValue(item, "id")) title = this.columnsGrid.store.getValue(item, "name");
          })
        });

        if (title) this._colorConditions.push({
          id: this._colorConditions.length,
          field: condition.field,
          fieldTitle: title,
          color: condition.color,
          applyToRow: condition.applyToRow,
          mask: condition.mask,
          fromValue: condition.fromValue,
          toValue: condition.toValue,
          title: this.formatConditionTitle(condition.mask, condition.fromValue, condition.toValue)
        });
      }));

      this.colorConditionsGrid.setStore(this.colorConditionsStore());
      this.colorConditionsGridSelected();

      if (!this.sourceGrid.pluginMgr || !this.sourceGrid.pluginMgr.getPlugin("status")) {

        var structure = this.columnsGrid.structure;
        structure[0].cells[0][5].hidden = true;
        structure[0].cells[0][5].width = 0;
        this.columnsGrid.setStructure(structure);

        this.tabContainer.removeChild(this.pluginsSettingsPane);
        this.pluginsSettingsPane.destroyRecursive();
        this.showFilterBarCheckBox = null;
        this.hideCatalogTree = null;
        this.hideCatalogTreeRow = null;
        this.additionsTable = null;

      }
      else {
        if (this.sourceCatalogTree) {
          this.hideCatalogTreeRow.style.display = "";
          this.hideCatalogTree.attr("checked", !parus.gridSettingsDialog.getCatalogTreeVisible(this.sourceCatalogTree));
        }

        if (this.additions) if (this.additions.length) {
          dojo.forEach(this.additions, dojo.hitch(this, function(addition) {
            var Row = this.additionsTable.insertRow(-1);
            var Cell = Row.insertCell(-1);
            var Node = Cell.appendChild(document.createElement("input"));
            Cell.appendChild(document.createElement("b")).
            appendChild(document.createTextNode("\n" + addition.title));
            dojo.mixin(addition, {
              _widget: new dijit.form.CheckBox({
                checked: addition.widget ? (addition.widget.domNode.style.display == "none") : (addition.get())
              }, Node)
            });


          }));

        }

        if (this.sourceGrid.pluginMgr.getPlugin("columnsFilter")) {
          this.showFilterBarRow.style.display = "";
          this.showFilterBarCheckBox.attr("checked", this.sourceGrid.getFilterBarVisible());
        }
        else {
          this.showFilterBarCheckBox.destroyRecursive();
          this.showFilterBarCheckBox = null;
        }

      }

      this.colorConditionsGridPopupMenu.bindDomNode(this.colorConditionsGrid.viewsNode);
    }
    else {
      this.tabContainer.removeChild(this.columnsSettingsPane);

      this.columnsSettingsPane.destroyRecursive();
      this.columnsSettingsPane = null;
      this.columnsGrid = null;

      var hasAdditions = false;
      if (this.additions) if (this.additions.length) {
        dojo.forEach(this.additions, dojo.hitch(this, function(addition) {
          hasAdditions = true;
          var Row = this.additionsTable.insertRow(-1);
          var Cell = Row.insertCell(-1);
          var Node = Cell.appendChild(document.createElement("input"));
          Cell.appendChild(document.createElement("b")).
          appendChild(document.createTextNode("\n" + addition.title));
          dojo.mixin(addition, {
            _widget: new dijit.form.CheckBox({
              checked: addition.widget ? (addition.widget.domNode.style.display == "none") : (addition.get())
            }, Node)
          });
        }));
      }
      if (!hasAdditions) {
        this.tabContainer.removeChild(this.pluginsSettingsPane);
        this.pluginsSettingsPane.destroyRecursive();
      }

      this.tabContainer.removeChild(this.colorConditionsPane);
      this.colorConditionsPane.destroyRecursive();
      this.colorConditionsPane = null;
      this.colorConditionsGrid = null;
    };

    if (this.sourceMenu) {

      this.actionsGrid.views.views[0].onAfterRow = dojo.hitch(this, this.actionsGridAfterRow);

      this.actionsGrid.setStore(this.actionsStore());

      var hasUserApps = false;

      if (this.userAppsUnitCode) {

        var store = this.userObjectsStore("userApps", this.userAppsUnitCode);

        if (store._jsonData.items.length) {
          this.userAppsGrid.setStore(store);
          hasUserApps = true;
        }
      };

      if (!hasUserApps) {

        this.tabContainer.removeChild(this.userAppsPane);
        this.userAppsGrid = null;
        this.userAppsPane.destroyRecursive();
        this.userAppsPane = null;
      };


      var hasUserProcs = false;

      if (this.userProcsUnitCode) {

        var store = this.userObjectsStore("userProcs", this.userProcsUnitCode);

        if (store._jsonData.items.length) {
          this.userProcsGrid.setStore(store);
          hasUserProcs = true;
        }
      };

      if (!hasUserProcs) {

        this.tabContainer.removeChild(this.userProcsPane);
        this.userProcsGrid = null;
        this.userProcsPane.destroyRecursive();
        this.userProcsPane = null;
      };



      var hasUserReports = false;

      if (this.userReportsUnitCode) {

        var store = this.userObjectsStore("userReports", this.userReportsUnitCode);

        if (store._jsonData.items.length) {
          this.userReportsGrid.setStore(store);
          hasUserReports = true;
        }

      };

      if (!hasUserReports) {
        this.tabContainer.removeChild(this.userReportsPane);
        this.userReportsGrid = null;
        this.userReportsPane.destroyRecursive();
        this.userReportsPane = null;
      };

    }
    else {
      this.tabContainer.removeChild(this.actionsSettingsPane);
      this.actionsGrid = null;
      this.actionsSettingsPane.destroyRecursive();
      this.actionsSettingsPane = null;

      this.tabContainer.removeChild(this.userAppsPane);
      this.userAppsGrid = null;
      this.userAppsPane.destroyRecursive();
      this.userAppsPane = null;

      this.tabContainer.removeChild(this.userProcsPane);
      this.userProcsGrid = null;
      this.userProcsPane.destroyRecursive();
      this.userProcsPane = null;

      this.tabContainer.removeChild(this.userReportsPane);
      this.userReportsGrid = null;
      this.userReportsPane.destroyRecursive();
      this.userReportsPane = null;



    };

    if ((dojo.indexOf(parus.balance.availableUnits, "Users") != -1)) this.spreadButton.domNode.style.display = "";

  },

  columnsStore: function() {

    var columnItems = [];
    var i = 0;

    dojo.forEach(this.sourceGrid.views.views[0].structure.cells[0], dojo.hitch(this, function(column) {
      if (column.field) columnItems.push({
        id: column.field,
        name: column.name,
        width: column.hidden ? 0 : parus.parus8.styleSize(column.unitWidth || column.width),
        nowrap: ((" " + (column.cellClasses || "") + " ").indexOf(" unwrappable ") >= 0),
        inabonent: (dojo.indexOf((this.sourceGrid.abonentFields || "").split(";"), column.field) != -1),
        aggregate: column.aggregate || 0,
        position: ++i
      });
    }));


    return store = new parus.gridSettingsDialogColumnGridStore({
      data: {
        identifier: "id",
        label: "name",
        items: columnItems
      }
    });
  },

  _moveUp: function(position) {

    if (position <= 0) return;

    this.columnsGrid.store.moveUp(position);

    id1 = this.columnsGrid.store.getIdentity(this.columnsGrid.store._arrayOfAllItems[position]);
    id2 = this.columnsGrid.store.getIdentity(this.columnsGrid.store._arrayOfAllItems[position - 1]);

    this.columnsGrid._by_idty[id1].item = this.columnsGrid.store._arrayOfAllItems[position];
    this.columnsGrid._by_idty[id2].item = this.columnsGrid.store._arrayOfAllItems[position - 1];

    this.columnsGrid._by_idx[position].item = this.columnsGrid.store._arrayOfAllItems[position];
    this.columnsGrid._by_idx[position - 1].item = this.columnsGrid.store._arrayOfAllItems[position - 1];

  },

  actionsStore: function() {

    var items = [];

    var id = 0;

    var checkMenu = function(menu, level) {
      dojo.forEach(menu.getChildren(), function(menuItem) {

        if (menuItem.declaredClass != "dijit.MenuSeparator") {
          if ((dojo.trim(menuItem.label) != "Настройки...") && !menuItem.userProcRN && !menuItem.userReportRN && !menuItem.userAppRN) {
            items.push({
              name: "<div class=\"dojoxGridExpando " + (menuItem.popup ? "dojoxGridExpandoOpened" : "dojoxGridNoChildren") + "\" style=\"margin-left: " + (level * 18) + "px;\">" + (menuItem.popup ? "<div class=\"dojoxGridExpandoNode\">" : "") + "<div class=\"dojoxGridExpandoNodeInner\">" + (menuItem.popup ? "-" : "+") + "</div>" + (menuItem.popup ? "</div>" : "") + "</div>" + menuItem.label,
              hash: parus.parus8.hash(menuItem.label),
              level: level,
              id: id++,
              enabled: (menuItem.domNode.style.display != "none"),
              icon: menuItem.customIcon ? (menuItem.customIcon + "Big") : "",
              defaultIcon: menuItem.defaultIcon,
              inabonent: menuItem.inAbonent
            });

            if (menuItem.popup) checkMenu(menuItem.popup, level + 1);
          }

        }
      });
    };

    checkMenu(this.sourceMenu, 0);

    return new parus.gridSettingsDialogStore({
      data: {
        identifier: "id",
        label: "name",
        items: items
      }
    });

  },

  userObjectsStore: function(queryid, unitCode) {

    var items = [];

    var id = 0;

    var _userObjectRNs = [];

    var checkMenu = function(menu) {
      dojo.forEach(menu.getChildren(), function(menuItem) {

        if (menuItem.userAppRN) _userObjectRNs.push(menuItem.userAppRN);

        if (menuItem.userProcRN) _userObjectRNs.push(menuItem.userProcRN);

        if (menuItem.userReportRN) _userObjectRNs.push(menuItem.userReportRN);

        if (menuItem.popup) checkMenu(menuItem.popup);
      });
    };

    var sm = this.sourceMenu;
    checkMenu(sm);

    dojo.forEach(parus.parus8.rowNodes(parus.database.query(queryid, {
      UNITCODE: unitCode
    })), function(node) {

      items.push({
        name: parus.parus8.nodeField(node, "NAME"),
        hash: parus.parus8.nodeField(node, "RN"),
        level: 1,
        id: id++,
        inmenu: dojo.indexOf(_userObjectRNs, parus.parus8.nodeField(node, "RN")) >= 0,
        inabonent: ((dojo.indexOf(sm.inAbonentUserApps || [], parus.parus8.nodeField(node, "RN")) >= 0) || (dojo.indexOf(sm.inAbonentUserProcs || [], parus.parus8.nodeField(node, "RN")) >= 0) || (dojo.indexOf(sm.inAbonentUserReports || [], parus.parus8.nodeField(node, "RN")) >= 0))
      });

    });

    return new parus.gridSettingsDialogStore({
      data: {
        identifier: "id",
        label: "name",
        items: items
      }
    });

  },

  madeSettings: function() {

    var gridSettings = []
    var abonentFields = [];

    if (this.columnsGrid) {

      this.columnsGrid.store.fetch({
        onItem: dojo.hitch(this, function(item) {
          var obj = {
            id: this.columnsGrid.store.getValue(item, "id"),
            name: this.columnsGrid.store.getValue(item, "name"),
            width: this.columnsGrid.store.getValue(item, "width"),
            nowrap: this.columnsGrid.store.getValue(item, "nowrap"),
            aggregate: this.columnsGrid.store.getValue(item, "aggregate")
          };
          gridSettings.push(obj);
          if (this.columnsGrid.store.getValue(item, "inabonent")) abonentFields.push(this.columnsGrid.store.getValue(item, "id"));
        })
      });
    };

    var actionSettings = [];

    var userAppsActions = [];
    var userProcsActions = [];
    var userReportsActions = [];

    var userAppsActionsInAbonent = [];
    var userProcsActionsInAbonent = [];
    var userReportsActionsInAbonent = [];


    if (this.actionsGrid) {

      this.actionsGrid.store.fetch({
        onItem: dojo.hitch(this, function(item) {
          var obj = {
            hash: this.actionsGrid.store.getValue(item, "hash"),
            enabled: this.actionsGrid.store.getValue(item, "enabled"),
            customIcon: (this.actionsGrid.store.getValue(item, "icon") || "").replace(/Big$/, ""),
            inabonent: this.actionsGrid.store.getValue(item, "inabonent")
          };
          actionSettings.push(obj);
        })
      });

      if (this.userAppsGrid) this.userAppsGrid.store.fetch({
        onItem: dojo.hitch(this, function(item) {
          if (this.userAppsGrid.store.getValue(item, "inmenu")) userAppsActions.push(this.userAppsGrid.store.getValue(item, "hash"));
          if (this.userAppsGrid.store.getValue(item, "inabonent")) userAppsActionsInAbonent.push(this.userAppsGrid.store.getValue(item, "hash"));
        })
      });

      if (this.userProcsGrid) this.userProcsGrid.store.fetch({
        onItem: dojo.hitch(this, function(item) {
          if (this.userProcsGrid.store.getValue(item, "inmenu")) userProcsActions.push(this.userProcsGrid.store.getValue(item, "hash"));
          if (this.userProcsGrid.store.getValue(item, "inabonent")) userProcsActionsInAbonent.push(this.userProcsGrid.store.getValue(item, "hash"));
        })
      });

      if (this.userReportsGrid) this.userReportsGrid.store.fetch({
        onItem: dojo.hitch(this, function(item) {
          if (this.userReportsGrid.store.getValue(item, "inmenu")) userReportsActions.push(this.userReportsGrid.store.getValue(item, "hash"));
          if (this.userReportsGrid.store.getValue(item, "inabonent")) userReportsActionsInAbonent.push(this.userReportsGrid.store.getValue(item, "hash"));
        })
      });

    };

    var colorConditions = [];

    dojo.forEach(this._colorConditions, function(condition) {
      colorConditions.push({
        applyToRow: condition.applyToRow,
        color: condition.color,
        field: condition.field,
        mask: condition.mask,
        fromValue: condition.fromValue,
        toValue: condition.toValue
      });
    });

    var additions = {};

    if (this.additions) dojo.forEach(this.additions, dojo.hitch(this, function(addition) {
      additions[addition.id] = addition._widget.checked;
    }));


    return {
      gridSettings: gridSettings,
      actionSettings: actionSettings,
      userAppsActions: (this.userAppsUnitCode /* && userAppsActions.length */ ) ? {
        actions: userAppsActions,
        inabonent: userAppsActionsInAbonent,
        unitcode: this.userAppsUnitCode
      } : null,
      userProcsActions: (this.userProcsUnitCode /* && userProcsActions.length */ ) ? {
        actions: userProcsActions,
        inabonent: userProcsActionsInAbonent,
        unitcode: this.userProcsUnitCode
      } : null,
      userReportsActions: (this.userReportsUnitCode /* && userReportsActions.length */ ) ? {
        actions: userReportsActions,
        inabonent: userReportsActionsInAbonent,
        unitcode: this.userReportsUnitCode
      } : null,
      colorConditions: colorConditions,
      showFilterBar: this.showFilterBarCheckBox ? this.showFilterBarCheckBox.checked : false,
      hideCatalogTree: this.hideCatalogTree ? this.hideCatalogTree.checked : false,
      additions: additions,
      filterValues: this.sourceGrid ? ((this.showFilterBarCheckBox && this.showFilterBarCheckBox.checked) ? this.sourceGrid.pluginMgr.getPlugin("columnsFilter").values : {}) : {},
      sortInfo: this.sourceGrid ? (this.sourceGrid.sortInfo || null) : null,
      abonentFields: abonentFields
    };



  },


  _checkActionsByLevel: function(index, startlevel) {

    var item = this.actionsGrid.getItem(index);
    if (!item) return;
    var level = this.actionsGrid.store.getValue(item, "level");
    if (level > startlevel) {
      this.actionsGrid.store.setValue(item, "enabled", false);
      this.actionsGrid.updateRow(index);
      this._checkActionsByLevel(index + 1, startlevel);
    }
  },

  toggleAction: function(index) {
    var item = this.actionsGrid.getItem(index);
    var value = this.actionsGrid.store.getValue(item, "enabled");
    this.actionsGrid.store.setValue(item, "enabled", value ? false : true);
    this.actionsGrid.updateRow(index);
    if (value) this._checkActionsByLevel(index + 1, this.actionsGrid.store.getValue(item, "level"));
  },

  toggleWrap: function(index) {
    var item = this.columnsGrid.getItem(index);
    var value = this.columnsGrid.store.getValue(item, "nowrap");
    this.columnsGrid.store.setValue(item, "nowrap", value ? false : true);
    this.columnsGrid.updateRow(index);
  },

  toggleAbonent: function(index) {
    var item = this.columnsGrid.getItem(index);
    var value = this.columnsGrid.store.getValue(item, "inabonent");
    this.columnsGrid.store.setValue(item, "inabonent", value ? false : true);
    this.columnsGrid.updateRow(index);
  },

  toggleActionAbonent: function(index) {
    var item = this.actionsGrid.getItem(index);
    var value = this.actionsGrid.store.getValue(item, "inabonent");
    this.actionsGrid.store.setValue(item, "inabonent", value ? false : true);
    this.actionsGrid.updateRow(index);
  },

  toggleUserAppAbonent: function(index) {
    var item = this.userAppsGrid.getItem(index);
    var value = this.userAppsGrid.store.getValue(item, "inabonent");
    this.userAppsGrid.store.setValue(item, "inabonent", value ? false : true);
    this.userAppsGrid.updateRow(index);
  },

  toggleUserProcAbonent: function(index) {
    var item = this.userProcsGrid.getItem(index);
    var value = this.userProcsGrid.store.getValue(item, "inabonent");
    this.userProcsGrid.store.setValue(item, "inabonent", value ? false : true);
    this.userProcsGrid.updateRow(index);
  },

  toggleUserReportAbonent: function(index) {
    var item = this.userReportsGrid.getItem(index);
    var value = this.userReportsGrid.store.getValue(item, "inabonent");
    this.userReportsGrid.store.setValue(item, "inabonent", value ? false : true);
    this.userReportsGrid.updateRow(index);
  },

  toggleUserApp: function(index) {
    var item = this.userAppsGrid.getItem(index);
    var value = this.userAppsGrid.store.getValue(item, "inmenu");
    this.userAppsGrid.store.setValue(item, "inmenu", value ? false : true);
    this.userAppsGrid.updateRow(index);
  },

  toggleUserProc: function(index) {
    var item = this.userProcsGrid.getItem(index);
    var value = this.userProcsGrid.store.getValue(item, "inmenu");
    this.userProcsGrid.store.setValue(item, "inmenu", value ? false : true);
    this.userProcsGrid.updateRow(index);
  },

  toggleUserReport: function(index) {
    var item = this.userReportsGrid.getItem(index);
    var value = this.userReportsGrid.store.getValue(item, "inmenu");
    this.userReportsGrid.store.setValue(item, "inmenu", value ? false : true);
    this.userReportsGrid.updateRow(index);
  },

  editTitle: function(index) {

    var item = this.columnsGrid.getItem(index);
    var value = this.columnsGrid.store.getValue(item, "name");
    var dialog = (new parus.richEditDialog({
      title: "Заголовок",

      onShow: function() {
        dialog.editor.attr("value", value);
      },
      onApply: dojo.hitch(this, function() {
        value = dialog.editor.attr("value");
        this.columnsGrid.store.setValue(item, "name", value);
        this.columnsGrid.updateRow(index);
        return true;
      })
    }));
    dialog.show();
  },

  fieldsAsOptions: function() {
    var options = [];

    this.columnsGrid.store.fetch({
      onItem: dojo.hitch(this, function(item) {
        options.push({
          value: this.columnsGrid.store.getValue(item, "id"),
          label: this.columnsGrid.store.getValue(item, "name")
        });
      })
    });
    return options;
  },


  _colorConditions: null,

  colorConditionsStore: function() {
    return new parus.gridSettingsDialogStore({
      data: {
        identifier: "id",
        items: dojo.clone(this._colorConditions)
      }
    });
  },

  formatConditionTitle: function(mask, fromValue, toValue) {
    if (mask) return mask
    else if (fromValue && !toValue) return "C " + fromValue
    else if (!fromValue && toValue) return "По " + toValue
    else return "C " + fromValue + " по " + toValue;
  },

  addColorCondition: function() {

    var dialog = new parus.gridFormatConditionDialog({
      fieldsAsOptions: this.fieldsAsOptions(),

      onShow: function() {
        if (dialog.fieldSelect.options.length) dialog.fieldSelect.attr("value", dialog.fieldSelect.options[0].value);
        if (dialog.colorSelect.options.length) dialog.colorSelect.attr("value", dialog.colorSelect.options[0].value);
      },

      onApply: dojo.hitch(this, function() {
        var title = dialog.fieldSelect.value;

        this.columnsGrid.store.fetch({
          onItem: dojo.hitch(this, function(item) {
            if (dialog.fieldSelect.value == this.columnsGrid.store.getValue(item, "id")) title = this.columnsGrid.store.getValue(item, "name");
          })
        });

        this._colorConditions.push({
          id: this._colorConditions.length,
          field: dialog.fieldSelect.value,
          fieldTitle: title,
          color: dialog.colorSelect.value,
          applyToRow: dialog.applyToRowCheckBox.checked ? 1 : 0,
          mask: dialog.maskEdit.value,
          fromValue: dialog.fromEdit.value,
          toValue: dialog.toEdit.value,
          title: this.formatConditionTitle(dialog.maskEdit.value, dialog.fromEdit.value, dialog.toEdit.value)
        });

        this.colorConditionsGrid.setStore(this.colorConditionsStore());

        this.colorConditionsGrid.selection.select(this._colorConditions.length - 1);
        this.colorConditionsGrid.updateRow(this._colorConditions.length - 1);
        this.colorConditionsGrid.views.setScrollTop(
        this.colorConditionsGrid.scroller.findScrollTop(this.colorConditionsGrid.getItem(this._colorConditions.length - 1)));
        return true;
      })

    });
    dialog.show();

  },

  editColorCondition: function() {

    var store = this.colorConditionsGrid.store;
    var index = this.colorConditionsGrid.selection.getSelectedIndex();
    var item = this.colorConditionsGrid.getItem(index);

    var dialog = new parus.gridFormatConditionDialog({
      fieldsAsOptions: this.fieldsAsOptions(),

      onShow: dojo.hitch(this, function() {

        dialog.fieldSelect.attr("value", store.getValue(item, "field"));
        dialog.colorSelect.attr("value", store.getValue(item, "color").toString());
        dialog.applyToRowCheckBox.attr("checked", store.getValue(item, "applyToRow") == "1");
        dialog.maskEdit.attr("value", store.getValue(item, "mask"));
        dialog.fromEdit.attr("value", store.getValue(item, "fromValue"));
        dialog.toEdit.attr("value", store.getValue(item, "toValue"));

        if (!dialog.maskEdit.value) dialog.useRange.attr("checked", true);
        dialog.modeChanged();

      }),

      onApply: dojo.hitch(this, function() {
        var title = dialog.fieldSelect.value;

        this.columnsGrid.store.fetch({
          onItem: dojo.hitch(this, function(item) {
            if (dialog.fieldSelect.value == this.columnsGrid.store.getValue(item, "id")) title = this.columnsGrid.store.getValue(item, "name");
          })
        });

        dojo.mixin(this._colorConditions[index], {
          field: dialog.fieldSelect.value,
          fieldTitle: title,
          color: dialog.colorSelect.value,
          applyToRow: dialog.applyToRowCheckBox.checked ? 1 : 0,
          mask: dialog.maskEdit.value,
          fromValue: dialog.fromEdit.value,
          toValue: dialog.toEdit.value,
          title: this.formatConditionTitle(dialog.maskEdit.value, dialog.fromEdit.value, dialog.toEdit.value)
        });

        this.colorConditionsGrid.setStore(this.colorConditionsStore());

        this.colorConditionsGrid.selection.select(index);
        this.colorConditionsGrid.updateRow(index);
        this.colorConditionsGrid.scrollToRow(index);

        return true;
      })

    });
    dialog.show();

  },

  deleteColorCondition: function() {


    var store = this.colorConditionsGrid.store;
    var index = this.colorConditionsGrid.selection.getSelectedIndex();

    (new parus.confirmationDialog({

      message: "Удалить запись (записи)?",

      onApply: dojo.hitch(this, function() {

        this._colorConditions.splice(index, 1);

        dojo.forEach(this._colorConditions, function(condition, idx) {
          condition.id = idx;
        });

        this.colorConditionsGrid.setStore(this.colorConditionsStore());
        this.colorConditionsGrid.selection.select(index - 1);
        this.colorConditionsGrid.updateRow(index - 1);
        this.colorConditionsGrid.scrollToRow(index - 1);

        return true;
      })
    })).show();

  },

  colorConditionsGridSelected: function() {

    var recordExists = (this.colorConditionsGrid.selection.getSelectedIndex() >= 0) && (this.colorConditionsGrid.selection.getSelectedIndex() < this._colorConditions.length);

    var checkMenu = function(menu) {
      dojo.forEach(menu.getChildren(), function(menuItem) {
        if (menuItem.itemAction) menuItem.attr("disabled", !recordExists);
        if (menuItem.popup) checkMenu(menuItem.popup);
      });
    };

    checkMenu(this.colorConditionsGridPopupMenu);

  },

  clearUserData: function() {


    (new parus.confirmationDialog({

      message: "Вы действительно хотите удалить все сделанные вами настройки всех разделов системы?",

      onApply: dojo.hitch(this, function() {
        parus.userdata.cleanUp();
        parus.parus8.notificationMessage("Настройки удалены. Необходимо перевойти в приложение, чтобы новые настройки вступили в силу.");
        this.close();
        return true;
      })
    })).show();

  },

  spread: function() {

    var dictionaryInfo = parus.dictionaries["Users"];


    dojo.mixin(dictionaryInfo, {
      code: "Users",
      multiselect: true,
      dictionary: dictionaryInfo,
      onApply: dojo.hitch(this, function(dialog) {
        var rns = dialog.getValue().split(";");
        if (!rns.length || !rns[0]) return false;

        (new parus.confirmationDialog({
          message: "Количество выбранных пользователей: " + rns.length + ". Настройки этих пользователей будут заменены на ваши. Продолжить?",
          onApply: dojo.hitch(this, function() {
            parus.userdata.spread(rns);
            parus.parus8.notificationMessage("Настройки выбранных пользователей заменены на ваши.");
            this.close();
            return true;
          })
        })).show();

        return true;
      })
    });

    setTimeout(function() {
      new parus.dictionaryDialog(dictionaryInfo).show();
    }, 100);

  },


  actionsGridAfterRow: function(inRowIndex, cells, inRowNode) {
    if (inRowIndex == -1) {

      var parsed = dojo.parser.parse({
        rootNode: inRowNode,
        template: true
      });

      dojo.forEach(parsed, dojo.hitch(this, function(widget) {
        dojo.mixin(widget, {
          dialogObject: this,
          dialog: this.dialog
        });
        var attachPoint = widget.dojoAttachPoint;
        if (attachPoint && (dojo.indexOf(this._attachPoints, attachPoint) != -1)) this[attachPoint] = widget;
      }));

    }
  },

  clearAllIcons: function() {
    (new parus.confirmationDialog({

      message: "Убрать все иконки действий?",

      onApply: dojo.hitch(this, function() {
        this.actionsGrid.store.fetch({

          onItem: dojo.hitch(this, function(item) {
            this.actionsGrid.store.setValue(item, "icon", null);
          }),
          onComplete: dojo.hitch(this, function() {
            setTimeout(dojo.hitch(this, function() {
              parus.balance.refreshGrid(this.actionsGrid);
            }), 30);

          })
        });

        return true;
      })
    })).show();
  },

  defaultAllIcons: function() {

    (new parus.confirmationDialog({

      message: "Вернуть все иконки действий в значения по умолчанию?",

      onApply: dojo.hitch(this, function() {
        this.actionsGrid.store.fetch({

          onItem: dojo.hitch(this, function(item) {
            this.actionsGrid.store.setValue(item, "icon", this.actionsGrid.store.getValue(item, "defaultIcon") ? this.actionsGrid.store.getValue(item, "defaultIcon") + "Big" : "");
          }),
          onComplete: dojo.hitch(this, function() {
            setTimeout(dojo.hitch(this, function() {
              parus.balance.refreshGrid(this.actionsGrid);
            }), 30);

          })
        });

        return true;
      })
    })).show();

  }

});

dojo.mixin(parus.gridSettingsDialog, {

  formatEditableText: function(data, rowIndex, column) {
    return ("<div><div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.editTitle(" + rowIndex + ")\" align=\"right\" style=\"position: relative; top: 0px; right: 0px; z-index: 99;\">" + "<span class=\"dijit dijitReset dijitInline dijitButton\">" + "<span class=\"dijitReset dijitInline dijitButtonNode\">" + "<span class=\"dijitReset dijitStretch dijitButtonContents\" style=\"user-select: none;\">" + "<span class=\"dijitReset dijitInline dijitIcon dijitNoIcon\"></span>" + "<span class=\"dijitReset dijitToggleButtonIconChar\">●</span>" + "<span class=\"dijitReset dijitInline\">" + "<div class=\"dictButton\" style=\"width:10px;height:10px;overflow:hidden\">&nbsp;</div>" + "</span>" + "</span>" + "</span>" + "</span>" + "</div>" + "<div style=\"position: relative; top: -16; left:0\">" + data + "</div></div>");
  },

  formatCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleAction(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatWrapCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleWrap(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatAbonentCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleAbonent(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatAbonentActionCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleActionAbonent(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatAbonentUserAppCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleUserAppAbonent(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatAbonentUserProcCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleUserProcAbonent(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatAbonentUserReportCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleUserReportAbonent(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatUserAppsCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleUserApp(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatUserProcsCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleUserProc(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatUserReportsCheck: function(data, rowIndex, column) {
    return "<div onclick=\"dijit.getEnclosingWidget(this).grid.dialogObject.toggleUserReport(" + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  formatIcon: function(data, rowIndex, column) {
    return data ?

    ("<div class=\"gridSettingsIcon\"><img class=\"" + data + "\" src=\"" + (dojo.config.blankGif || dojo.moduleUrl("dojo", "resources/blank.gif")).toString() + "\"/></div>")

    : "(Нет)";
  },

  formatAggregate: function(data, rowIndex, column) {
    return (data ? ((["(Нет)", "Количество", "Сумма", "Минимум", "Максимум", "Среднее"])[data]) : "(Нет)");
  },

  mergeColorConditions: function(grid, settings) {
    if (!grid) return;
    if (!settings) return;

    grid.colorConditions = settings;
    grid.setQuery(grid.query);
  },


  _mergeStructures: function(str, settings) {

    var strItems = str[0].cells ? str[0].cells[0] : str;

    var res = [];

    dojo.forEach(settings, function(setting) {
      for (var i = 0; i < strItems.length; i++) {
        if (strItems[i]) if (strItems[i].field == setting.id) {

          if (setting.width) {
            strItems[i].width = setting.width + "px";
            strItems[i].hidden = false
          }
          else strItems[i].hidden = true;

          var classes = (strItems[i].cellClasses || "").split(" ");
          var idx = dojo.indexOf(classes, "unwrappable");

          if (setting.nowrap) {
            if (idx == -1) classes.push("unwrappable")
          }
          else {
            if (idx != -1) delete classes[idx];
          };

          strItems[i].cellClasses = classes.join(" ");

          strItems[i].name = setting.name || strItems[i].name;

          strItems[i].aggregate = setting.aggregate;

          res.push(dojo.clone(strItems[i]));
          strItems[i] = null;
        }
      }
    });

    for (var i = 0; i < strItems.length; i++) {
      if (strItems[i]) res.push(dojo.clone(strItems[i]));
    }

    if (str[0] && str[0].cells) str[0].cells[0] = res;
    else str = res;

    return str;


  },

  mergeGridSettings: function(grid, settings) {
    if (!grid) return;
    if (!settings) return;

    grid.setStructure(this._mergeStructures(dojo.clone(grid.structure), settings));
    grid.abonentFields = settings.abonentFields || "";

  },

  mergeMenuSettings: function(menu, settings, userProcsSettings, userReportsSettings, userAppsSettings) {
    if (!menu) return;

    if (!settings) return;

    var settingsItem = null;
    var settingsItemMenu = null;

    var checkMenu = function(menu, forceHidden) {

      var hasEnabled = false;

      dojo.forEach(menu.getChildren(), function(menuItem, idx) {

        var enabled = true;
        var customIcon = "";
        var inAbonent = menuItem.inAbonent;

        if (menuItem.declaredClass != "dijit.MenuSeparator") {

          if (dojo.trim(menuItem.label) == "Настройки...") {
            settingsItemMenu = menu;
            settingsItem = menuItem;
          };

          for (var i = 0; i < settings.length; i++)
          if (parus.parus8.hash(menuItem.label) == settings[i].hash) {
            enabled = settings[i].enabled;
            customIcon = settings[i].customIcon || customIcon;
            inAbonent = settings[i].inabonent;
          }

          if (forceHidden) enabled = false;

          if (menuItem.popup) {
            if (enabled) enabled = checkMenu(menuItem.popup);
            if (!enabled) checkMenu(menuItem.popup, true)
          }

          if (menuItem.userProcRN || menuItem.userReportRN || menuItem.userAppRN) {
            enabled = false;
            menuItem.destroyRecursive();
            menuItem = null;
          }
        }

        if (menuItem) {
          if (enabled) {
            menuItem.hiddenBySettings = false;
            menuItem.domNode.style.display = "";
            hasEnabled = true;
          }
          else {

            menuItem.hiddenBySettings = true;
            menuItem.domNode.style.display = "none";
          }

          menuItem.customIcon = customIcon;
          menuItem.inAbonent = inAbonent;

        }
      });

      return hasEnabled;
    };

    checkMenu(menu);


    if ((userProcsSettings || userReportsSettings || userAppsSettings) && settingsItemMenu && settingsItem) {

      if (userAppsSettings) {

        menu.inAbonentUserApps = userAppsSettings.inabonent || [];

        settingsItemMenu.addChild(new dijit.MenuSeparator(), settingsItem.getIndexInParent());

        dojo.forEach(parus.parus8.rowNodes(parus.database.query("userApps", {
          UNITCODE: userAppsSettings.unitcode
        })), function(node) {

          var rn = parus.parus8.nodeField(node, "RN");
          if (dojo.indexOf(userAppsSettings.actions, rn) == -1) return;

          var item = new dijit.MenuItem({
            label: parus.parus8.nodeField(node, "NAME"),
            itemAction: false,
            userAppRN: rn,
            onClick: function() {
              parus.balance.userApplication(item.userObjectsGrid, userAppsSettings.unitcode, rn, parus.parus8.nodeField(node, "GROUP_RECORDS") != "0");
            }
          });
          settingsItemMenu.addChild(item, settingsItem.getIndexInParent());

        });

      }

      if (userProcsSettings) {

        menu.inAbonentUserProcs = userProcsSettings.inabonent || [];

        settingsItemMenu.addChild(new dijit.MenuSeparator(), settingsItem.getIndexInParent());

        dojo.forEach(parus.parus8.rowNodes(parus.database.query("userProcs", {
          UNITCODE: userProcsSettings.unitcode
        })), function(node) {

          var rn = parus.parus8.nodeField(node, "RN");
          if (dojo.indexOf(userProcsSettings.actions, rn) == -1) return;

          var item = new dijit.MenuItem({
            label: parus.parus8.nodeField(node, "NAME"),
            itemAction: false,
            userProcRN: rn,
            onClick: function() {

              parus.balance.userProcedure(item.userObjectsGrid, userProcsSettings.unitcode, rn, parus.parus8.nodeField(node, "CONFIRM_TEXT"), parus.parus8.nodeField(node, "PERRECORD") != "0", parus.parus8.nodeField(node, "PERSELECTION") != "0");
            }
          });
          settingsItemMenu.addChild(item, settingsItem.getIndexInParent());

        });
      };

      if (userReportsSettings) {

        menu.inAbonentUserReports = userReportsSettings.inabonent || [];

        settingsItemMenu.addChild(new dijit.MenuSeparator(), settingsItem.getIndexInParent());

        dojo.forEach(parus.parus8.rowNodes(parus.database.query("userReports", {
          UNITCODE: userReportsSettings.unitcode
        })), function(node) {

          var rn = parus.parus8.nodeField(node, "RN");
          if (dojo.indexOf(userReportsSettings.actions, rn) == -1) return;

          var item = new dijit.MenuItem({
            label: parus.parus8.nodeField(node, "NAME"),
            itemAction: false,
            userReportRN: rn,
            onClick: function() {
              parus.balance.userReport(item.userObjectsGrid, userReportsSettings.unitcode, rn, parus.parus8.nodeField(node, "NAME"), parus.parus8.nodeField(node, "REPORT_TYPE"));
            }
          });
          settingsItemMenu.addChild(item, settingsItem.getIndexInParent());

        });


      };



      settingsItemMenu.addChild(new dijit.MenuSeparator(), settingsItem.getIndexInParent());

    };

    parus.parus8.checkMenuSeparators(menu);

    if (menu.actionsButtonPane) parus.balance._createActionsButton(menu, menu.actionsButtonPane, true);
  },

  mergeFilterBar: function(grid, showFilterBar, filterValues, sortInfo) {
    if (!grid) return;
    if (!grid.pluginMgr) return;
    if (!grid.pluginMgr.getPlugin("columnsFilter")) return;

    if (sortInfo) grid.sortInfo = sortInfo;

    if (showFilterBar) {
      if (filterValues) dojo.mixin(grid.pluginMgr.getPlugin("columnsFilter").values, filterValues);
      grid.showFilterBar();
    }
    else grid.hideFilterBar();
  },

  mergeAdditions: function(additions, settings) {
    if (!additions) return;
    if (!settings) return;

    dojo.forEach(additions, function(addition) {
      if (addition.widget) {
        var container = dijit.byNode(addition.widget.domNode.parentNode);

        if (settings.hasOwnProperty(addition.id)) {
          addition.widget.domNode.style.display = settings[addition.id] ? "none" : "";
        }

        if (addition.widget._splitterWidget) addition.widget._splitterWidget.domNode.style.display = addition.widget.domNode.style.display;

        dojo.query("*[widgetId]", addition.widget.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.declaredClass == "dijit.Tree") {
            if (addition.widget.domNode.style.display) {
              widget.listMode = true;
              widget.hiddenMode = true;
            }
            else {
              widget.listMode = false;
              widget.hiddenMode = false;
              parus.catalogActions.refreshCatalogTree(widget);
            }
          }
        });


        if (container) setTimeout(function() {
          container.layout();
        }, 100);

      }
      else if (addition.set) {
        addition.set(settings[addition.id])
      }
    });
  },

  getCatalogTreeVisible: function(catalogTree) {
    return catalogTree ? !catalogTree.hiddenMode : false;
  },

  setCatalogTreeVisible: function(catalogTree, value) {

    if (!catalogTree) return;
    catalogTree.hiddenMode = !value;
    var node = catalogTree.domNode.parentNode.parentNode.parentNode;
    var widget = dijit.byNode(node);
    if (!widget) {
      node = catalogTree.domNode.parentNode;
      widget = dijit.byNode(node);
    };

    var container = dijit.byNode(node.parentNode);
    if (value) {
      widget.domNode.style.display = "";
      catalogTree.listMode = false;
      parus.catalogActions.refreshCatalogTree(catalogTree);
    }
    else {
      widget.domNode.style.display = "none";
      catalogTree.listMode = true;
    }

    if (widget._splitterWidget) widget._splitterWidget.domNode.style.display = value ? "" : "none";

    setTimeout(function() {
      container.layout();
    }, 100);
  }


});

dojo.declare("parus.gridSettingsDialogStore", [dojo.data.ItemFileWriteStore], {

  _containsValue: function(item, attribute, value, regexp) {
    if (dojo.isFunction(value) && !regexp) return true;
    else return this.inherited(arguments);
  }

});


dojo.declare("parus.gridSettingsDialogColumnGridStore", [parus.gridSettingsDialogStore], {

  moveUp: function(position) {

    if (position <= 0) return;

    var current = {
      name: dojo.clone(this._arrayOfAllItems[position].name),
      width: dojo.clone(this._arrayOfAllItems[position].width),
      nowrap: dojo.clone(this._arrayOfAllItems[position].nowrap),
      inabonent: dojo.clone(this._arrayOfAllItems[position].inabonent),
      aggregate: dojo.clone(this._arrayOfAllItems[position].aggregate),
      id: dojo.clone(this._arrayOfAllItems[position].id)
    };

    var previous = {
      name: dojo.clone(this._arrayOfAllItems[position - 1].name),
      width: dojo.clone(this._arrayOfAllItems[position - 1].width),
      nowrap: dojo.clone(this._arrayOfAllItems[position - 1].nowrap),
      inabonent: dojo.clone(this._arrayOfAllItems[position - 1].inabonent),
      aggregate: dojo.clone(this._arrayOfAllItems[position - 1].aggregate),
      id: dojo.clone(this._arrayOfAllItems[position - 1].id)
    };

    this._arrayOfAllItems[position].name = previous.name;
    this._arrayOfAllItems[position].width = previous.width;
    this._arrayOfAllItems[position].nowrap = previous.nowrap;
    this._arrayOfAllItems[position].inabonent = previous.inabonent;
    this._arrayOfAllItems[position].aggregate = previous.aggregate;
    this._arrayOfAllItems[position].id = previous.id;

    this._arrayOfAllItems[position - 1].name = current.name;
    this._arrayOfAllItems[position - 1].width = current.width;
    this._arrayOfAllItems[position - 1].nowrap = current.nowrap;
    this._arrayOfAllItems[position - 1].inabonent = current.inabonent;
    this._arrayOfAllItems[position - 1].aggregate = current.aggregate;
    this._arrayOfAllItems[position - 1].id = current.id;

    this._itemsByIdentity[this.getIdentity(this._arrayOfAllItems[position])] = this._arrayOfAllItems[position];
    this._itemsByIdentity[this.getIdentity(this._arrayOfAllItems[position - 1])] = this._arrayOfAllItems[position - 1];
  }

});


dojo.declare("parus.gridSettingsDialogPositionEditor", [parus.UpDown], {

  cell: null,

  onChange: function(delta) {
    dijit.typematic.stop();
    if (delta == 1) {
      this.value -= 2;
      this.moveUp(this.value, -1);
    }
    else {
      this.value += 2;
      this.moveUp(this.value - 1, 0);
    }

  },

  moveUp: function(inRowIndex, delta) {
    if (inRowIndex <= 0) return;
    if (inRowIndex >= this.cell.grid.store._arrayOfAllItems.length) return;

    this.cell.grid.dialogObject._moveUp(inRowIndex);

    setTimeout(dojo.hitch(this, function() {
      this.cell.apply(inRowIndex);
      this.cell.grid.selection.select(inRowIndex + delta);
      this.cell.grid.focus.focusGrid();
      this.cell.grid.focus.setFocusIndex(inRowIndex + delta, this.cell.index);
      this.cell.grid.edit.setEditCell(this.cell, inRowIndex + delta);
      this.cell.grid.updateRow(inRowIndex);
      this.cell.grid.updateRow(inRowIndex - 1);
    }), 50);

  }

});

dojo.declare("dojox.grid.cells.gridSettingsDialogPositionEditor", [dojox.grid.cells._Widget], {

  getWidgetProps: function(inDatum) {
    var props = this.inherited(arguments);
    dojo.mixin(props, {
      cell: this
    });
    return props;
  },

  getValue: function(inRowIndex) {
    return inRowIndex + 1;
  },

  setValue: function(inRowIndex, inValue) {
    this.widget.value = inRowIndex + 1;
    dijit.focus(this.widget.domNode);
  },

  _finish: function(inRowIndex) {
    this.inherited(arguments);
    this.grid.updateRow(inRowIndex);
  }

});

dojo.mixin(dojox.grid.cells.gridSettingsDialogPositionEditor, {

  markupFactory: dojox.grid.cells._Widget.markupFactory,

  formatPosition: function(data, rowIndex, column) {
    return rowIndex + 1;
  }

});

dojo.declare("dojox.grid.cells.gridSettingsDialogIconEditor", [dojox.grid.cells._Widget], {

  getWidgetProps: function(inDatum) {
    var props = this.inherited(arguments);
    dojo.mixin(props, {
      cell: this
    });
    return props;
  },

  getValue: function(inRowIndex) {
    return this.widget.value;
  }

});

dojo.declare("parus.gridSettingsDialogIconEditor", [parus.customIconsEditor], {

  cell: null,

  definition: dojo.cache("parus", "theme/customIconsBig.js")

});

dojo.mixin(dojox.grid.cells.gridSettingsDialogIconEditor, {

  markupFactory: dojox.grid.cells._Widget.markupFactory

});

dojo.declare("parus.gridSettingsDialogAggregateEditor", [dojox.grid.cells._Widget], {
  widgetProps: {
    options: [{
      label: "(Нет)",
      value: 0
    },
    {
      label: "Количество",
      value: 1
    },
    {
      label: "Сумма",
      value: 2
    },
    {
      label: "Минимум",
      value: 3
    },
    {
      label: "Максимум",
      value: 4
    },
    {
      label: "Среднее",
      value: 5
    }]
  }
});

dojo.mixin(parus.gridSettingsDialogAggregateEditor, {

  markupFactory: dojox.grid.cells._Widget.markupFactory

});