dojo.provide("parus.designer");

dojo.require("dojo.date.locale");

dojo.require("dijit.dijit");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.Menu");
dojo.require("dijit.Tree");
dojo.require("dijit.tree._dndSelector");
dojo.require("dijit.form.Textarea");
dojo.require("dijit.Toolbar");
dojo.require("dijit.ToolbarSeparator");


dojo.require("dojox.grid.DataGrid");
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.grid.enhanced._PluginManager");
dojo.require("dojox.grid.enhanced.plugins.IndirectSelection");
dojo.require("dojox.grid.enhanced.plugins.Selector");

dojo.require("parus.cache");
dojo.require("parus.balance");

dojo.require("parus.catalogTreeModel");
dojo.require("parus.gridData");
dojo.require("parus.catalogActions");
dojo.require("parus.userdata");

dojo.require("parus.confirmationDialog");
dojo.require("parus.treeDialog");
dojo.require("parus.gridSettingsDialog");
dojo.require("parus.gridStatus");
dojo.require("parus.gridColumnsFilter");

dojo.require("parus.customIconsPalette");

dojo.require("parus.excelFileFormatDialog");
dojo.require("parus.excelColorModeDialog");
dojo.require("parus.exportGridDialog");

dojo.require("parus.designerTemplatesDialog");

dojo.require("parus.designerReportDialog");
dojo.require("parus.designerReportEditionDialog");
dojo.require("parus.designerEditionSplitDialog");

dojo.require("parus.designerReportFormulaDialog");
dojo.require("parus.designerReportCheckListDialog");

dojo.require("parus.designerReportLinkDialog");
dojo.require("parus.designerReportIndexDialog");

dojo.require("parus.designerReportTablesDictionaryDialog");
dojo.require("parus.designerReportTableDialog");
dojo.require("parus.designerReportTableIndexDialog");

dojo.require("parus.designerReportSectionDialog");
dojo.require("parus.designerSectionDialog");

dojo.require("parus.designerIndexDialog");
dojo.require("parus.designerIndexFormulaDialog");

dojo.require("parus.designerIndexGroupDialog");
dojo.require("parus.designerIndexGroupPartDialog");

dojo.require("parus.editableDictionaryDialog");

dojo.require("parus.designerTemplatesCheckDialog");

if (!parus) parus = {};

if (!parus.balance) dojo.mixin(parus, {
  balance: {}
});

dojo.mixin(parus.balance, {

  _createFormsPane: function(node) {

    parus.balance.formsPage = new dijit.layout.ContentPane({
      style: "height:100%;width:100%;padding:0",
      title: parus.balance.formatPageTitle("Формы<br/>отчетов"),
      href: dojo.moduleUrl("parus", "designer.html").toString(),
      selected: true,
      region: "center",
      onShow: function() {
        if (dojo.isIE <= 8) {
          if (parus.balance._shownPages[page.id]) setTimeout(function() {
            parus.catalogActions.refreshCatalogTree(parus.balance.formsCatalogTree);
          }, 1000)
          else parus.balance.refreshGrid(parus.balance.formsMasterGrid);
          parus.balance._shownPages[page.id] = true;
        }
        else parus.balance.refreshGrid(parus.balance.formsMasterGrid);
      },
      onLoad: function() {

        if (parus.balance.applicationCode) {
          parus.balance._processMenu(parus.balance.formsMasterGridPopupMenu, function(menuItem) {
            if (menuItem.removeForApplications) if (dojo.indexOf(menuItem.removeForApplications.split(";"), parus.balance.applicationCode) >= 0) menuItem.destroyRecursive();
          });
          parus.balance._processMenu(parus.balance.formsDetailGridPopupMenu, function(menuItem) {
            if (menuItem.removeForApplications) if (dojo.indexOf(menuItem.removeForApplications.split(";"), parus.balance.applicationCode) >= 0) menuItem.destroyRecursive();
          });
        };

        var structure = [];

        dojo.forEach(parus.balance._docprops, function(docprop) {
          if (parus.parus8.nodeField(docprop, "SHOW_IN_GRID") == "1") {
            structure.push({
              colSpan: 1,
              propRN: parus.parus8.nodeField(docprop, "RN"),
              dataType: parus.parus8.nodeField(docprop, "DATATYPE"),
              dataSubType: parus.parus8.nodeField(docprop, "SUBTYPE"),
              field: "prop" + parus.parus8.nodeField(docprop, "RN"),
              name: parus.parus8.nodeField(docprop, "CODE"),
              formatter: parus.balance.formatDocPropValue,
              width: "121px",
              styles: "text-align:" + ((parus.parus8.nodeField(docprop, "DATATYPE") == 0) ? "left" : "right") + ";",
              sortField: (parus.parus8.nodeField(docprop, "DATATYPE") == 2) ? "F_DOCS_PROPS_GET_DATE_VALUE(" + parus.parus8.nodeField(docprop, "RN") + ",'BalanceReports', T.RN)" : ((parus.parus8.nodeField(docprop, "DATATYPE") == 1) ? "F_DOCS_PROPS_GET_NUM_VALUE(" + parus.parus8.nodeField(docprop, "RN") + ",'BalanceReports', T.RN)" : "F_DOCS_PROPS_GET_STR_VALUE(" + parus.parus8.nodeField(docprop, "RN") + ",'BalanceReports', T.RN)")
            })
          }
        });

        dojo.forEach(parus.balance._masterAttrDescriptors, function(descriptor) {

          structure.push({
            colSpan: 1,
            attrRN: parus.parus8.nodeField(descriptor, "RN"),
            dataType: parus.parus8.nodeField(descriptor, "DATATYPE"),
            dataSubType: 0,
            field: "attr" + parus.parus8.nodeField(descriptor, "RN"),
            name: parus.parus8.nodeField(descriptor, "NAME"),
            formatter: parus.balance.formatAttrValue,
            width: (parus.parus8.nodeField(descriptor, "ACTIVE") == "1") ? "121px" : "0px",
            hidden: (parus.parus8.nodeField(descriptor, "ACTIVE") != "1"),
            styles: "text-align:" + ((parus.parus8.nodeField(descriptor, "DATATYPE") == 0) ? "left" : "right") + ";",
            sortField: (parus.parus8.nodeField(descriptor, "PARAMCOUNT") == "2") ? (parus.parus8.nodeField(descriptor, "STOREDPROC") + "(T.COMPANY, T.RN)") : (parus.parus8.nodeField(descriptor, "STOREDPROC") + "(T.RN)")
          })

        });


        if (structure.length) {
          var str = dojo.clone(parus.balance.formsMasterGrid.structure);
          str[0].cells[0] = str[0].cells[0].concat(structure);
          parus.balance.formsMasterGrid.setStructure(str);
        }

        var structure = [];


        dojo.forEach(parus.balance._detailDocprops, function(docprop) {
          if (parus.parus8.nodeField(docprop, "SHOW_IN_GRID") == "1") {
            structure.push({
              colSpan: 1,
              propRN: parus.parus8.nodeField(docprop, "RN"),
              dataType: parus.parus8.nodeField(docprop, "DATATYPE"),
              dataSubType: parus.parus8.nodeField(docprop, "SUBTYPE"),
              field: "prop" + parus.parus8.nodeField(docprop, "RN"),
              name: parus.parus8.nodeField(docprop, "CODE"),
              formatter: parus.balance.formatDocPropValue,
              width: "121px",
              styles: "text-align:" + ((parus.parus8.nodeField(docprop, "DATATYPE") == 0) ? "left" : "right") + ";",
              sortField: (parus.parus8.nodeField(docprop, "DATATYPE") == 2) ? "F_DOCS_PROPS_GET_DATE_VALUE(" + parus.parus8.nodeField(docprop, "RN") + ",'BalanceSubReports', T.RN)" : ((parus.parus8.nodeField(docprop, "DATATYPE") == 1) ? "F_DOCS_PROPS_GET_NUM_VALUE(" + parus.parus8.nodeField(docprop, "RN") + ",'BalanceSubReports', T.RN)" : "F_DOCS_PROPS_GET_STR_VALUE(" + parus.parus8.nodeField(docprop, "RN") + ",'BalanceSubReports', T.RN)")
            })
          }
        });


        dojo.forEach(parus.balance._detailAttrDescriptors, function(descriptor) {

          structure.push({
            colSpan: 1,
            attrRN: parus.parus8.nodeField(descriptor, "RN"),
            dataType: parus.parus8.nodeField(descriptor, "DATATYPE"),
            dataSubType: 0,
            field: "attr" + parus.parus8.nodeField(descriptor, "RN"),
            name: parus.parus8.nodeField(descriptor, "NAME"),
            formatter: parus.balance.formatAttrValue,
            width: (parus.parus8.nodeField(descriptor, "ACTIVE") == "1") ? "121px" : "0px",
            hidden: (parus.parus8.nodeField(descriptor, "ACTIVE") != "1"),
            styles: "text-align:" + ((parus.parus8.nodeField(descriptor, "DATATYPE") == 0) ? "left" : "right") + ";",
            sortField: (parus.parus8.nodeField(descriptor, "PARAMCOUNT") == "2") ? (parus.parus8.nodeField(descriptor, "STOREDPROC") + "(T.COMPANY, T.RN)") : (parus.parus8.nodeField(descriptor, "STOREDPROC") + "(T.RN)")
          })

        });

        if (structure.length) {
          var str = dojo.clone(parus.balance.formsDetailGrid.structure);
          str[0].cells[0] = str[0].cells[0].concat(structure);
          parus.balance.formsDetailGrid.setStructure(str);
        }

        parus.balance._createActionsButton(parus.balance.formsCatalogTreePopupMenu, parus.balance.formsCatalogTreeHeaderPane);
        parus.balance._createActionsButton(parus.balance.formsMasterGridPopupMenu, parus.balance.formsMasterGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.formsDetailGridPopupMenu, parus.balance.formsDetailGridHeaderPane);

        parus.balance._formsConditions = parus.userdata.get("formsConditions") || {};

        parus.balance.formsCatalogTreePopupMenu.bindDomNode(parus.balance.formsCatalogTree.domNode);
        parus.balance.formsMasterGridPopupMenu.bindDomNode(parus.balance.formsMasterGrid.viewsNode);
        if (parus.balance.formsDetailGridPopupMenu) parus.balance.formsDetailGridPopupMenu.bindDomNode(parus.balance.formsDetailGrid.viewsNode);

        var settings = parus.userdata.get("parus.balance.formsCatalogTree");
        if (settings) parus.gridSettingsDialog.mergeMenuSettings(parus.balance.formsCatalogTreePopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);

        var settings = parus.userdata.get("parus.balance.formsMasterGrid");
        if (settings) {
          parus.gridSettingsDialog.setCatalogTreeVisible(parus.balance.formsCatalogTree, !settings.hideCatalogTree);
          parus.gridSettingsDialog.mergeAdditions(parus.balance.formsSettingsAdditions(), settings.additions);
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.formsMasterGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.formsMasterGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.formsMasterGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.formsMasterGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
          parus.balance.formsMasterGrid.abonentFields = (settings.abonentFields || parus.balance.formsMasterGrid.abonentFields.split(";")).join(";");

        };

        var settings = parus.userdata.get("parus.balance.formsDetailGrid");
        if (settings) {
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.formsDetailGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.formsDetailGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.formsDetailGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.formsDetailGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
          parus.balance.formsDetailGrid.abonentFields = (settings.abonentFields || parus.balance.formsDetailGrid.abonentFields.split(";")).join(";");
        };


        parus.balance.formsCatalogTree.model = parus.balance.formsCatalogTreeStoreModel(parus.balance.formsCatalogTree);
        parus.catalogActions.refreshCatalogTree(parus.balance.formsCatalogTree);

        parus.balance._catalogChangeBuffer = {};

        parus.balance._translateConditionsToFilters(parus.balance._formsConditions, parus.balance.formsMasterGrid.columnsFilterObject.values);

        parus.parus8.showApplication(function() {
          setTimeout(function() {
            parus.balance.formsMasterGrid.focus.focusGrid();
          }, 300);
        });


      }
    }, node);


  },


  startupDesigner: function() {

    parus.balance.availableUnits = dojo.map(parus.parus8.rowNodes(parus.database.query("availableUnits")), function(node) {
      return parus.parus8.nodeField(node, "UNITCODE")
    });

    if (dojo.indexOf(parus.balance.availableUnits, "BalanceReportForms") == -1) {
      parus.parus8.errorMessage("У вас нет доступа к разделу <br/> \"Формы отчетов\"<br/> в приложении <br/> \"Сведение отчетности. Центр учета Онлайн\". <br/>Обратитесь к администратору.", parus.parus8.logout);
      return;
    };

    if (dojo.indexOf(parus.balance.availableUnits, "BalanceNotifications") != -1) {
      parus.parus8.checkNotifications();
    };

    parus.balance.formsPage = new dijit.layout.ContentPane({
      href: dojo.moduleUrl("parus", "balance.html").toString(),
      preload: true,
      "class": parus.parus8.zoomContainerClass(),
      onLoad: function() {

        parus.parus8.interfaceSchemaLoaded("designer");

        parus.balance._createFormsPane();

        parus.balance.TabContainer.addChild(parus.balance.formsPage);


      }

    }, parus.parus8.applicationNode()).startup();

  },


  formsCatalogTreeStoreModel: function(catalogTree) {
    return new parus.catalogTreeModel({
      queryid: "catalogsQuery",
      onGetConditions: function(model, parentNode) {
        if (catalogTree) if (catalogTree.hiddenMode) return {
          CRN: parus.parus8.CLASS_EmptyData
        };

        return {

          UNITCODE: "BalanceReportForms",
          CRN: (parentNode ? model.getIdentity(parentNode) : "!*")
        }
      }
    })
  },

  formsDetailGridStore: function(catalogTree, masterGrid, detailGridID) {

    return new parus.gridData({
      queryid: "BalanceReportFormEditions",
      parentUnitCode: "BalanceReportForms",

      onGetConditions: dojo.hitch(this, function(astore) {
        var store = masterGrid.store;
        var index = masterGrid.selection.getSelectedIndex();
        var item = (index >= 0) ? masterGrid.getItem(index) : null;

        var conditions = {
          "PRN": store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData
        };

        astore.parentRN = store.getValue(item, "RN");

        return conditions;
      }),

      onComplete: dojo.hitch(this, function(store, items, keywordArgs) {

        var item = catalogTree.selectedItem;

        var detailGrid = parus.parus8.denote(detailGridID);


        var checkMenu = function(menu) {

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

            if (menuItem.declaredClass != "dijit.MenuSeparator") {
              menuItem.userObjectsGrid = detailGrid;
              var disabled = catalogTree.listMode ? false : !catalogTree.model.hasAction(item, menuItem.actionCode);
              if (catalogTree.model.checkAccess()) {
                if (!menuItem.hiddenBySettings) menuItem.domNode.style.display = disabled ? "none" : "";
              }
              if (!disabled && (items.length == 0) && menuItem.itemAction) disabled = true;

              if (menuItem.declaredClass != "dijit.MenuSeparator") menuItem.attr("disabled", disabled);

              if (menuItem.popup) {
                menuItem.popup.from_item = menuItem;
                checkMenu(menuItem.popup);
              }

            }

          });
        };

        checkMenu(detailGrid.headerMenu);
        parus.parus8.checkMenuSeparators(detailGrid.headerMenu);


        if (items.length > 0 && !keywordArgs.start) {
          detailGrid.selection.select(0);
          detailGrid.updateRow(0);
          detailGrid.autoSelected = true;
        };

        setTimeout(function() {

          if (!dijit.popup.getTopPopup()) if (dojo.marginBox(masterGrid.domNode).w) masterGrid.focus.focusGrid();
        }, 0);


      })


    });

  },

  formsMasterGridStore: function(catalogTree, masterGridID) {
    return parus.gridData({
      queryid: "BalanceReportForms",

      onGetConditions: dojo.hitch(this, function(store) {

        var grid = parus.parus8.denote(masterGridID);

        if (!catalogTree.selectedItem && catalogTree.rootNode) {
          var path = [];

          var selectedCatalog = parus.userdata.get(masterGridID + "selectedCatalog");

          if (selectedCatalog.selectedCatalog) path = selectedCatalog.selectedCatalog.split(";");

          if ((path.length == 0) || (path[0] == "")) {
            var response = parus.database.execute("findAvailableCatalog", {
              UNITCODE: "BalanceReportForms"
            });

            if (response) path = parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "PATH").split(";");
          };

          if ((path.length == 0) || (path[0] == "")) path = [catalogTree.rootNode.item];

          var r = catalogTree.attr("path", path);
          if (r && r.addCallback) r.addCallback(function() {
            delete parus.balance._catalogChangeBuffer[catalogTree.id];
            catalogTree.onClick();
          });


          if (selectedCatalog.checks) {
            catalogTree.setCheckedPaths(

            dojo.map(selectedCatalog.checks.split(";"), function(path) {
              return path.split("/");
            })

            )
          };

        };

        var items = [];

        if (catalogTree.checked.length) dojo.forEach(catalogTree.checked, function(node) {
          items.push(catalogTree.model.getIdentity(node.item));
        })
        else dojo.forEach(catalogTree.paths, function(path) {
          if (catalogTree.model.isValid(path[path.length - 1])) items.push(catalogTree.model.getIdentity(path[path.length - 1]));
        });

        store.catalogRN = catalogTree.listMode ? null : items[0];

        var conditions = {
          "CRN": catalogTree.listMode ? null : (items.join(";") || parus.parus8.CLASS_EmptyData)
        };

        var item = catalogTree.selectedItem;

        dojo.forEach(grid.headerMenu.getChildren(), function(menuItem) {
          if (menuItem.actionCode) if (menuItem.declaredClass != "dijit.MenuSeparator") menuItem.attr("disabled", !catalogTree.model.hasAction(item, menuItem.actionCode));
        });

        return conditions;
      }),

      onComplete: dojo.hitch(this, function(store, items, keywordArgs) {

        var item = catalogTree.selectedItem;
        var grid = parus.parus8.denote(masterGridID);

        var checkMenu = function(menu) {

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

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

              menuItem.userObjectsGrid = grid;

              var disabled = catalogTree.listMode ? false : !catalogTree.model.hasAction(item, menuItem.actionCode);
              if (catalogTree.model.checkAccess()) {
                if (!menuItem.hiddenBySettings) menuItem.domNode.style.display = disabled ? "none" : "";
              }

              if (!disabled && (items.length == 0) && menuItem.itemAction) disabled = true;

              if (menuItem.declaredClass != "dijit.MenuSeparator") menuItem.attr("disabled", disabled);

              if (menuItem.popup) {
                menuItem.popup.from_item = menuItem;
                checkMenu(menuItem.popup);
              }

            }

          });

        };

        checkMenu(grid.headerMenu);
        parus.parus8.checkMenuSeparators(grid.headerMenu);

        if ((items.length > 0) && !grid.selection.getSelectedCount() && !keywordArgs.start) {
          grid.selection.select(0);
          grid.updateRow(0);
          grid.autoSelected = true;
        }
        grid.onSelected();
      })
    });
  },

  formsMasterGridChange: function(detailGridID, masterGridID, catalogTreeID) {

    if (parus.balance._refreshDetailGridTimeoutID) clearTimeout(parus.balance._refreshDetailGridTimeoutID);
    parus.balance._refreshDetailGridTimeoutID = setTimeout(dojo.hitch(parus.balance, function() {

      if (this._refreshDetailGridTimeoutID) clearTimeout(this._refreshDetailGridTimeoutID);
      this._refreshDetailGridTimeoutID = null;

      parus.balance._validateMenuByGrid(parus.parus8.denote(masterGridID), parus.parus8.denote(catalogTreeID));

      var grid = parus.parus8.denote(masterGridID);
      var store = grid.store;

      var index = grid.selection.getSelectedIndex();
      var item = (index >= 0) ? grid.getItem(index) : null;
      var selectedMaster = store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData;

      if (this._catalogChangeBuffer[masterGridID] != selectedMaster) {
        this._catalogChangeBuffer[masterGridID] = selectedMaster;
        var grid = parus.parus8.denote(detailGridID);

        if (grid) parus.balance.refreshGrid(grid);
      }


    }), 300);
  },

  showFormsPage: function(page) {
    if (dojo.isIE <= 8) {
      if (parus.balance._shownPages[page.id]) setTimeout(function() {
        parus.catalogActions.refreshCatalogTree(parus.balance.formsCatalogTree);
      }, 1000)
      else parus.balance.refreshGrid(parus.balance.formsMasterGrid);
      parus.balance._shownPages[page.id] = true;
    }
    else parus.balance.refreshGrid(parus.balance.formsMasterGrid);
  },

  formsSettingsAdditions: function() {
    return {};
  },

  createForm: function(catalogTree, grid) {
    parus.editableDictionaryDialog.prototype.insertAction(this, grid, parus.designerReportDialog);
  },

  duplicateForm: function(catalogTree, grid) {
    parus.editableDictionaryDialog.prototype.duplicateAction(this, grid, parus.designerReportDialog);
  },

  editForm: function(grid) {
    parus.editableDictionaryDialog.prototype.updateAction(this, grid, parus.designerReportDialog);
  },

  deleteForm: function(grid) {
    parus.editableDictionaryDialog.prototype.deleteAction(this, grid, parus.designerReportDialog);
  },

  moveForm: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    (new parus.treeDialog({

      model: parus.balance.formsCatalogTreeStoreModel(),

      key: "BalanceReportForms",

      onDefaultNeeded: function() {
        var response = parus.database.execute("findAvailableCatalog", {
          UNITCODE: "BalanceReportForms"
        });
        return response ? parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "PATH") : null;
      },

      onPerform: function(catalog) {
        for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
          parus.database.execute("moveDesignerReport", {
            RN: store.getValue(item, "RN"),
            CRN: catalog
          });
          item = grid.selection.getNextSelected(item);
        };

        grid.selection.deselectAll();
        parus.balance.refreshGrid(grid);
        return true;
      }

    })).show();
  },

  createEdition: function(grid) {
    parus.editableDictionaryDialog.prototype.insertAction(this, grid, parus.designerReportEditionDialog);
  },

  duplicateEdition: function(grid) {
    parus.editableDictionaryDialog.prototype.duplicateAction(this, grid, parus.designerReportEditionDialog);
  },

  editEdition: function(grid) {
    parus.editableDictionaryDialog.prototype.updateAction(this, grid, parus.designerReportEditionDialog);
  },

  deleteEdition: function(grid) {
    parus.editableDictionaryDialog.prototype.deleteAction(this, grid, parus.designerReportEditionDialog);
  },

  editionSections: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();
    var prn = store.getValue(item, "RN");

    var dialog;

    var menu = new dijit.Menu({
      "class": "balanceMenu"
    });

    menu.addChild(new dijit.MenuItem({
      label: "Добавить...",
      itemAction: false,
      defaultIcon: "PCHardwareadaltCustomIcon",
      onClick: dojo.hitch(this, function() {
        new parus.designerReportSectionDialog({
          titlePostfix: "Добавление",
          prn: prn,
          onApply: dojo.hitch(this, function(sectionDialog) {
            var response = sectionDialog.executeInsert();
            if (response) {
              var rn = parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN");
              var path = parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "PATH");

              if (path) {
                path = path.split(";");
                parus.catalogActions.refreshCatalogTree(dialog.catalogTree).then(

                function() {
                  dialog.catalogTree.attr("path", path)
                });
              }
            }
            return !!rn;
          })
        }).show();
      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Удалить",
      itemAction: true,
      defaultIcon: "PCreduceCustomIcon",
      onClick: dojo.hitch(this, function() {
        parus.catalogActions.deleteCatalogTreeItem(dialog.catalogTree, "Удалить разрез отчетности", "designer.BalanceReportForm.Sections.Delete");
      })
    }));

    menu.addChild(new dijit.MenuSeparator());
    menu.addChild(new dijit.MenuItem({
      label: "Обновить",
      itemAction: false,
      defaultIcon: "PCisyncCustomIcon",
      onClick: dojo.hitch(this, function() {
        parus.catalogActions.refreshCatalogTree(dialog.catalogTree);
      })
    }));

    menu.startup();

    dialog = new parus.treeDialog({
      title: "Разрезы отчетности формы",
      key: "BalanceReportFormsSections",
      restoreSelected: true,

      model: new parus.catalogTreeModel({
        queryid: "designer.BalanceReportForm.Sections",
        onGetConditions: dojo.hitch(this, function(model, parentNode) {
          return {
            PRN: prn,
            CRN: parentNode ? model.getIdentity(parentNode) : "!*"
          };
        })
      }),
      menu: menu
    });
    dialog.show();
  },

  showIndexes: function(multiselect, onApplyCallback) {
    var dictionaryInfo = parus.dictionaries["DesignerBalanceIndexesWithDetails"];
    dojo.mixin(dictionaryInfo, {
      multiselect: multiselect,
      dictionary: dictionaryInfo,
      editDialogClass: parus.designerIndexDialog,
      editDetailDialogClass: parus.designerIndexFormulaDialog,

      onApply: dojo.hitch(this, function(selectDialog) {
        if (onApplyCallback) onApplyCallback(selectDialog);
        return true;
      })
    });
    new parus.editableDictionaryDialog(dictionaryInfo).show();
  },

  showIndexesGroups: function(multiselect, onApplyCallback) {
    var dictionaryInfo = parus.dictionaries["DesignerBalanceIndexesGroupsWithDetails"];

    var dialog;

    var detailMenu = new dijit.Menu({
      "class": "balanceMenu"
    });

    detailMenu.addChild(new dijit.MenuItem({
      label: "Добавить списком...",
      itemAction: false,
      onClick: dojo.hitch(this, function() {
        this.showIndexes(true, dojo.hitch(this, function(selectDialog) {
          var grid = dialog.detailGrid;
          var store = grid.store;

          var prn = store.parentRN;
          var checks = selectDialog.getValue();

          if (checks && checks.length > 0) {
            if (parus.designerIndexGroupPartDialog.prototype.executeInsertList(prn, checks)) parus.balance.refreshGrid(dialog.detailGrid);
          }
        }));
      })
    }));

    detailMenu.startup();

    dojo.mixin(dictionaryInfo, {
      multiselect: multiselect,
      dictionary: dictionaryInfo,
      editDialogClass: parus.designerIndexGroupDialog,
      editDetailDialogClass: parus.designerIndexGroupPartDialog,

      onApply: dojo.hitch(this, function(selectDialog) {
        if (onApplyCallback) onApplyCallback(selectDialog);
        return true;
      }),
      detailMenu: detailMenu
    });

    dialog = new parus.editableDictionaryDialog(dictionaryInfo);
    dialog.show();
  },

  editionIndexes: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var editionRN = store.getValue(item, "RN");

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

    var dialog;

    var menu = new dijit.Menu({
      "class": "balanceMenu"
    });

    menu.addChild(new dijit.MenuItem({
      label: "Добавить списком...",
      itemAction: false,
      onClick: dojo.hitch(this, function() {
        this.showIndexes(true, dojo.hitch(this, function(selectDialog) {
          var checks = selectDialog.getValue();
          if (checks && checks.length > 0) {
            if (parus.designerReportIndexDialog.prototype.executeInsertList(editionRN, checks)) parus.balance.refreshGrid(dialog.grid);
          }
        }));
      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Добавить группу...",
      itemAction: false,
      onClick: dojo.hitch(this, function() {
        this.showIndexesGroups(false, dojo.hitch(this, function(selectDialog) {
          var group = selectDialog.getLabel();
          if (parus.designerReportIndexDialog.prototype.executeInsertGroup(editionRN, group)) parus.balance.refreshGrid(dialog.grid);
        }));
      })
    }));

    menu.startup();

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      multiselect: true,
      hideCancel: true,
      editByDoubleClick: true,
      editDialogClass: parus.designerReportIndexDialog,
      gridConditions: {
        PRN: editionRN
      },
      menu: menu
    });

    dialog = new parus.editableDictionaryDialog(dictionaryInfo);
    dialog.show();
  },

  editionTables: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var editionRN = store.getValue(item, "RN");

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

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      multiselect: true,
      hideCancel: true,
      editByDoubleClick: true,
      editDialogClass: parus.designerReportTableDialog,
      editDetailDialogClass: parus.designerReportTableIndexDialog,
      gridConditions: {
        PRN: editionRN
      }
    });

    new parus.designerReportTablesDictionaryDialog(dictionaryInfo).show();
  },

  editionLinks: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var editionRN = store.getValue(item, "RN");

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

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      multiselect: true,
      hideCancel: true,
      editByDoubleClick: true,
      editDialogClass: parus.designerReportLinkDialog,
      gridConditions: {
        PRN: editionRN
      }
    });

    new parus.editableDictionaryDialog(dictionaryInfo).show();
  },

  editionCheckLists: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var editionRN = store.getValue(item, "RN");

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

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      multiselect: true,
      hideCancel: true,
      editByDoubleClick: true,
      editDialogClass: parus.designerReportCheckListDialog,
      gridConditions: {
        PRN: editionRN
      }
    });

    new parus.editableDictionaryDialog(dictionaryInfo).show();
  },

  editionFormulas: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var editionRN = store.getValue(item, "RN");

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

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      multiselect: true,
      hideCancel: true,
      editByDoubleClick: true,
      editByDoubleClick: true,
      editDialogClass: parus.designerReportFormulaDialog,
      gridConditions: {
        PRN: editionRN
      }
    });

    new parus.editableDictionaryDialog(dictionaryInfo).show();
  },

  editionSplit: function(grid) {
    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    (new parus.designerEditionSplitDialog({
      rn: store.getValue(item, "RN"),
      onApply: dojo.hitch(this, function(dialog) {
        var result = dialog.split();
        if (result) parus.balance.refreshGrid(grid, "RN", dialog.rn);
        return result;
      })
    })).show();
  },

  editionTemplates: function(grid) {
    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    new parus.designerTemplatesDialog({
      editionRN: store.getValue(item, "RN")
    }).show();
  },

  editionCheckTemplates: function(grid) {
    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    (new parus.designerTemplatesCheckDialog({
      rn: store.getValue(item, "RN")
    })).show();
  },

  formatUserProcParamDataType: function(data, rowIndex, column) {
    return (["Строка (varchar2)", "Число (number)", "Дата (date)", "Логический (boolean)", "Двоичные данные (blob)", "Текстовые данные (clob)"])[data];
  },

  formatUserProcParamType: function(data, rowIndex, column) {
    return (["Входной (in)", "Выходной (out)"])[data];
  },

  formatUserProcParamLinking: function(data, rowIndex, column) {
    return (["Нет", "К организации", "К разделу", "К идентификатору ведомости", "К регистрационному номеру записи", "К дополнительному словарю", "К коду раздела", "К идентификатору отмеченных записей", "К Нет"])[data];
  },

  formatCheckErrorLevel: function(data, rowIndex, column) {
    return (["Ошибка", "Предупреждение"])[data];
  },

  formatBalanceIndexType: function(data, rowIndex, column) {
    return (["Строка", "Число", "Дата"])[data];
  },

  formatBalanceIndexAgrFunc: function(data, rowIndex, column) {
    return (["Сумма", "Среднее", "Минимальное", "Максимальное"])[data];
  },

  formatBalanceTableTotalKind: function(data, rowIndex, column) {
    return (["Промежуточный", "Общий"])[data];
  },

  formatBalanceTableTotalLocation: function(data, rowIndex, column) {
    return (["Под данными", "Над данными"])[data];
  },

  formatBalanceTableConstraintType: function(data, rowIndex, column) {
    return (["Уникальность", "Проверка"])[data];
  }

});

if (!parus.designer) dojo.mixin(parus, {
  designer: {}
});

if (!parus.designer.startup) dojo.mixin(parus.designer, {
  startup: dojo.hitch(parus.balance, parus.balance.startupDesigner)
});