dojo.provide("parus.balance");

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.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.userReportPane");
dojo.require("parus.balanceUserProcsDialog");
dojo.require("parus.balanceUserProcParamsDialog");
dojo.require("parus.balanceUserReportParamsDialog");

dojo.require("parus.templateGridPane");
dojo.require("parus.balanceReportsConditionsDialog");
dojo.require("parus.balanceReportDialog");
dojo.require("parus.balanceSubReportDialog");
dojo.require("parus.balanceCheckReportDialog");
dojo.require("parus.balanceReportCheckProtocolTabPage");
dojo.require("parus.balanceTemplatesDialog");
dojo.require("parus.balanceLoadReportsDialog");
dojo.require("parus.balanceCustomLoadReportsDialog");
dojo.require("parus.balanceCustomDownloadReportsDialog");
dojo.require("parus.balanceConsolidatedReportDialog");
dojo.require("parus.balanceReportsFileExportDialog");
dojo.require("parus.balanceReportsFileImportDialog");

dojo.require("parus.balanceSpecialActions");
dojo.require("parus.balanceStatusModel");
dojo.require("parus.balanceAdvReportPane");

dojo.require("parus.balanceUserCalcsDialog");

dojo.require("parus.signDialog");
dojo.require("parus.customIconsPalette");

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

if (!parus) parus = {};

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

dojo.mixin(parus.balance, {

  _primaryConditions: null,

  _consolidatedConditions: null,

  _refreshGridTimeoutID: null,

  _refreshDetailGridTimeoutID: null,

  _catalogChangeBuffer: {},

  _shownPages: {},

  primaryIgnoreMaxGridRecords: false,

  consolidatedIgnoreMaxGridRecords: false,

  showTemplateGutter: false,

  applicationCode: null,

  _createActionsButton: function(menu, pane, merged) {
    if (!pane) return;

    var children = pane.getChildren();

    if (children.length < 3) return;

    var buttonsPane = children[1];
    var barPane = children[2];

    if (!pane.actionsButton) {
      buttonsPane.domNode.style.overflow = "hidden";
      buttonsPane.domNode.style.zIndex = "100";

      var actionsButton = new dijit.form.ComboButton({
        label: "<span labelContent=\"1\">Действия</span>",
        dropDown: menu,
        style: "font-weight:bold;font-size:90%;margin:1px"
      }, dojo.place("<div/>", buttonsPane.domNode, "only"));

      dojo.mixin(actionsButton, {
        onClick: dojo.hitch(actionsButton, actionsButton.toggleDropDown)
      });

      dojo.mixin(pane, {
        actionsButton: actionsButton
      });

      dojo.mixin(menu, {
        actionsButtonPane: pane
      });

    };

    var buttons = [];

    var separatorNeeded = false;

    var clickHandler = function(item, preAction) {
      if (preAction) return function() {
        preAction();
        item.onClick();
      }
      else return dojo.hitch(item, item.onClick);
    }

    var checkMenu = function(menu, preAction) {
      separatorNeeded = true;
      dojo.forEach(menu.getChildren(), function(menuItem) {
        if (menuItem.declaredClass == "dijit.MenuSeparator") separatorNeeded = true;

        var icon = merged ? menuItem.customIcon : menuItem.defaultIcon;

        menuItem.customIcon = icon;

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

        if (icon) {

          if (separatorNeeded) {
            if (buttons.length /*&& !dojo.isIE */ ) buttons.push(new dijit.ToolbarSeparator({
              "class": "balanceToolBarSeparator"
            }));
            separatorNeeded = false;
          }

          menuItem.toolBarButton = new dijit.form.Button({
            label: menuItem.label,
            showLabel: false,
            "class": "balanceToolBarButton",
            iconClass: icon + "Big",
            onClick: clickHandler(menuItem, preAction)
          });

          buttons.push(menuItem.toolBarButton);
        }
        else menuItem.toolBarButton = null;


        if (menuItem.popup) checkMenu(menuItem.popup, preAction);

      });
    };

    checkMenu(menu, menu.preAction);


    if (buttons.length) {

      if (!pane.toolbar) {

        var toolbar = new dijit.Toolbar({
          "class": "balanceToolBar"
        }, dojo.place("<div>", barPane.domNode, "only"));

        dojo.mixin(pane, {
          toolbar: toolbar
        });

      }

      dojo.forEach(pane.toolbar.getChildren(), function(button) {
        pane.toolbar.removeChild(button);
      });

      dojo.forEach(buttons, function(button) {
        pane.toolbar.addChild(button);
      });

      pane.domNode.style.height = "33px";

      dojo.query("[labelContent]", pane.actionsButton.domNode).style({
        height: "21px",
        paddingTop: "5px",
        display: "block"
      });

    }
    else {
      if (pane.toolbar) {
        pane.toolbar.destroyRecursive();
        pane.toolbar = null;
      }
      pane.domNode.style.height = "25px";

      dojo.query("[labelContent]", pane.actionsButton.domNode).style({
        height: "auto",
        paddingTop: "0",
        display: ""
      });

    }

    parus.parus8.checkMenuSeparators(menu);
    dijit.byNode(pane.domNode.parentNode).layout();
    pane.layout();

  },

  _docprops: null,

  _detailDocprops: null,

  _masterAttrDescriptors: null,

  _masterUserCalcs: null,

  _detailUserCalcs: null,

  _detailAttrDescriptors: null,

  _masterHasStatusModel: false,

  formatPageTitle: function(title) {

    if (parus.parus8._embeddedMode) {
      var t = title.split("\n").join(" ");
      return "<div align='center'>" + t + "</div>";
    }
    else {
      var t = title.split("\n").join("<br/>");
      return (dojo.isIE) ? ("<span style='height:30px'>" + t + "</span>") : ("<div align='center' style='height:30px'>" + t + "</div>");
    }
  },

  availableUnits: null,

  _processMenu: function(menu, action) {
    dojo.forEach(menu.getChildren(), function(menuItem) {
      if (menuItem.popup) parus.balance._processMenu(menuItem.popup, action);
      action(menuItem);
    });
  },

  _createPrimaryReportsPane: function(node) {

    parus.balance.primaryPage = new dijit.layout.ContentPane({
      style: "height:100%;width:100%;padding:0",
      title: parus.balance.formatPageTitle("Первичные<br/>отчеты"),
      href: dojo.moduleUrl("parus", "balancePrimaryReportPane.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.primaryCatalogTree);
          }, 1000)
          else parus.balance.refreshGrid(parus.balance.primaryMasterGrid);
          parus.balance._shownPages[page.id] = true;
        }
        else parus.balance.refreshGrid(parus.balance.primaryMasterGrid);
      },
      onLoad: function() {

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

        if (!parus.balance._masterHasStatusModel) parus.balance._processMenu(parus.balance.primaryMasterGridPopupMenu, function(menuItem) {
          if (menuItem.features) if (dojo.indexOf(menuItem.features.split(";"), "StatusModel") >= 0) menuItem.destroyRecursive();
        });

        var structure = [];

        if (parus.balance._masterHasStatusModel) structure = structure.concat(parus.balance.statusModelColumns());

        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.primaryMasterGrid.structure);
          str[0].cells[0] = str[0].cells[0].concat(structure);
          parus.balance.primaryMasterGrid.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.primaryDetailGrid.structure);
          str[0].cells[0] = str[0].cells[0].concat(structure);
          parus.balance.primaryDetailGrid.setStructure(str);
        }

        parus.balance._createActionsButton(parus.balance.primaryCatalogTreePopupMenu, parus.balance.primaryCatalogTreeHeaderPane);
        parus.balance._createActionsButton(parus.balance.primaryMasterGridPopupMenu, parus.balance.primaryMasterGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.primaryDetailGridPopupMenu, parus.balance.primaryDetailGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.primaryFoldersTreePopupMenu, parus.balance.primaryFoldersTreeHeaderPane);


        parus.balance._primaryConditions = parus.userdata.get("primaryConditions") || {};

        parus.balance.primaryCatalogTreePopupMenu.bindDomNode(parus.balance.primaryCatalogTree.domNode);
        parus.balance.primaryMasterGridPopupMenu.bindDomNode(parus.balance.primaryMasterGrid.viewsNode);
        if (parus.balance.primaryDetailGridPopupMenu) parus.balance.primaryDetailGridPopupMenu.bindDomNode(parus.balance.primaryDetailGrid.viewsNode);
        parus.balance.primaryFoldersTreePopupMenu.bindDomNode(parus.balance.primaryFolderTree.domNode);

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

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

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

        };

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


        parus.balance.primaryCatalogTree.model = parus.balance.catalogTreeStoreModel(parus.balance.primaryCatalogTree);
        parus.catalogActions.refreshCatalogTree(parus.balance.primaryCatalogTree);

        parus.balance.primaryFolderTree.model = parus.balance.foldersTreeStoreModel(parus.balance.primaryFolderTree);
        parus.catalogActions.refreshCatalogTree(parus.balance.primaryFolderTree);

        parus.balance.primaryFoldersPane._splitterWidget.domNode.style.display = parus.balance.primaryFoldersPane.domNode.style.display;

        parus.balance._catalogChangeBuffer = {};

        parus.balance._translateConditionsToFilters(parus.balance._primaryConditions, parus.balance.primaryMasterGrid.columnsFilterObject.values);

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


      }
    }, node);
  },

  _createConsolidatedReportsPane: function(node) {

    parus.balance.consolidatedPage = new dijit.layout.ContentPane({
      style: "height:100%;width:100%;padding:0",
      title: parus.balance.formatPageTitle("Сводные<br/>отчеты"),
      href: dojo.moduleUrl("parus", "balanceConsolidatedReportPane.html").toString(),
      region: "center",

      onShow: function() {
        if (parus.balance.consolidatedMasterGrid) {
          if (dojo.isIE <= 8) {
            setTimeout(function() {
              parus.catalogActions.refreshCatalogTree(parus.balance.consolidatedCatalogTree);
            }, 1000)
          }
          else parus.balance.refreshGrid(parus.balance.consolidatedMasterGrid);
        }
      },

      onLoad: function() {

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

        if (!parus.balance._masterHasStatusModel) parus.balance._processMenu(parus.balance.consolidatedMasterGridPopupMenu, function(menuItem) {
          if (menuItem.features) if (dojo.indexOf(menuItem.features.split(";"), "StatusModel") >= 0) menuItem.destroyRecursive();
        });

        var structure = [];

        if (parus.balance._masterHasStatusModel) structure = structure.concat(parus.balance.statusModelColumns());

        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.consolidatedMasterGrid.structure);
          str[0].cells[0] = str[0].cells[0].concat(structure);
          parus.balance.consolidatedMasterGrid.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.consolidatedDetailGrid.structure);
          str[0].cells[0] = str[0].cells[0].concat(structure);
          parus.balance.consolidatedDetailGrid.setStructure(str);
        }


        parus.balance._createActionsButton(parus.balance.consolidatedCatalogTreePopupMenu, parus.balance.consolidatedCatalogTreeHeaderPane);
        parus.balance._createActionsButton(parus.balance.consolidatedMasterGridPopupMenu, parus.balance.consolidatedMasterGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.consolidatedDetailGridPopupMenu, parus.balance.consolidatedDetailGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.consolidatedFoldersTreePopupMenu, parus.balance.consolidatedFoldersTreeHeaderPane);

        parus.balance._consolidatedConditions = parus.userdata.get("consolidatedConditions") || {};

        parus.balance.consolidatedCatalogTreePopupMenu.bindDomNode(parus.balance.consolidatedCatalogTree.domNode);
        parus.balance.consolidatedMasterGridPopupMenu.bindDomNode(parus.balance.consolidatedMasterGrid.viewsNode);
        parus.balance.consolidatedDetailGridPopupMenu.bindDomNode(parus.balance.consolidatedDetailGrid.viewsNode);
        parus.balance.consolidatedFoldersTreePopupMenu.bindDomNode(parus.balance.consolidatedFolderTree.domNode);

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

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

        var settings = parus.userdata.get("parus.balance.consolidatedMasterGrid");
        if (settings) {
          parus.gridSettingsDialog.setCatalogTreeVisible(parus.balance.consolidatedCatalogTree, !settings.hideCatalogTree);
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.consolidatedMasterGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeAdditions(parus.balance.consolidatedSettingsAdditions(), settings.additions);

          var store = parus.balance.consolidatedMasterGrid.store;
          parus.balance.consolidatedMasterGrid.setStore(new parus.emptyGridData());

          parus.gridSettingsDialog.mergeGridSettings(parus.balance.consolidatedMasterGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.consolidatedMasterGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.consolidatedMasterGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);

          parus.balance.consolidatedMasterGrid.setStore(store);

        };

        var settings = parus.userdata.get("parus.balance.consolidatedDetailGrid");
        if (settings) {
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.consolidatedDetailGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.consolidatedDetailGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.consolidatedDetailGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.consolidatedDetailGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
        };

        var catalogTree = parus.balance.consolidatedCatalogTree;
        catalogTree.model = parus.balance.catalogTreeStoreModel(catalogTree);

        if (catalogTree.dndController && !dojo.isString(catalogTree.dndController)) {
          var controllerClass = catalogTree.dndController.declaredClass;
          catalogTree.dndController.destroy();
          catalogTree.dndController = controllerClass;
        };

        catalogTree.postMixInProperties();
        catalogTree.postCreate();


        var foldersTree = parus.balance.consolidatedFolderTree;
        foldersTree.model = parus.balance.foldersTreeStoreModel(foldersTree);

        if (foldersTree.dndController && !dojo.isString(foldersTree.dndController)) {
          var controllerClass = foldersTree.dndController.declaredClass;
          foldersTree.dndController.destroy();
          foldersTree.dndController = controllerClass;
        };

        foldersTree.postMixInProperties();
        foldersTree.postCreate();

        parus.balance.consolidatedFoldersPane._splitterWidget.domNode.style.display = parus.balance.consolidatedFoldersPane.domNode.style.display;

        parus.balance._translateConditionsToFilters(parus.balance._consolidatedConditions, parus.balance.consolidatedMasterGrid.columnsFilterObject.values);


      }

    }, node);

  },

  _createCompareReportsPane: function(node) {

    parus.balance.advContentPage = new dijit.layout.ContentPane({
      style: "height:100%;width:100%;padding:0",
      title: parus.balance.formatPageTitle("Протоколы<br/>сравнения отчетов"),
      href: dojo.moduleUrl("parus", "balanceAdvReportPane.html").toString(),
      region: "center",

      onShow: function() {
        if (parus.balance.advCheckMasterGrid) {
          if (dojo.isIE <= 8) {
            setTimeout(function() {
              parus.catalogActions.refreshCatalogTree(parus.balance.advCheckCatalogTree);
            }, 1000)
          }
          else parus.balance.refreshGrid(parus.balance.advCheckMasterGrid);
        }

      },

      onLoad: function() {

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

        parus.balance._createActionsButton(parus.balance.advCheckCatalogTreePopupMenu, parus.balance.advCheckCatalogTreeHeaderPane);
        parus.balance._createActionsButton(parus.balance.advCheckMasterGridPopupMenu, parus.balance.advCheckMasterGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.advCheckEqualDetailGridPopupMenu, parus.balance.advCheckEqualDetailGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.advCheckEqualSubDetailGridPopupMenu, parus.balance.advCheckEqualSubDetailGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.advCheckUnEqualDetailGridPopupMenu, parus.balance.advCheckUnEqualDetailGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.advCheckUnEqualSubDetailGridPopupMenu, parus.balance.advCheckUnEqualSubDetailGridHeaderPane);
        parus.balance._createActionsButton(parus.balance.advCheckExcludedDetailGridPopupMenu, parus.balance.advCheckExcludedDetailGridHeaderPane);


        parus.balance.advCheckCatalogTreePopupMenu.bindDomNode(parus.balance.advCheckCatalogTree.domNode);
        parus.balance.advCheckMasterGridPopupMenu.bindDomNode(parus.balance.advCheckMasterGrid.viewsNode);
        parus.balance.advCheckEqualDetailGridPopupMenu.bindDomNode(parus.balance.advCheckEqualDetailGrid.viewsNode);
        parus.balance.advCheckEqualSubDetailGridPopupMenu.bindDomNode(parus.balance.advCheckEqualSubDetailGrid.viewsNode);
        parus.balance.advCheckUnEqualDetailGridPopupMenu.bindDomNode(parus.balance.advCheckUnEqualDetailGrid.viewsNode);
        parus.balance.advCheckUnEqualSubDetailGridPopupMenu.bindDomNode(parus.balance.advCheckUnEqualSubDetailGrid.viewsNode);
        parus.balance.advCheckExcludedDetailGridPopupMenu.bindDomNode(parus.balance.advCheckExcludedDetailGrid.viewsNode);


        var settings = parus.userdata.get("parus.balance.advCheckMasterGrid");
        if (settings) {

          parus.gridSettingsDialog.setCatalogTreeVisible(parus.balance.advCheckCatalogTree, !settings.hideCatalogTree);
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.advCheckMasterGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeAdditions(parus.balance.advCheckSettingsAdditions(), settings.additions);


          var store = parus.balance.advCheckMasterGrid.store;
          parus.balance.advCheckMasterGrid.setStore(new parus.emptyGridData());

          parus.gridSettingsDialog.mergeGridSettings(parus.balance.advCheckMasterGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.advCheckMasterGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.advCheckMasterGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);

          parus.balance.advCheckMasterGrid.setStore(store);

        };

        var settings = parus.userdata.get("parus.balance.advCheckEqualDetailGrid");
        if (settings) {
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.advCheckEqualDetailGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.advCheckEqualDetailGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.advCheckEqualDetailGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.advCheckEqualDetailGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
          parus.gridSettingsDialog.mergeAdditions(parus.balance.advCheckEqualSettingsAdditions(), settings.additions);
        };


        var settings = parus.userdata.get("parus.balance.advCheckEqualSubDetailGrid");
        if (settings) {
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.advCheckEqualSubDetailGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.advCheckEqualSubDetailGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.advCheckEqualSubDetailGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.advCheckEqualSubDetailGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
        };

        var settings = parus.userdata.get("parus.balance.advCheckUnEqualDetailGrid");
        if (settings) {
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.advCheckUnEqualDetailGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.advCheckUnEqualDetailGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.advCheckUnEqualDetailGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.advCheckUnEqualDetailGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
          parus.gridSettingsDialog.mergeAdditions(parus.balance.advCheckUnEqualSettingsAdditions(), settings.additions);
        };


        var settings = parus.userdata.get("parus.balance.advCheckUnEqualSubDetailGrid");
        if (settings) {
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.advCheckUnEqualSubDetailGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.advCheckUnEqualSubDetailGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.advCheckUnEqualSubDetailGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.advCheckUnEqualSubDetailGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
        };

        var settings = parus.userdata.get("parus.balance.advCheckExcludedDetailGrid");
        if (settings) {
          parus.gridSettingsDialog.mergeMenuSettings(parus.balance.advCheckExcludedDetailGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
          parus.gridSettingsDialog.mergeGridSettings(parus.balance.advCheckExcludedDetailGrid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(parus.balance.advCheckExcludedDetailGrid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(parus.balance.advCheckExcludedDetailGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
        };

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

        parus.balance.advCheckCatalogTree.model =
        new parus.catalogTreeModel({
          queryid: "catalogsQuery",
          onGetConditions: function(model, parentNode) {
            return {
              UNITCODE: "BalanceCompareReports",
              CRN: (parentNode ? model.getIdentity(parentNode) : "!*")
            }
          }
        });

        if (!parus.balance.advCheckCatalogTree.hiddenMode) parus.catalogActions.refreshCatalogTree(parus.balance.advCheckCatalogTree);

      }

    }, node);



  },


  _loadUserObjects: function() {

    parus.balance._docprops = parus.parus8.rowNodes(parus.database.query("docProperties", {
      "UNITCODE": "BalanceReports"
    })) || [];

    parus.balance._detailDocprops = parus.parus8.rowNodes(parus.database.query("docProperties", {
      "UNITCODE": "BalanceSubReports"
    })) || [];

    parus.balance._masterAttrDescriptors = parus.parus8._attrDescriptors ? parus.parus8.rowNodes(parus.database.execute("attrDescriptors", {
      "UNITCODE": "BalanceReports"
    }).documentElement.childNodes[0].childNodes[0].childNodes[0]) || [] : [];

    parus.balance._masterUserCalcs = parus.parus8.rowNodes(parus.database.query("UserCalcs", {
      "UNITCODE": "BalanceReports"
    })) || [];

    parus.balance._detailAttrDescriptors = parus.parus8._attrDescriptors ? parus.parus8.rowNodes(parus.database.execute("attrDescriptors", {
      "UNITCODE": "BalanceSubReports"
    }).documentElement.childNodes[0].childNodes[0].childNodes[0]) || [] : [];

    parus.balance._detailUserCalcs = parus.parus8.rowNodes(parus.database.query("UserCalcs", {
      "UNITCODE": "BalanceSubReports"
    })) || [];


  },

  _startupBalanceApplication: function() {

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

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

        parus.parus8.interfaceSchemaLoaded("balance");

        parus.balance._loadUserObjects();

        parus.balance._createPrimaryReportsPane();
        parus.balance.TabContainer.addChild(parus.balance.primaryPage);

        if (dojo.indexOf(parus.balance.availableUnits, "BalanceConsolidatedReports") != -1) {
          parus.balance._createConsolidatedReportsPane();
          parus.balance.TabContainer.addChild(parus.balance.consolidatedPage);
        };

        if (parus.database.attributes.advcheck && (dojo.indexOf(parus.balance.availableUnits, "BalanceCompareReports") != -1)) {
          parus.balance._createCompareReportsPane();
          parus.balance.TabContainer.addChild(parus.balance.advContentPage);
        };

      }

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


  },

  startup: function(sessionContent) {
    //    console.log(sessionContent);

    parus.balance.applicationCode = parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("getAppCode"))[0], "APPLICATION");

    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, "BalanceReports") == -1) {
      parus.parus8.errorMessage("У вас нет доступа к разделу <br/> \"Первичные/сводные отчеты\"<br/> в приложении <br/> \"Сведение отчетности. Центр учета Онлайн\". <br/>Обратитесь к администратору.", parus.parus8.logout);
      return;
    };

    parus.parus8._attrDescriptors = (dojo.indexOf(parus.balance.availableUnits, "AttributesDescriptors") != -1);
    parus.parus8.extraDictionaries._canCacheExtraDictionaries = (parus.parus8.optionValue("BalanceOnlineCacheContractorDictValues") != "0");
    parus.parus8.extraDictionaries._autoCompleteLimit = parus.parus8.optionValue("BalanceOnlineAutoCompleteDictSize");

    parus.parus8.maxGridRecords = parus.parus8.optionValue("BalanceOnlineMaxGridRecords");

    parus.dictionaries._autoCompleteLimit = parus.parus8.optionValue("BalanceOnlineAutoCompleteUnitSize");

    if (dojo.indexOf(parus.balance.availableUnits, "UnitsStatusModels") != -1) {
      parus.balance._masterHasStatusModel =
      parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("hasStatusModel", {
        "UNITCODE": "BalanceReports"
      }))[0], "VALUE") != "0";
    }

    if (parus.parus8._embeddedMode) {

      if (sessionContent["unitCode"] == "BalanceReports") {
        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, "BalanceReports") == -1) {
          parus.parus8.errorMessage("У вас нет доступа к разделу <br/> \"Первичные/сводные отчеты\"<br/> в приложении <br/> \"Сведение отчетности. Центр учета Онлайн\". <br/>Обратитесь к администратору.", parus.parus8.logout);
          return;
        };

        parus.balance._loadUserObjects();

        parus.balance._createPrimaryReportsPane(parus.parus8.applicationNode());
        parus.WindowContainer.addChild(parus.balance.primaryPage);

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


      }
      else if (sessionContent["unitCode"] == "BalanceConsolidatedReports") {
        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, "BalanceConsolidatedReports") == -1) {
          parus.parus8.errorMessage("У вас нет доступа к разделу <br/> \"Сводные отчеты\"<br/> в приложении <br/> \"Сведение отчетности. Центр учета Онлайн\". <br/>Обратитесь к администратору.", parus.parus8.logout);
          return;
        };

        parus.balance._loadUserObjects();

        parus.balance._createConsolidatedReportsPane(parus.parus8.applicationNode());
        parus.WindowContainer.addChild(parus.balance.consolidatedPage);

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

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

      }
      else if (sessionContent["unitCode"] == "BalanceCompareReports") {
        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, "BalanceCompareReports") == -1) {
          parus.parus8.errorMessage("У вас нет доступа к разделу <br/> \"Протоколы сравнения отчетов\"<br/> в приложении <br/> \"Сведение отчетности. Центр учета Онлайн\". <br/>Обратитесь к администратору.", parus.parus8.logout);
          return;
        };

        parus.balance._loadUserObjects();

        parus.balance._createCompareReportsPane(parus.parus8.applicationNode());
        parus.WindowContainer.addChild(parus.balance.advContentPage);

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

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

      }
      else {
        parus.parus8.errorMessage("Раздел не поддерживается.", parus.parus8.logout);
      }
    }
    else parus.balance._startupBalanceApplication();
  },

  primarySettingsAdditions: function() {
    var settings = [{
      widget: parus.balance.primaryDetailGridPane,
      title: "Скрыть подотчеты",
      id: "detailGridPaneHiddenMode"
    }];


    if ((dojo.indexOf(parus.balance.availableUnits, "ConditionFolders") != -1)) settings.push({
      widget: parus.balance.primaryFoldersPane,
      title: "Скрыть дерево папок",
      id: "primaryFoldersHiddenMode"
    });

    settings.push({
      title: "Отображать иерархию итогов при открытии отчета",
      id: "showGutter",
      get: dojo.hitch(this, function() {
        return this.showTemplateGutter;
      }),
      set: dojo.hitch(this, function(value) {
        this.showTemplateGutter = value;
      })
    });

    return settings;
  },


  consolidatedSettingsAdditions: function() {
    var settings = [{
      widget: parus.balance.consolidatedDetailGridPane,
      title: "Скрыть подотчеты",
      id: "detailGridPaneHiddenMode"
    }];

    if ((dojo.indexOf(parus.balance.availableUnits, "ConditionFolders") != -1)) settings.push({
      widget: parus.balance.consolidatedFoldersPane,
      title: "Скрыть дерево папок",
      id: "consolidatedFoldersHiddenMode"
    });

    settings.push({
      title: "Отображать иерархию итогов при открытии отчета",
      id: "showGutter",
      get: dojo.hitch(this, function() {
        return this.showTemplateGutter;
      }),
      set: dojo.hitch(this, function(value) {
        this.showTemplateGutter = value;
        var settings = parus.userdata.get("parus.balance.primaryMasterGrid");
        settings.additions.showGutter = this.showTemplateGutter;
        parus.userdata.set("parus.balance.primaryMasterGrid", settings)

      })
    });


    return settings;
  },

  catalogTreeStoreModel: 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: "BalanceReports",
          CRN: (parentNode ? model.getIdentity(parentNode) : "!*")
        }
      }
    })
  },

  foldersTreeStoreModel: function(foldersTree) {

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


        return {
          UNITCODE: "BalanceReports",
          CRN: (parentNode ? model.getIdentity(parentNode) : "!*")
        }
      }
    })

  },

  refreshGrid: function(grid, posFieldName, posFieldValue) {
    if (!grid) return;

    var query = grid.query || {};

    var selections = [];

    delete parus.balance._catalogChangeBuffer[grid.gridid];

    var item = grid.selection.getFirstSelected();
    if (item) for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      selections.push(grid.getItemIndex(item));
      item = grid.selection.getNextSelected(item);
    };

    if (selections.length || (posFieldName && posFieldValue)) {
      dojo.mixin(query, {
        onComplete: function() {

          if (posFieldName && posFieldValue) {
            var item = grid.store.findIndex(posFieldName, posFieldValue);
            if (item >= 0 && grid.selection.getSelectedCount() <= 1) {
              grid.scrollToRow(item);
              grid.selection.select(item);
              grid.updateRow(item);
              grid.autoSelected = true;
            }
          }
          else {
            grid.selection.deselectAll();
            grid.store.forEach(

            function(store, item, idx) {
              if (dojo.indexOf(selections, idx) >= 0) {
                grid.scrollToRow(idx);
                grid.selection.addToSelection(idx);
                grid.updateRow(idx);
              }
            });
          }
          delete query.onComplete;
        }
      });
    };
    if (grid.store) grid.store.close();
    grid.setQuery(query);
  },

  catalogTreeChange: function(catalogTree, foldersTree, linkedGrid, linkedGridID, menu, foldersMenu) {

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

      if (this._refreshGridTimeoutID) clearTimeout(this._refreshGridTimeoutID);

      this._refreshGridTimeoutID = null;

      var changed = false;

      if (linkedGridID) {

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

        var path = [];

        var checks = [];
        if (catalogTree.checked.length > 1) dojo.forEach(catalogTree.checked, function(node) {
          checks.push(dojo.map(node.getTreePath(node), function(item) {
            return catalogTree.model.getIdentity(item);
          }).join("/"));
        });

        dojo.forEach(catalogTree.path, function(item) {
          path.push(catalogTree.model.getIdentity(item));
        });


        if (path.length) dojo.mixin(selectedCatalog, {
          selectedCatalog: path.join(";"),
          checks: checks.join(";")
        });

        if (foldersTree) {
          var folderPath = [];

          if (!foldersTree.hiddenMode) {
            dojo.forEach(foldersTree.path, function(item) {
              folderPath.push(foldersTree.model.getIdentity(item));
            });
          };

          if (folderPath.length) dojo.mixin(selectedCatalog, {
            selectedFolder: folderPath.join(";")
          });

          var selectedFolder = folderPath.join(";");

          if (this._catalogChangeBuffer[foldersTree.id] != selectedFolder) {
            changed = true;
            this._catalogChangeBuffer[foldersTree.id] = selectedFolder;
          }

        }

        parus.userdata.set(linkedGridID + "selectedCatalog", selectedCatalog, true);

        if (this._catalogChangeBuffer[catalogTree.id] != (catalogTree.listMode ? "0" : dojo.toJson(selectedCatalog))) {
          changed = true;
          this._catalogChangeBuffer[catalogTree.id] = (catalogTree.listMode ? "0" : dojo.toJson(selectedCatalog));
        }


      };

      var path = catalogTree.path;

      dojo.forEach(menu.getChildren(), function(menuItem) {
        var disabled = !catalogTree.model.hasAction(path[path.length - 1], menuItem.actionCode);
        if (catalogTree.model.checkAccess()) {
          if (!menuItem.hiddenBySettings) menuItem.domNode.style.display = disabled ? "none" : "";
        }
        if (menuItem.declaredClass != "dijit.MenuSeparator") menuItem.attr("disabled", disabled);
      });

      parus.parus8.checkMenuSeparators(menu);


      if (foldersTree) {

        var path = foldersTree.path;

        dojo.forEach(foldersMenu.getChildren(), function(menuItem) {
          var disabled = !foldersTree.model.hasAction(path[path.length - 1], menuItem.actionCode);
          if (foldersTree.model.checkAccess()) {
            if (!menuItem.hiddenBySettings) menuItem.domNode.style.display = disabled ? "none" : "";
          }
          if (menuItem.declaredClass != "dijit.MenuSeparator") menuItem.attr("disabled", disabled);
        });

        parus.parus8.checkMenuSeparators(foldersMenu);

      };

      if (changed) linkedGrid.setQuery(linkedGrid.query);


    }), 300);
  },

  detailGridStore: function(catalogTree, masterGrid, detailGridID) {


    return new parus.gridData({
      queryid: "detailGridData",
      parentUnitCode: "BalanceReports",

      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);


      })


    });

  },

  masterGridStore: function(catalogTree, masterGridID, kind, foldersTree) {
    return parus.gridData({
      queryid: "masterGridData",

      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: "BalanceReports"
            });

            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("/");
            })

            )
          };

        };

        if (foldersTree) {
          if (!foldersTree.selectedItem && foldersTree.rootNode && !foldersTree.hiddenMode) {
            var path = [];
            var selectedCatalog = parus.userdata.get(masterGridID + "selectedCatalog");
            if (selectedCatalog.selectedFolder) path = selectedCatalog.selectedFolder.split(";");
            if ((path.length == 0) || (path[0] == "")) {
              path = [foldersTree.rootNode.item];
              foldersTree.model.getChildren(foldersTree.rootNode.item, function(children) {
                if (children.length) {
                  path.push(children[0]);
                  foldersTree.attr("path", path)
                }
              });
            }
            foldersTree.attr("path", path);
          };
        };

        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 = {
          "KIND": kind,
          "CRN": catalogTree.listMode ? null : (items.join(";") || parus.parus8.CLASS_EmptyData)
        };

        if (foldersTree && !foldersTree.hiddenMode) {
          var folder = ((foldersTree.selectedItem) ? foldersTree.model.getIdentity(foldersTree.selectedItem) : 0) || 0;
          if (folder == "-1" || folder == "0") folder = parus.parus8.CLASS_EmptyData;
          dojo.mixin(conditions, {
            "CONDFOLDER": folder
          });
        };

        if (kind == 0) {
          document.getElementById("parus.balance.primaryMasterGridFilterIndicator").style.display = (this.hasConditions(this._primaryConditions) ? "" : "none");
          parus.balance.primaryMasterGridHeaderPane.layout();
          dojo.mixin(conditions, this._primaryConditions);
        }
        else {
          document.getElementById("parus.balance.consolidatedMasterGridFilterIndicator").style.display = (this.hasConditions(this._consolidatedConditions) ? "" : "none");
          parus.balance.consolidatedMasterGridHeaderPane.layout();
          dojo.mixin(conditions, this._consolidatedConditions);
        }

        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));
        });

        if (kind == 0) {
          if (parus.balance.primaryIgnoreMaxGridRecords) {
            dojo.mixin(conditions, {
              "IGNORE_MAX_RECORDS": 1
            });
            grid.onClose = parus.balance.masterGridOnCloseHandler(kind);
          }
        }
        else {
          if (parus.balance.consolidatedIgnoreMaxGridRecords) {
            dojo.mixin(conditions, {
              "IGNORE_MAX_RECORDS": 1
            });
            grid.onClose = parus.balance.masterGridOnCloseHandler(kind);
          }
        };

        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 (parus.parus8.maxGridRecords != null) {
          if (kind == 0) {
            document.getElementById("parus.balance.primaryMasterGridMaxGridRecordsIndicator").style.display = ((items.length == parus.parus8.maxGridRecords) ? "" : "none");
            parus.balance.primaryMasterGridHeaderPane.layout();
          }
          else {
            document.getElementById("parus.balance.consolidatedMasterGridMaxGridRecordsIndicator").style.display = ((items.length == parus.parus8.maxGridRecords) ? "" : "none");
            parus.balance.consolidatedMasterGridHeaderPane.layout();
          };
        };

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

      onClose: parus.balance.masterGridOnCloseHandler(kind)



    });
  },

  masterGridOnCloseHandler: function(kind) {

    return function() {
      if (kind == 0) {
        parus.balance.primaryIgnoreMaxGridRecords = false;
      }
      else {
        parus.balance.consolidatedIgnoreMaxGridRecords = false;
      };
    };
  },

  primaryMasterGridMaxGridRecordsIndicatorClick: function() {
    (new parus.confirmationDialog({
      message: "Показать все записи, игнорируя ограничения?<br/>Это может занять длительное время.",
      onApply: function() {
        var grid = parus.balance.primaryMasterGrid;
        if (grid.store) grid.store.close();
        parus.balance.primaryIgnoreMaxGridRecords = true;
        parus.balance.refreshGrid(grid);
        return true;
      }
    })).show();
  },

  consolidatedMasterGridMaxGridRecordsIndicatorClick: function() {
    (new parus.confirmationDialog({
      message: "Показать все записи, игнорируя ограничения?<br/>Это может занять длительное время.",
      onApply: function() {
        var grid = parus.balance.consolidatedMasterGrid;
        if (grid.store) grid.store.close();
        parus.balance.consolidatedIgnoreMaxGridRecords = true;
        parus.balance.refreshGrid(grid);
        return true;
      }
    })).show();
  },

  hasConditions: function(conditions) {
    var hasConditions = false;
    for (var key in conditions)
    if (key == "DOCPROPS") for (var docprop in conditions[key]) hasConditions = hasConditions || conditions[key][docprop].value || conditions[key][docprop].from || conditions[key][docprop].to;
    else hasConditions = hasConditions || conditions[key];
    return hasConditions;
  },

  _validateMenuByGrid: function(grid, catalogTree) {


    var store = grid.store;
    var item = grid.selection.getFirstSelected();
    var rns = null;

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      if (!rns) rns = store.getValue(item, "CRN")
      else if (rns != store.getValue(item, "CRN")) return;
      item = grid.selection.getNextSelected(item);
    };

    if (!rns) return;

    if (catalogTree.checked.length <= 1 && !catalogTree.listMode && !catalogTree.hiddenMode) return;

    var ctlgItem = catalogTree.model.getItem(rns);
    if (!ctlgItem) return;

    var checkMenu = function(menu) {

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

        if (menuItem.declaredClass != "dijit.MenuSeparator") {
          var disabled = !catalogTree.model.hasAction(ctlgItem, menuItem.actionCode);
          if (catalogTree.model.checkAccess()) {
            if (!menuItem.hiddenBySettings) menuItem.domNode.style.display = disabled ? "none" : "";
          }
          if (menuItem.declaredClass != "dijit.MenuSeparator") menuItem.attr("disabled", disabled);

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

      });
    };

    var menu = grid.headerMenu;
    checkMenu(menu);
    parus.parus8.checkMenuSeparators(menu);

  },


  masterGridChange: 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);
  },

  primaryBalanceReportsConditions: function() {
    var dialog = new parus.balanceReportsConditionsDialog({

      title: "Первичные отчеты: Отбор",

      onShow: dojo.hitch(this, function() {
        dialog.loadConditions(this._primaryConditions);

      }),

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

        this._primaryConditions = dialog.saveConditions();

        if (parus.balance._translateConditionsToFilters(this._primaryConditions, parus.balance.primaryMasterGrid.columnsFilterObject.values)) parus.balance.primaryMasterGrid.columnsFilterObject.valuesChanged();

        parus.userdata.set("primaryConditions", this._primaryConditions);
        parus.balance.primaryMasterGrid.setQuery(parus.balance.primaryMasterGrid.query);
        return true;
      })
    });

    dialog.show();
  },

  formatReportKind: function(data, rowIndex, column) {
    return (["Первичный", "Сводный", "Все"])[data];
  },

  formatReportStatus: function(data, rowIndex, column) {
    return (["Новый", "Изменен", "Рассчитан", "В своде", "Сведен без итогов", "Сведен с итогами", "Загружен", "Сведен предварительно"])[data];
  },

  formatReportHistory: function(data, rowIndex, column) {
    return (["Нет", "Да", "По запросу"])[data];
  },

  formatReportAccepted: function(data, rowIndex, column) {
    return (["Нет", "Да", "Отклонен"])[data];
  },

  formatProtocolCheckType: function(data, rowIndex, column) {
    return (["Ошибки", "Ошибки и предупреждения", "Предупреждения", "Нет ошибок и предупреждений", "Проверка не проводилась"])[data];
  },

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

  formatAttachedContentFileType: function(data, rowIndex, column) {
    return (["Двоичный", "Текстовый"])[data];
  },

  formatUserProcedureType: function(data, rowIndex, column) {
    return (["Процедура", "Неименованный блок"])[data];
  },

  formatUserProcedureAuto: function(data, rowIndex, column) {
    return (["Ручной", "Автоматический"])[data];
  },

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

  formatCharset: function(data, rowIndex, column) {
    return (["Windows-1251 (WIN)", "IBM CP866 (OEM)"])[data];
  },

  formatReportStatusSetMode: function(data, rowIndex, column) {
    return (["Начальная установка", "Ручной", "Автоматический"])[data];
  },

  balanceReportsCreateReport: function(catalogTree, grid, kind) {

    var NCRN;
    if (catalogTree.hiddenMode) NCRN = null
    else {

      var path = catalogTree.path;
      NCRN = catalogTree.model.getIdentity(path[path.length - 1]);
    };

    var dialog = new parus.balanceReportDialog({

      title: ((kind == 0) ? "Первичные" : "Сводные") + " отчеты: Добавление",

      _userCalcParams: {
        "NCRN": NCRN,
        "NKIND": kind
      },

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

        dojo.forEach(parus.balance._docprops, function(docprop) {
          var rn = parus.parus8.nodeField(docprop, "RN");
          parus._docPropsValueValueForWidget(
          dialog._docprops[rn], parus.parus8.nodeField(docprop, "VALUE"), parus.parus8.nodeField(docprop, "DATATYPE") == "3" ? "4" : parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));
        });

        dialog.historySelect.attr("value", parus.parus8.optionValue("BalanceUseHistory"));
        dialog.historyLastCheckBox.attr("checked", parus.parus8.optionValue("BalanceOnlyLastHistory") == "1");

        setTimeout(function() {
          parus.balance.executeUserCalcs(parus.balance._masterUserCalcs, true, false, dojo.hitch(dialog, dialog.paramsForUserCalc), dojo.hitch(dialog, dialog.paramsFromUserCalc)

          );
        }, 100);


      }),

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



        (new parus.treeDialog({

          model: parus.balance.catalogTreeStoreModel(),

          key: "BalanceReports",

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

          onSingle: function() {
            if (catalogTree.hiddenMode)

            return parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("singleCatalog", {
              "UNITCODE": "BalanceReports",
              "ACTION_CODE": "BLREPORTS_INSERT"
            }))[0], "CATALOG");

            else {
              var path = catalogTree.path;
              return catalogTree.model.getIdentity(path[path.length - 1]);
            }

          },

          onPerform: function(catalog) {

            response = parus.database.execute("insertReport", {
              CRN: catalog,
              AGENT_CODE: dialog.agentCodeEdit.value,
              AGENT_NAME: dialog.agentNameEdit.value,
              BDATE: dialog.reportDateEdit.value,
              NOTE: dialog.noteEdit.value,
              KIND: kind,
              FORM_CODE: dialog.formCodeEdit.value,
              USE_HISTORY: dialog.historySelect.value,
              ONLY_LAST_HISTORY: (dialog.historyLastCheckBox.checked ? 1 : 0),
              DOCPROPS: dialog.propValues()
            });

            if (response) parus.balance.refreshGrid(grid, "RN", parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));

            dialog.applied = !! response;
            if (dialog.applied) dialog.close();
            return true;
          }

        })).show();

        return false;

      })


    });

    dialog.show();
  },


  balanceReportsDuplicateReport: function(catalogTree, grid, kind) {

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

    var dialog = new parus.balanceReportDialog({

      title: ((kind == 0) ? "Первичные" : "Сводные") + " отчеты: Размножение",

      _agentCodeLoaded: true,

      _agentNameLoaded: true,


      _userCalcParams: {
        "NCRN": store.getValue(item, "CRN"),
        "NKIND": kind,
        "NRN": store.getValue(item, "RN")
      },

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

        dialog.formCodeEdit.attr("value", store.getValue(item, "FORM_CODE"));

        dialog.agentCodeEdit.attr("value", store.getValue(item, "AGNABBR"));

        dialog.agentNameEdit.attr("disabled", false);
        dialog.agentNameEdit.attr("value", store.getValue(item, "AGNNAME"));

        dialog.agentHeadEdit.attr("value", store.getValue(item, "HEAD_ORG_NAME"));

        dialog.reportDateEdit.attr("value", store.getValue(item, "BDATE"));
        dialog._dateIsSet = true;

        dialog.noteEdit.attr("value", store.getValue(item, "NOTE", ""));

        dialog.historySelect.attr("value", store.getValue(item, "USE_HISTORY"));
        dialog.historyLastCheckBox.attr("checked", store.getValue(item, "ONLY_LAST_HISTORY") == "1");


        dojo.forEach(parus.balance._docprops, function(docprop) {
          var rn = parus.parus8.nodeField(docprop, "RN");
          parus._docPropsValueValueForWidget(
          dialog._docprops[rn], parus.parus8.nodeField(docprop, "DUPLICATE_VALUE") == "1" ? parus.parus8.docPropValue(item, rn) || parus.parus8.nodeField(docprop, "VALUE") : parus.parus8.nodeField(docprop, "VALUE"), parus.parus8.nodeField(docprop, "DATATYPE") == "3" ? "4" : parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));
        });


        setTimeout(function() {
          parus.balance.executeUserCalcs(parus.balance._masterUserCalcs, true, false, dojo.hitch(dialog, dialog.paramsForUserCalc), dojo.hitch(dialog, dialog.paramsFromUserCalc)

          );
        }, 100);


      }),

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

        var path = catalogTree.path;

        response = parus.database.execute("duplicateReport", {
          RN: store.getValue(item, "RN"),
          CRN: store.getValue(item, "CRN"),
          AGENT_CODE: dialog.agentCodeEdit.value,
          AGENT_NAME: dialog.agentNameEdit.value,
          BDATE: dialog.reportDateEdit.value,
          NOTE: dialog.noteEdit.value,
          KIND: kind,
          FORM_CODE: dialog.formCodeEdit.value,
          USE_HISTORY: dialog.historySelect.value,
          ONLY_LAST_HISTORY: (dialog.historyLastCheckBox.checked ? 1 : 0),
          DOCPROPS: dialog.propValues()

        });

        if (!response) return false;

        this.refreshGrid(grid, "RN", parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));

        return true;
      })

    });

    dialog.show();


  },

  balanceReportsEditReport: function(grid, kind) {

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

    var dialog = new parus.balanceReportDialog({

      title: ((kind == 0) ? "Первичные" : "Сводные") + " отчеты: Исправление",

      _agentCodeLoaded: true,

      _agentNameLoaded: true,

      _userCalcParams: {
        "NCRN": store.getValue(item, "CRN"),
        "NKIND": kind,
        "NRN": store.getValue(item, "RN")
      },


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

        dialog.formCodeEdit.attr("value", store.getValue(item, "FORM_CODE"));

        dialog.agentCodeEdit.attr("value", store.getValue(item, "AGNABBR"));

        dialog.agentNameEdit.attr("disabled", false);
        dialog.agentNameEdit.attr("value", store.getValue(item, "AGNNAME"));

        dialog.agentHeadEdit.attr("value", store.getValue(item, "HEAD_ORG_NAME"));

        dialog.reportDateEdit.attr("value", store.getValue(item, "BDATE"));
        dialog._dateIsSet = true;

        dialog.noteEdit.attr("value", store.getValue(item, "NOTE", ""));


        dialog.historySelect.attr("value", store.getValue(item, "USE_HISTORY"));
        dialog.historyLastCheckBox.attr("checked", store.getValue(item, "ONLY_LAST_HISTORY") == "1");

        dojo.forEach(parus.balance._docprops, function(docprop) {
          var rn = parus.parus8.nodeField(docprop, "RN");
          parus._docPropsValueValueForWidget(
          dialog._docprops[rn], parus.parus8.docPropValue(item, rn), parus.parus8.nodeField(docprop, "DATATYPE") == "3" ? "4" : parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));
        });

        setTimeout(function() {
          parus.balance.executeUserCalcs(parus.balance._masterUserCalcs, false, true, dojo.hitch(dialog, dialog.paramsForUserCalc), dojo.hitch(dialog, dialog.paramsFromUserCalc)

          );
        }, 100);


      }),

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

        response = parus.database.execute("editReport", {
          RN: store.getValue(item, "RN"),
          AGENT_CODE: dialog.agentCodeEdit.value,
          AGENT_NAME: dialog.agentNameEdit.value,
          BDATE: dialog.reportDateEdit.value,
          NOTE: dialog.noteEdit.value,
          KIND: kind,
          FORM_CODE: dialog.formCodeEdit.value,
          USE_HISTORY: dialog.historySelect.value,
          ONLY_LAST_HISTORY: (dialog.historyLastCheckBox.checked ? 1 : 0),
          DOCPROPS: dialog.propValues()

        });

        if (!response) return false;

        this.refreshGrid(grid, "RN", store.getValue(item, "RN"));

        return true;
      })

    });

    dialog.show();


  },

  balanceReportsMoveReport: function(grid) {

    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    (new parus.treeDialog({

      model: parus.balance.catalogTreeStoreModel(),

      key: "BalanceReports",

      onDefaultNeeded: function() {
        var response = parus.database.execute("findAvailableCatalog", {
          UNITCODE: "BalanceReports"
        });
        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("moveReport", {
            RN: store.getValue(item, "RN"),
            CRN: catalog
          });
          item = grid.selection.getNextSelected(item);
        };

        parus.balance.refreshGrid(grid);

        return true;

      }

    })).show();
  },

  balanceReportsDeleteReport: function(grid) {

    (new parus.confirmationDialog({

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

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

        var store = grid.store;
        var item = grid.selection.getFirstSelected();
        for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
          parus.database.execute("deleteReport", {
            RN: store.getValue(item, "RN")
          });
          item = grid.selection.getNextSelected(item);
        };

        grid.selection.deselectAll();
        this.refreshGrid(grid);

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

  },

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

    this.refreshGrid(grid, "RN", grid.store.getValue(item, "RN"));
  },


  primaryBalanceReportsCreateSubReport: function() {

    var grid = parus.balance.primaryDetailGrid;
    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);


    var prn = parus.balance.primaryMasterGrid.store.getValue(
    parus.balance.primaryMasterGrid.getItem(parus.balance.primaryMasterGrid.selection.getSelectedIndex()), "RN");

    var dialog = new parus.balanceSubReportDialog({

      title: "Подотчет: добавление",

      formCode: parus.balance.primaryMasterGrid.store.getValue(
      parus.balance.primaryMasterGrid.getItem(parus.balance.primaryMasterGrid.selection.getSelectedIndex()), "FORM_CODE"),

      edition: parus.balance.primaryMasterGrid.store.getValue(
      parus.balance.primaryMasterGrid.getItem(parus.balance.primaryMasterGrid.selection.getSelectedIndex()), "BLREPFORMED"),

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

        response = parus.database.execute("insertSubReport", {
          PRN: prn,
          CODE: dialog.sectionCodeEdit.value,
          NOTE: dialog.noteEdit.value,
          DOCPROPS: dialog.propValues()
        });

        if (!response) return false;

        this.refreshGrid(grid, "RN", parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));

        return true;
      }),

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

        dojo.forEach(parus.balance._detailDocprops, function(docprop) {
          var rn = parus.parus8.nodeField(docprop, "RN");
          parus._docPropsValueValueForWidget(
          dialog._docprops[rn], parus.parus8.nodeField(docprop, "VALUE"), parus.parus8.nodeField(docprop, "DATATYPE") == "3" ? "4" : parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));
        });

      })


    });

    dialog.show();

  },


  primaryBalanceReportsDuplicateSubReport: function() {


    var grid = parus.balance.primaryDetailGrid;
    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);


    var prn = parus.balance.primaryMasterGrid.store.getValue(
    parus.balance.primaryMasterGrid.getItem(parus.balance.primaryMasterGrid.selection.getSelectedIndex()), "RN");

    var dialog = new parus.balanceSubReportDialog({

      title: "Подотчеты: Размножение",

      formCode: parus.balance.primaryMasterGrid.store.getValue(
      parus.balance.primaryMasterGrid.getItem(parus.balance.primaryMasterGrid.selection.getSelectedIndex()), "FORM_CODE"),

      edition: parus.balance.primaryMasterGrid.store.getValue(
      parus.balance.primaryMasterGrid.getItem(parus.balance.primaryMasterGrid.selection.getSelectedIndex()), "BLREPFORMED"),

      onShow: dojo.hitch(this, function() {
        dialog.sectionCodeEdit.attr("value", store.getValue(item, "CODE"));
        dialog.noteEdit.attr("value", store.getValue(item, "NOTE"));


        dojo.forEach(parus.balance._detailDocprops, function(docprop) {
          var rn = parus.parus8.nodeField(docprop, "RN");
          parus._docPropsValueValueForWidget(
          dialog._docprops[rn], parus.parus8.nodeField(docprop, "DUPLICATE_VALUE") == "1" ? parus.parus8.docPropValue(item, rn) || parus.parus8.nodeField(docprop, "VALUE") : parus.parus8.nodeField(docprop, "VALUE"), parus.parus8.nodeField(docprop, "DATATYPE") == "3" ? "4" : parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));
        });

      }),

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

        response = parus.database.execute("duplicateSubReport", {
          RN: store.getValue(item, "RN"),
          PRN: prn,
          CODE: dialog.sectionCodeEdit.value,
          NOTE: dialog.noteEdit.value,
          DOCPROPS: dialog.propValues()
        });

        if (!response) return false;

        this.refreshGrid(grid, "RN", parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));

        return true;
      })

    });

    dialog.show();


  },


  balanceReportsEditSubReport: function(grid, masterGrid) {

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

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

    var dialog = new parus.balanceSubReportDialog({

      title: "Подотчеты: Исправление",

      formCode: masterGrid.store.getValue(
      masterGrid.getItem(masterGrid.selection.getSelectedIndex()), "FORM_CODE"),

      edition: masterGrid.store.getValue(
      masterGrid.getItem(masterGrid.selection.getSelectedIndex()), "BLREPFORMED"),

      onShow: dojo.hitch(this, function() {
        dialog.sectionCodeEdit.attr("value", store.getValue(item, "CODE"));
        dialog.noteEdit.attr("value", store.getValue(item, "NOTE"));

        dojo.forEach(parus.balance._detailDocprops, function(docprop) {
          var rn = parus.parus8.nodeField(docprop, "RN");
          parus._docPropsValueValueForWidget(
          dialog._docprops[rn], parus.parus8.docPropValue(item, rn), parus.parus8.nodeField(docprop, "DATATYPE") == "3" ? "4" : parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));
        });

      }),

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

        response = parus.database.execute("updateSubReport", {
          RN: rn,
          CODE: dialog.sectionCodeEdit.value,
          NOTE: dialog.noteEdit.value,
          DOCPROPS: dialog.propValues()
        });

        if (!response) return false;

        this.refreshGrid(grid, "RN", rn);

        return true;
      })

    });

    dialog.show();

  },

  balanceReportsDeleteSubReport: function(grid) {

    (new parus.confirmationDialog({

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

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

        var store = grid.store;
        var item = grid.selection.getFirstSelected();
        for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
          parus.database.execute("deleteSubReport", {
            RN: store.getValue(item, "RN")
          });
          item = grid.selection.getNextSelected(item);
        };

        grid.selection.deselectAll();

        this.refreshGrid(grid);

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

  },

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

  consolidatedBalanceReportsConditions: function() {

    var dialog = new parus.balanceReportsConditionsDialog({

      title: "Сводные отчеты: Отбор",

      consolidated: true,

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

        dialog.loadConditions(this._consolidatedConditions);

      }),

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

        this._consolidatedConditions = dialog.saveConditions();

        if (parus.balance._translateConditionsToFilters(this._consolidatedConditions, parus.balance.consolidatedMasterGrid.columnsFilterObject.values)) parus.balance.consolidatedMasterGrid.columnsFilterObject.valuesChanged();

        parus.userdata.set("consolidatedConditions", this._consolidatedConditions, true);

        parus.balance.consolidatedMasterGrid.setQuery(parus.balance.consolidatedMasterGrid.query);
        return true;
      })
    });

    dialog.show();

  },

  balanceReportsCheckValues: function(grid, kind, isSubReport) {

    var rnValues = [];
    var formedRnValues = [];
    var reportValues = [];


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

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      rnValues.push(store.getValue(item, "RN"));
      formedRnValues.push(store.getValue(item, "BLREPFORMED"));

      if (isSubReport) reportValues.push(store.getValue(item, "PRN"))
      else reportValues.push(store.getValue(item, "RN"));

      item = grid.selection.getNextSelected(item);
    };

    if (rnValues.length == 0) return;

    var dialog = new parus.balanceCheckReportDialog({
      grid: grid,
      kind: kind,
      isSubReport: isSubReport,
      rn: rnValues,
      formedRn: formedRnValues,
      reportRn: reportValues,
      title: ((kind == 0) ? "Первичные" : "Сводные") + " отчеты: Параметры проверки"
    });

    dialog.show();
  },

  _createHeadingPane: function(title) {

    var headingContentPane = dijit.layout.BorderContainer({
      design: "sidebar",
      gutters: false,
      region: "top",
      "class": "balanceHeadingPane"
    });

    headingContentPane.addChild(
    dijit.layout.ContentPane({
      region: "left",
      "class": "balanceHeadingPaneTitle",
      style: "margin:5px;",
      content: title
    }));

    var barPane = dijit.layout.ContentPane({
      region: "center",
      style: "margin:1px;overflow:hidden"
    });

    barPane.domNode.align = "right";


    headingContentPane.addChild(
    dijit.layout.ContentPane({
      region: "right"
    }));

    headingContentPane.addChild(barPane);

    return headingContentPane;
  },

  showReportValues: function(report, subreport, date, formcode, agentcode, section, template, direction, kind, agent, onDone) {
    if (!template) return;

    var contentPane;

    var borderContainer = new dijit.layout.BorderContainer({
      design: "headline",
      gutters: false,
      "class": "balanceTemplateContentPane",
      region: "center",
      style: "height:100%;width:100%;padding:0"
    });


    var title = parus.balance.describeReport(report, subreport, template, null, null, null, null, 0);

    var headingContentPane = parus.balance._createHeadingPane(title);

    borderContainer.addChild(headingContentPane);

    var templateGridPane = new parus.templateGridPane({
      region: "center",
      report: report,
      subreport: subreport,
      template: template,
      direction: direction,
      kind: kind,
      reportDate: date,
      formCode: formcode,
      agent: agent,
      headingContentPane: headingContentPane,
      onDone: onDone,
      onModified: function() {
        if (contentPane.controlButton) {
          var list = dojo.query("*", contentPane.controlButton.containerNode);
          list.removeClass("balanceReadOnlyHeader");
          list.removeClass("balanceModifiedHeader");
          if (templateGridPane.readonly) list.addClass("balanceReadOnlyHeader");
          else if (templateGridPane.modified) list.addClass("balanceModifiedHeader");
        }

        if (parus.parus8._embeddedMode) {
          parus.embeddedMode.changeTabState(templateGridPane.modified);
        }
      },
      onTitleChanged: function() {
        if (templateGridPane.title) {
          var title = parus.balance.formatPageTitle(templateGridPane.title);

          contentPane.attr("title", title);

          if (parus.parus8._embeddedMode) {
            parus.embeddedMode.changeTabTitle(title);
          }
        }
      }

    });

    borderContainer.addChild(templateGridPane);

    contentPane = new dijit.layout.ContentPane({
      title: parus.balance.formatPageTitle(title),
      closable: true,
      region: "center",
      "class": "balanceTemplateContentPane",
      onClose: dojo.hitch(templateGridPane, templateGridPane.onClose)
    });

    templateGridPane.parentPane = contentPane;

    contentPane.setContent(borderContainer);

    if (parus.balance.TabContainer) {
      parus.balance.TabContainer.addChild(contentPane);
      parus.balance.TabContainer.selectChild(contentPane);
    }
    return contentPane;

  },

  executeEditValues: function(report, subreport, date, formCode, agentCode, sectionCode, kind, agent, onDone) {

    if (!parus.balance.TabContainer || parus.parus8._embeddedMode) {

      if (parus.parus8._themeEditorMode) {
        alert("В режиме редактирования схемы это действие невозможно.");
        return;
      }

      var url = dojo.moduleUrl("parus", "report.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([report, subreport /*, widget.templateRN */ ]);

      if (parus.parus8._embeddedMode) {
        var id = [report, subreport, (+(new Date))].join("_");
        parus.embeddedMode.openTab(id, "Исправление значений отчета", url);
      } else {
        window.open(url, "_blank");
      }

      parus.parus8.registerAction();

      return;
    }


    parus.database.query("BalanceReportTemplates", {
      "REPORT": report
    }, dojo.hitch(this, function(response) {

      var templates = parus.parus8.rowNodes(response);
      if (templates.length == 0) {
        parus.parus8.errorMessage("Трафареты для редактирования значений отсутствуют или недоступны.");
        return;
      };

      var template;
      var direction;


      if (templates.length == 1) {
        template = parus.parus8.nodeField(templates[0], "RN");
        direction = parus.parus8.nodeField(templates[0], "DIRECT_TABLE");
      }
      else dojo.forEach(templates, function(templateNode) {
        if (parus.parus8.nodeField(templateNode, "EDIT_DEFAULT") == "1") {
          template = parus.parus8.nodeField(templateNode, "RN");
          direction = parus.parus8.nodeField(templateNode, "DIRECT_TABLE");
        }
      });


      if (template) parus.balance.showReportValues(report, subreport, date, formCode, agentCode, sectionCode, template, direction, kind, agent, onDone)
      else {

        var dialog = new parus.balanceTemplatesDialog({

          templates: templates,

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

            dojo.forEach(dialog.templatesGrid.selection.getSelected(), function(item) {
              template = dialog.templatesGrid.store.getValue(item, "RN", "");
              direction = dialog.templatesGrid.store.getValue(item, "DIRECT_TABLE", "")
            });

            if (!template) return false;

            this.showReportValues(report, subreport, date, formCode, agentCode, sectionCode, template, direction, kind, agent, onDone);

            return true;
          })


        });
        dialog.show();
      }

    }));



  },


  editReportValues: function(grid, kind) {

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

    this.executeEditValues(
    store.getValue(item, "RN"), null, store.getValue(item, "BDATE"), store.getValue(item, "FORM_CODE"), store.getValue(item, "AGNABBR"), null, kind, store.getValue(item, "AGENT"));
  },

  editSubReportValues: function(grid, mastergrid, kind) {


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

    var masterstore = mastergrid.store;
    var masterindex = mastergrid.selection.getSelectedIndex();
    var masteritem = mastergrid.getItem(masterindex);


    this.executeEditValues(
    store.getValue(item, "PRN"), store.getValue(item, "RN"), masterstore.getValue(masteritem, "BDATE"), masterstore.getValue(masteritem, "FORM_CODE"), masterstore.getValue(masteritem, "AGNABBR"), store.getValue(item, "CODE"), kind, masterstore.getValue(masteritem, "AGENT"));
  },



  downloadExcelWorkBook: function(unitcode, report, subreport, template, extension, colormode) {

    if (parus.parus8._themeEditorMode) {
      alert("В режиме редактирования схемы это действие невозможно.");
      return;
    }

    var f = function(extension, colormode, save, keepOtherSheets, template) {

      if (save) {
        var progressIndicator = new parus.progressDialog({
          message: "Выполняется сохранение отчетов"
        });

        progressIndicator.show();

        parus.database._xhr("savereport.xml", null, {
          unitcode: unitcode,
          report: (report) ? (dojo.isArray(report) ? report.join(";") : report) : "",
          subreport: (subreport) ? (dojo.isArray(subreport) ? subreport.join(";") : subreport) : "",
          template: (template) ? template : "",
          extension: extension,
          colormode: colormode,
          othersheets: keepOtherSheets ? "1" : "0"
        }, function(response) {
          progressIndicator.close();
          progressIndicator.destroyRecursive();

          if (response.documentElement.nodeName != "error") {
            parus.parus8.notificationMessage("Отчеты успешно сохранены.");
          }
        });
      }
      else {

        var form = document.createElement("form");
        form.method = "POST";
        form.action = parus.database.getReportExcelUrl(extension);
        //if (!dojo.isChrome || (extension == "html"))
        if (!parus.parus8._embeddedMode) form.target = "_blank";

        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "report";
        input.value = (report) ? (dojo.isArray(report) ? report.join(";") : report) : "";
        form.appendChild(input);

        input = document.createElement("input");
        input.type = "hidden";
        input.name = "subreport";
        input.value = (subreport) ? (dojo.isArray(subreport) ? subreport.join(";") : subreport) : "";
        form.appendChild(input);

        input = document.createElement("input");
        input.type = "hidden";
        input.name = "template";
        input.value = (template) ? template : "";
        form.appendChild(input);

        input = document.createElement("input");
        input.type = "hidden";
        input.name = "colormode";
        input.value = colormode;
        form.appendChild(input);

        input = document.createElement("input");
        input.type = "hidden";
        input.name = "othersheets";
        input.value = keepOtherSheets ? "1" : "0";
        form.appendChild(input);

        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
      }
    };

    if (extension == "xls") {
      (new parus.excelFileFormatDialog({
        allowSave: true,
        allowTypeSelect: (!template || template == "*"),
        onApply: function() {
          f(this.formatEdit.value, colormode, this.saveCheckBox.checked, this.otherSheetsCheckBox.checked, this.allowTypeSelect ? this.typeEdit.attr("value") : template);
          return true;
        }
      })).show();
    }
    else if (extension == "pdf" || extension == "html") {
      (new parus.excelColorModeDialog({
        allowSave: true,
        allowTypeSelect: (!template || template == "*"),
        onApply: function() {
          f(extension, this.colorModeEdit.value, this.saveCheckBox.checked, this.otherSheetsCheckBox.checked, this.allowTypeSelect ? this.typeEdit.attr("value") : template);
          return true;
        }
      })).show();
    }
    else f(extension, colormode, false, false, template);
  },

  downloadExcelReport: function(grid, extension, colormode) {
    var store = grid.store;

    if (grid.selection.getSelectedCount() == 1) {
      var index = grid.selection.getSelectedIndex();
      var item = grid.getItem(index);
      this.downloadExcelWorkBook("BalanceReports", store.getValue(item, "RN"), "*", null, extension, colormode);
    }
    else if (grid.selection.getSelectedCount() > 1) {

      var rns = [];
      var edition = "";
      var item = grid.selection.getFirstSelected();
      var template = null;

      for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
        if (!edition) edition = store.getValue(item, "BLREPFORMED");
        else if (edition != store.getValue(item, "BLREPFORMED")) template = "*";

        rns.push(store.getValue(item, "RN"));
        item = grid.selection.getNextSelected(item);
      };

      this.downloadExcelWorkBook("BalanceReports", rns, "*", template, extension, colormode);
    }

  },

  downloadExcelSubReport: function(grid, mastergrid, extension, colormode) {
    var store = grid.store;

    if (grid.selection.getSelectedCount() == 1) {
      var index = grid.selection.getSelectedIndex();
      var item = grid.getItem(index);
      this.downloadExcelWorkBook("BalanceSubReports", store.getValue(item, "PRN"), store.getValue(item, "RN"), null, extension, colormode);
    }
    else if (grid.selection.getSelectedCount() > 1) {

      var rns = [];
      var prn = "";
      var item = grid.selection.getFirstSelected();

      for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
        if (!prn) prn = store.getValue(item, "PRN");
        rns.push(store.getValue(item, "RN"));
        item = grid.selection.getNextSelected(item);
      };

      this.downloadExcelWorkBook("BalanceSubReports", prn, rns, null, extension, colormode);
    }

  },

  downloadReport: function(grid) {

    if (parus.parus8._themeEditorMode) {
      alert("В режиме редактирования схемы это действие невозможно.");
      return;
    }

    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var reports = [];

    var colindex = -1;
    dojo.forEach(grid.views.views[0].structure.cells[0], dojo.hitch(this, function(column, idx) {
      if (column.field == "SENT") colindex = idx;
    }));

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      reports.push(store.getValue(item, "RN"));
      item = grid.selection.getNextSelected(item);
    };

    if (!reports.length) return;


    var response = parus.database._xhr("report.xml", null, {
      REPORTS: reports.join(";")
    });


    if (response) {

      var item = grid.selection.getFirstSelected();
      for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
        var node = grid.views.views[0].getCellNode(grid.getItemIndex(item), colindex);
        if (node) node.innerHTML = parus.parus8.formatBoolean(1);
        if (!dojo.isIE) item._fieldsMap["SENT"] = 1;
        item = grid.selection.getNextSelected(item);
      };

      var form = document.createElement("form");
      form.method = "GET";
      form.action = parus.database.getReportXmlDataUrl();
      //if (!dojo.isChrome)
      if (!parus.parus8._embeddedMode) form.target = "_blank";

      document.body.appendChild(form);
      form.submit();
      document.body.removeChild(form);

    }
  },

  balanceReportsLoadReports: function(grid, catalogTree, kind) {

    var dialog = new parus.balanceLoadReportsDialog({

      kind: kind,

      catalogTree: catalogTree,

      onApply: dojo.hitch(this, function() {
        this.refreshGrid(grid, "RN", grid.store.getValue(grid.selection.getFirstSelected(), "RN"));
        return true;
      })

    });

    dialog.show();
  },


  balanceReportsCustomFormatLoadReports: function(grid, catalogTree, kind) {

    var dialog = new parus.balanceCustomLoadReportsDialog({

      kind: kind,

      catalogTree: catalogTree,

      onApply: dojo.hitch(this, function() {
        if (dialog.showReport.attr("value") == "0") this.refreshGrid(grid, "RN", grid.store.getValue(grid.selection.getFirstSelected(), "RN"));
        return true;
      })

    });

    dialog.show();

  },

  showHelp: function(dialogClass) {
    var helpWindow = window.open(parus.database.getHelpUrl() + "balance/m_po_1077.htm", "parus8balancehelp");
    helpWindow.document.title = document.title + " (Справка)";
    parus.parus8.registerAction();
  },

  formatAttrValue: function(data, rowIndex, column) {
    var item = column.grid.getItem(rowIndex);
    return parus._docPropsValueForGrid(
    parus.parus8.docAttrValue(item, column.attrRN), column.dataType, column.dataSubType);
  },

  formatDocPropValue: function(data, rowIndex, column) {
    var item = column.grid.getItem(rowIndex);
    return parus._docPropsValueForGrid(
    parus.parus8.docPropValue(item, column.propRN), column.dataType, column.dataSubType);
  },

  executeUserProc: function(userproc, rn, unitcode, paramValues) {


    var _done = function() {

      parus.database.execute("executeUserProcedure", {
        "RN": rn,
        "USERPROC": userproc,
        "UNITCODE": unitcode,
        "PARAMS": {
          "PARAMS": paramValues
        }
      }, function(response) {


        var text = "";

        if (response.documentElement.childNodes[0].childNodes[0].childNodes.length) dojo.forEach(parus.parus8.rowNodes(response.documentElement.childNodes[0].childNodes[0].childNodes[0]), function(param) {
          if (parus.parus8.nodeField(param, "VISUALIZE") == "1") text = text + "<div><b>" + parus.parus8.nodeField(param, "NAME") + ":</b>" + String.fromCharCode(160) + "<b style='color:black'>" + parus.parus8.nodeField(param, "VALUE") + "</b></div>";
        });

        if (text) parus.parus8.notificationMessage("<div>Пользовательская процедура выполнена.</div>" + text);

      });

    };


    var files = [];

    for (var key in paramValues) {
      var it = paramValues[key];

      if (dojo.isObject(it)) {
        files.push({
          input: it.domNode,
          key: key,
          type: it.type
        });
        delete paramValues[key];
      };
    };

    if (files.length) {

      var i = files.length - 1;
      parus.database.toBuffer(files[i].input, files[i].type, null, function(r) {
        paramValues[files[i].key] = r;
        i--;
        if (i >= 0) parus.database.toBuffer(files[i].input, files[i].type, null, arguments.callee)
        else _done();
      });

    }
    else _done();

  },


  userProcedure: function(grid, unitcode, userproc, confirmText, perRecord, perSelection) {

    var execute = dojo.hitch(this, function() {


      var paramsDialog = new parus.balanceUserProcParamsDialog({

        useSavedValues: parus.parus8.optionValue("StoreUserProcsParams") != "0",

        userproc: userproc,

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

          if (perSelection) {
            var store = grid.store;
            var item = grid.selection.getFirstSelected();
            var rns = [];
            for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
              rns.push(store.getValue(item, "RN"));
              item = grid.selection.getNextSelected(item);
            };
            this.executeUserProc(userproc, rns.join(";"), unitcode, paramsDialog.paramValues());
          } else if (perRecord) {
            var store = grid.store;
            var item = grid.selection.getFirstSelected();
            if (!item) {
              parus.parus8.errorMessage("Регистрационный номер записи не определен.");
              return true;
            }
            for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
              this.executeUserProc(userproc, store.getValue(item, "RN"), unitcode, paramsDialog.paramValues());
              item = grid.selection.getNextSelected(item);
            };
          }
          else this.executeUserProc(userproc, null, unitcode, paramsDialog.paramValues());

          this.refreshGrid(grid);
          return true;
        })
      });
      paramsDialog.show();

    });



    if (confirmText) {
      (new parus.confirmationDialog({
        message: confirmText,
        onApply: function() {
          execute();
          return true;
        }
      })).show();
    }
    else execute();



  },

  parseUserApplicationResponse: function(response) {

    var messages = (response.documentElement.nodeName == "error") ? [] : dojo.map(dojo.filter(parus.parus8.rowNodes(response), function(node) {
      return (node.nodeName == "message");
    }), function(message) {
      return message.firstChild ? message.firstChild.nodeValue : "<br/>";
    });

    if (response.documentElement.nodeName != "error") dojo.forEach(parus.parus8.rowNodes(response), function(node) {
      if (node.nodeName == "response") {
        if (parus.parus8.nodeField(node, "handleAs") == "json") {
          var obj = dojo.fromJson(parus.parus8.nodeField(node, "data")) || {};
          if (obj.startup) obj.startup();
        }
      }
    });

    if (messages.length) parus.parus8.notificationMessage(messages.join("<br/>"));

  },

  executeUserApplication: function(userApplication, rn, unitcode, paramValues, parentUnitCode, parentRn, catalog, done) {

    var _done = function() {


      var progressIndicator = new parus.progressDialog({
        message: "Выполняется пользовательское приложение"
      });

      progressIndicator.show();

      parus.database._xhr("userApplication.xml", null, {
        "RN": rn,
        "USERAPP": userApplication,
        "UNITCODE": unitcode,
        "PARAMS": {
          "PARAMS": paramValues
        },
        "PARENTUNITCODE": parentUnitCode,
        "PARENTRN": parentRn,
        "CATALOGRN": catalog
      }, function(response) {

        progressIndicator.close();
        progressIndicator.destroyRecursive();

        parus.balance.parseUserApplicationResponse(response);

        if (done) done();

      });

    };


    var files = [];

    for (var key in paramValues) {
      var it = paramValues[key];

      if (dojo.isObject(it)) {
        files.push({
          input: it.domNode,
          key: key,
          type: it.type
        });
        delete paramValues[key];
      };
    };

    if (files.length) {

      var i = files.length - 1;
      parus.database.toBuffer(files[i].input, files[i].type, null, function(r) {
        paramValues[files[i].key] = r;
        i--;
        if (i >= 0) parus.database.toBuffer(files[i].input, files[i].type, null, arguments.callee)
        else _done();
      });

    }
    else _done();

  },

  userApplication: function(grid, unitcode, userapp, groupRecords) {


    var paramsDialog = new parus.balanceUserProcParamsDialog({

      userproc: userapp,

      queryid: "userAppParams",

      title: "Параметры пользовательского приложения",

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

        if (groupRecords) {
          var store = grid.store;
          var item = grid.selection.getFirstSelected();
          var rns = [];
          for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
            rns.push(store.getValue(item, "RN"));
            item = grid.selection.getNextSelected(item);
          };
          this.executeUserApplication(userapp, rns.join(";"), unitcode, paramsDialog.paramValues(), grid.store.parentUnitCode, grid.store.parentRN, grid.store.catalogRN, function() {
            parus.balance.refreshGrid(grid)
          });

        } else {
          var store = grid.store;
          var item = grid.selection.getFirstSelected();
          if (!item) {

            this.executeUserApplication(userapp, null, unitcode, paramsDialog.paramValues(), grid.store.parentUnitCode, grid.store.parentRN, grid.store.catalogRN, function() {
              parus.balance.refreshGrid(grid)
            });

          }
          else {
            var rns = [];
            for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
              rns.push(store.getValue(item, "RN"));
              item = grid.selection.getNextSelected(item);
            };

            dojo.forEach(rns, dojo.hitch(this, function(rn, idx) {
              this.executeUserApplication(userapp, rn, unitcode, paramsDialog.paramValues(), grid.store.parentUnitCode, grid.store.parentRN, grid.store.catalogRN, (idx == (rns.length - 1)) ?
              function() {
                parus.balance.refreshGrid(grid)
              } : null);
            }));
          };
        };

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

  },

  userApplications: function(grid, unitcode) {


    var dialog = new parus.balanceUserProcsDialog({
      unitcode: unitcode,

      queryid: "userApps",

      title: "Выбор пользовательского приложения",

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


        var userapp;
        var groupRecords = false;

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userapp = dialog.userProcsGrid.store.getValue(item, "RN", "");
          groupRecords = (dialog.userProcsGrid.store.getValue(item, "GROUP_RECORDS", "") != "0");
        });

        if (!userapp) return false;
        this.userApplication(grid, unitcode, userapp, groupRecords);
        return true;
      })
    });

    dialog.show();
  },

  userProcedures: function(grid, unitcode) {

    var dialog = new parus.balanceUserProcsDialog({
      unitcode: unitcode,

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

        var userproc;
        var confirmText = "";
        var perRecord = false;
        var perSelection = false;

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userproc = dialog.userProcsGrid.store.getValue(item, "RN", "");
          confirmText = dialog.userProcsGrid.store.getValue(item, "CONFIRM_TEXT", "");
          perRecord = (dialog.userProcsGrid.store.getValue(item, "PERRECORD", "") != "0");
          perSelection = (dialog.userProcsGrid.store.getValue(item, "PERSELECTION", "") != "0");
        });

        if (!userproc) return false;
        this.userProcedure(grid, unitcode, userproc, confirmText, perRecord, perSelection);
        return true;
      })



    });

    dialog.show();

  },


  downloadUserReport: function(userreport, rn, unitcode, paramValues, userreportTitle) {

    if (parus.parus8._themeEditorMode) {
      alert("В режиме редактирования схемы это действие невозможно.");
      return;
    }


    parus.database._xhr("userreport.xml", null, {
      rn: rn,
      unitcode: unitcode,
      userreport: userreport,
      params: parus.xml.toXml({
        "PARAMS": paramValues
      })
    },

    function(response) {

      if (response.documentElement.nodeName != "error") {

        var form = document.createElement("form");
        form.method = "POST";
        form.action = parus.database.getUserReportDataUrl();
        //if (!dojo.isChrome)
        form.target = "_blank";
        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);

      }
    }

    );

  },

  executeUserReport: function(userreport, rn, unitcode, paramValues, userreportTitle) {

    if (parus.parus8._embeddedMode || !parus.balance.TabContainer) {

      var params = [userreport, rn, unitcode, userreportTitle];
      for (var key in paramValues) {
        params.push(key);
        params.push(dojo.isArray(paramValues[key]) ? paramValues[key].join(";") : paramValues[key]);
      }

      var url = dojo.moduleUrl("parus", "userReport.html").toString() + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams(params);

      if (parus.parus8._embeddedMode) {
        var id = ["userreport", userreport, rn, unitcode].join("_");
        parus.embeddedMode.openTab(id, "Пользовательский отчет \"" + userreportTitle + "\"", url);
      } else {
        window.open(url, "_blank");
      }

      parus.parus8.registerAction();

    }
    else {

      var contentPane;

      var borderContainer = new dijit.layout.BorderContainer({
        design: "headline",
        "class": "balanceTemplateContentPane",
        gutters: false,
        style: "height:100%;width:100%;padding:0"
      });

      var headingContentPane = parus.balance._createHeadingPane("Пользовательский отчет \"" + userreportTitle + "\"");

      borderContainer.addChild(headingContentPane);

      var templateGridPane = new parus.userReportPane({
        region: "center",
        userreport: userreport,
        rn: rn,
        unitcode: unitcode,
        paramValues: paramValues,
        returnToPane: parus.balance.TabContainer.selectedChildWidget,
        headingContentPane: headingContentPane
      });

      borderContainer.addChild(templateGridPane);

      contentPane = new dijit.layout.ContentPane({
        title: parus.balance.formatPageTitle("Пользовательский отчет" + "<br/>\"" + userreportTitle + "\""),
        closable: true,
        "class": "balanceTemplateContentPane",
        onClose: dojo.hitch(templateGridPane, templateGridPane.onClose)
      });

      templateGridPane.parentPane = contentPane;

      contentPane.setContent(borderContainer);

      parus.balance.TabContainer.addChild(contentPane);
      parus.balance.TabContainer.selectChild(contentPane);

    }

  },

  userReport: function(grid, unitcode, userrep, userreptitle, userreporttype) {


    var store = grid.store;
    var item = grid.selection.getFirstSelected();
    var rns = [];
    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      rns.push(store.getValue(item, "RN"));
      item = grid.selection.getNextSelected(item);
    };

    var paramsDialog = new parus.balanceUserReportParamsDialog({

      userproc: userrep,

      unitcode: unitcode,

      rns: rns.join(";"),

      userreporttype: userreporttype,

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

        if (userreporttype == "4") this.downloadUserReport(userrep, rns.join(";"), unitcode, dojo.clone(paramsDialog.paramValues()), userreptitle);
        else this.executeUserReport(userrep, rns.join(";"), unitcode, dojo.clone(paramsDialog.paramValues()), userreptitle);

        return true;
      })

    });
    paramsDialog.show();

  },

  userReports: function(grid, unitcode) {

    var dialog = new parus.balanceUserProcsDialog({
      unitcode: unitcode,

      queryid: "userReports",

      title: "Выбор пользовательского отчета",

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

        var userrep;
        var userreptitle = "";
        var userreporttype = "1";

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userrep = dialog.userProcsGrid.store.getValue(item, "RN", "");
          userreptitle = dialog.userProcsGrid.store.getValue(item, "NAME", "");
          userreporttype = dialog.userProcsGrid.store.getValue(item, "REPORT_TYPE", "1");
        });

        if (!userrep) return false;
        this.userReport(grid, unitcode, userrep, userreptitle, userreporttype);
        return true;

      })
    });

    dialog.show();

  },

  downloadAttachedFile: function(rn) {

    if (parus.parus8._themeEditorMode) {
      alert("В режиме редактирования схемы это действие невозможно.");
      return;
    }

    var form = document.createElement("form");
    form.method = "GET";
    form.action = parus.database.getDownloadAttachedDocumentUrl();
    //if (!dojo.isChrome)
    form.target = "_blank";

    var input = document.createElement("input");
    input.type = "hidden";
    input.name = "rn";
    input.value = rn;
    form.appendChild(input);

    document.body.appendChild(form);
    try {
      form.submit();
    }
    finally {
      document.body.removeChild(form);
    };
  },

  formatAttachedFileName: function(data, rowIndex, column) {
    return "<a href='javascript:parus.balance.downloadAttachedFile(" + column.grid.store.getValue(column.grid.getItem(rowIndex), "RN") + ")'>" + data + "</a>";
  },

  balanceReportsCustomFormatDownloadReports: function(kind) {
    (new parus.balanceCustomDownloadReportsDialog({
      kind: kind
    })).show();
  },

  showConsolidationProposal: function() {

    var store = parus.balance.consolidatedMasterGrid.store;
    var index = parus.balance.consolidatedMasterGrid.selection.getSelectedIndex();
    var item = parus.balance.consolidatedMasterGrid.getItem(index);

    var dictionaryInfo = dojo.clone(parus.dictionaries["ConsolidationProposal"]);

    var dialog;

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


    menu.addChild(new dijit.MenuItem({
      label: "Добавить...",
      defaultIcon: "PCHardwareadaltCustomIcon",
      onClick: dojo.hitch(this, function() {

        var intdialog = new parus.balanceConsolidatedReportDialog({
          onShow: function() {
            intdialog.formCodeEdit.attr("value", store.getValue(item, "FORM_CODE"));
            intdialog.reportDateEdit.attr("value", dojo.date.locale.parse(
            store.getValue(item, "BDATE"), {
              datePattern: "dd.MM.yyyy",
              selector: "date"
            }));
          },

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

            response = parus.database.execute("insertConsolidationProposal", {
              PRN: store.getValue(item, "RN"),
              AGENT_CODE: intdialog.agentCodeEdit.value,
              AGENT_NAME: intdialog.agentNameEdit.value,
              KIND: intdialog.kindSelect.value
            });

            if (!response) return false;

            this.refreshGrid(dialog.grid, "RN", parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));

            return true;

          })

        });

        intdialog.show();

      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Исправить...",
      defaultIcon: "PCdocumentCustomIcon",
      itemAction: true,
      onClick: dojo.hitch(this, function() {

        var intstore = dialog.grid.store;
        var intindex = dialog.grid.selection.getSelectedIndex();
        var intitem = dialog.grid.getItem(intindex);

        var intdialog = new parus.balanceConsolidatedReportDialog({
          _agentCodeLoaded: true,

          _agentNameLoaded: true,

          onShow: function() {

            intdialog.formCodeEdit.attr("value", store.getValue(item, "FORM_CODE"));
            intdialog.reportDateEdit.attr("value", dojo.date.locale.parse(
            store.getValue(item, "BDATE"), {
              datePattern: "dd.MM.yyyy",
              selector: "date"
            }));


            intdialog.agentCodeEdit.attr("value", intstore.getValue(intitem, "AGNABBR"));
            intdialog.agentNameEdit.attr("disabled", false);
            intdialog.agentNameEdit.attr("value", intstore.getValue(intitem, "AGNNAME"));
            intdialog.agentHeadEdit.attr("value", intstore.getValue(intitem, "HEAD_ORG_NAME"));

            intdialog.kindSelect.attr("value", intstore.getValue(intitem, "KIND"));
          },

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

            response = parus.database.execute("updateConsolidationProposal", {
              RN: intstore.getValue(intitem, "RN"),
              AGENT_CODE: intdialog.agentCodeEdit.value,
              AGENT_NAME: intdialog.agentNameEdit.value,
              KIND: intdialog.kindSelect.value
            });

            if (!response) return false;

            this.refreshGrid(dialog.grid, "RN", intstore.getValue(intitem, "RN"));

            return true;

          })

        });

        intdialog.show();


      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Размножить...",
      defaultIcon: "PCcopyCustomIcon",
      itemAction: true,
      onClick: dojo.hitch(this, function() {



        var intstore = dialog.grid.store;
        var intindex = dialog.grid.selection.getSelectedIndex();
        var intitem = dialog.grid.getItem(intindex);

        var intdialog = new parus.balanceConsolidatedReportDialog({
          _agentCodeLoaded: true,

          _agentNameLoaded: true,

          onShow: function() {

            intdialog.formCodeEdit.attr("value", store.getValue(item, "FORM_CODE"));
            intdialog.reportDateEdit.attr("value", dojo.date.locale.parse(
            store.getValue(item, "BDATE"), {
              datePattern: "dd.MM.yyyy",
              selector: "date"
            }));


            intdialog.agentCodeEdit.attr("value", intstore.getValue(intitem, "AGNABBR"));
            intdialog.agentNameEdit.attr("disabled", false);
            intdialog.agentNameEdit.attr("value", intstore.getValue(intitem, "AGNNAME"));
            intdialog.agentHeadEdit.attr("value", intstore.getValue(intitem, "HEAD_ORG_NAME"));

            intdialog.kindSelect.attr("value", intstore.getValue(intitem, "KIND"));
          },

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

            response = parus.database.execute("insertConsolidationProposal", {
              PRN: store.getValue(item, "RN"),
              AGENT_CODE: intdialog.agentCodeEdit.value,
              AGENT_NAME: intdialog.agentNameEdit.value,
              KIND: intdialog.kindSelect.value
            });

            if (!response) return false;

            this.refreshGrid(dialog.grid, "RN", parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));

            return true;

          })

        });

        intdialog.show();

      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Удалить...",
      defaultIcon: "PCreduceCustomIcon",
      itemAction: true,
      onClick: dojo.hitch(this, function() {


        (new parus.confirmationDialog({

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

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

            var store = dialog.grid.store;
            var item = dialog.grid.selection.getFirstSelected();
            for (var i = 0; i < dialog.grid.selection.getSelectedCount(); i++) {
              parus.database.execute("deleteConsolidationProposal", {
                RN: store.getValue(item, "RN")
              });
              item = dialog.grid.selection.getNextSelected(item);
            };

            this.refreshGrid(dialog.grid);

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




      })
    }));

    menu.startup();

    dojo.mixin(dictionaryInfo, {
      menu: menu,
      dictionary: dictionaryInfo,
      multiselect: true,
      gridConditions: {
        REPORT: store.getValue(item, "RN")
      },
      hideCancel: true
    });

    dialog = new parus.dictionaryDialog(dictionaryInfo);

    dialog.show();

  },


  exportToFile: function(grid) {

    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var reports = [];

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      reports.push(store.getValue(item, "RN"));
      item = grid.selection.getNextSelected(item);
    };

    if (!reports.length) return;

    var dialog = new parus.balanceReportsFileExportDialog({

      onApply: function() {

        if (parus.parus8._themeEditorMode) {
          alert("В режиме редактирования схемы это действие невозможно.");
          return true;
        }

        var response = parus.database.execute("FindUserProcedure", {
          CODE: dialog.userProcEdit.value
        });

        if (!response) return false;

        var paramsDialog = new parus.balanceUserProcParamsDialog({
          useSavedValues: parus.parus8.optionValue("StoreUserProcsParams") != "0",
          userproc: parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"),
          onApply: dojo.hitch(this, function() {


            parus.database._xhr("fileexport.xml", null, {
              RN: reports.join(";"),
              USERPROC: paramsDialog.userproc,
              UNITCODE: "BalanceReports",
              PARAMS: parus.xml.toXml({
                "PARAMS": {
                  "PARAMS": paramsDialog.paramValues()
                }
              })
            },

            function(response) {
              if (response.documentElement.nodeName == "error") return;

              setTimeout(function() {

                var form = document.createElement("form");
                form.method = "GET";
                form.action = parus.database.getCustomDownloadDataUrl();
                //if (!dojo.isChrome)
                form.target = "_blank";
                document.body.appendChild(form);
                form.submit();
                document.body.removeChild(form);
              }, 1000);


            }

            );

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

        return true;
      }

    });

    dialog.show();
  },

  exportToSignedFile: function(grid, unitCode) {

    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var reports = [];

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      reports.push(store.getValue(item, "RN"));
      item = grid.selection.getNextSelected(item);
    };

    if (!reports.length) return;

    var dialog = new parus.balanceReportsFileExportDialog({

      onApply: function() {

        var response = parus.database.execute("FindUserProcedure", {
          CODE: dialog.userProcEdit.value
        });

        if (!response) return false;

        var paramsDialog = new parus.balanceUserProcParamsDialog({

          useSavedValues: parus.parus8.optionValue("StoreUserProcsParams") != "0",

          userproc: parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"),

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

            var paramValues = parus.xml.toXml({
              PARAMS: {
                PARAMS: paramsDialog.paramValues()
              }
            });

            var signDialog = new parus.signDialog({
              showNote: false,
              allowSimpleSign: false,
              checkPluginVersion: true,
              requiredVersion: {
                major: 1,
                minor: 5,
                build: 1500
              },

              rn: reports,
              unitCode: unitCode,

              onApply: dojo.hitch(this, function() {
                var signInfo = [];
                var signTemplate;

                var template = parus.parus8.getXMLReportSignTemplateName(signDialog.getGOSTVersion(), signDialog.getGOSTKeySize());
                if (template.length == 0) {
                  parus.parus8.errorMessage("Неподдерживаемая версия ГОСТ алгоритма в выбранном сертификате: " + signDialog.getGOSTVersion() + " (" + signDialog.getGOSTKeySize() + ")");
                  return true;
                }

                dojo.xhrGet({
                  sync: true,
                  handleAs: "xml",
                  url: "../parusjs/" + template,
                  load: dojo.hitch(this, function(response) {
                    signTemplate = response;
                    return response;
                  })
                });

                var errorText;

                dojo.forEach(reports, function(rn) {

                  var response = parus.database._xhr("fileexport.xml", null, {
                    RN: rn,
                    USERPROC: paramsDialog.userproc,
                    UNITCODE: "BalanceReports",
                    PARAMS: paramValues
                  });

                  if (response.documentElement.nodeName == "error") return;

                  dojo.xhrGet({
                    sync: true,

                    handleAs: "xml",
                    url: parus.database.getCustomDownloadDataUrl(),

                    load: dojo.hitch(this, function(response, ioargs) {

                      var responseFileName = "";
                      dojo.forEach(ioargs.xhr.getResponseHeader("Content-Disposition").split(";"), function(item) {
                        if (item.indexOf("filename=") >= 0) {
                          responseFileName = dojo.string.trim(item.split("=")[1]);
                          responseFileName = responseFileName.substr(1, responseFileName.length - 2);
                        };
                      });

                      response.documentElement.appendChild(signTemplate.documentElement);

                      var reportData = (dojo.isIE <= 9) ? response.xml : (new XMLSerializer()).serializeToString(response);
                      reportData = dojo.trim(reportData.replace(/\>\s+\</g, function(match) {
                        return match.replace(/\s+/g, "");
                      }));

                      signInfo.push({
                        rn: rn,
                        fileName: responseFileName,
                        data: reportData
                      });

                      return response;
                    }),

                    error: function(e) {
                      if (!errorText) errorText = "Ошибка получения данных. <br/>Вероятно, произошел сетевой сбой, или сервер стал недоступен. <br/>Попробуйте обновить страницу в браузере и перевойти в приложение.";
                      return e;
                    }
                  });

                });

                if (errorText) {
                  parus.parus8.errorMessage(errorText);
                  return true;
                }

                parus.digitalSignature.signXMLData(signInfo, signDialog.getThumbprint(), true).then(
                dojo.hitch(this, function() {
                  dojo.forEach(signInfo, function(item) {
                    if (item.signedData) {

                      if (parus.parus8._themeEditorMode) {
                        alert("В режиме редактирования схемы это действие невозможно.");
                        return;
                      }

                      var form = document.createElement("form");
                      form.method = "POST";
                      form.action = parus.database.getDownloadSignedReportPackageUrl();
                      //if (!dojo.isChrome)
                      form.target = "_blank";

                      var appendParam = function(name, value) {
                        var input = document.createElement("input");
                        input.type = "hidden";
                        input.name = name;
                        input.value = value;
                        form.appendChild(input);
                      };

                      appendParam("unitcode", "BalanceReports");
                      appendParam("reports", item.rn);
                      appendParam("fileName", item.fileName);
                      appendParam("fileData", item.signedData);
                      appendParam("params", paramValues);

                      document.body.appendChild(form);
                      form.submit();
                      document.body.removeChild(form);
                    }
                  });
                }), function(message) {
                  parus.parus8.errorMessage(message);
                });

                return true;
              })
            });

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

        paramsDialog.show();
        return true;
      }

    });

    dialog.show();
  },

  importFromFile: function(grid) {

    var dialog = new parus.balanceReportsFileImportDialog({
      onApply: dojo.hitch(this, function() {
        this.refreshGrid(grid);
        return true;
      })
    });

    dialog.show();
  },

  executeSettings: function(grid, menu, section, catalogTree, additions, userProcsUnitCode, userReportsUnitCode, userAppsUnitCode) {

    var dialog = new parus.gridSettingsDialog({
      sourceGrid: grid,
      sourceMenu: menu,
      sourceCatalogTree: catalogTree,
      additions: additions,
      userProcsUnitCode: userProcsUnitCode,
      userReportsUnitCode: userReportsUnitCode,
      userAppsUnitCode: userAppsUnitCode,

      onApply: function() {
        var settings = dialog.madeSettings();
        parus.userdata.set(section, settings, true);
        parus.gridSettingsDialog.setCatalogTreeVisible(catalogTree, !settings.hideCatalogTree);
        parus.gridSettingsDialog.mergeMenuSettings(menu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions, settings.userAppsActions);
        parus.gridSettingsDialog.mergeAdditions(additions, settings.additions);


        if (grid) {

          var store = grid.store;
          grid.setStore(new parus.emptyGridData());
          parus.gridSettingsDialog.mergeGridSettings(grid, settings.gridSettings);
          parus.gridSettingsDialog.mergeColorConditions(grid, settings.colorConditions);
          parus.gridSettingsDialog.mergeFilterBar(grid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
          setTimeout(function() {
            grid.setStore(store);
          }, 500);
          grid.abonentFields = (settings.abonentFields || []).join(";");
        }

        return true;
      }

    });

    dialog.show();
  },

  _translateConditionsToFilters: function(conditions, values) {

    //    console.log("_translateConditionsToFilters", conditions, values);
    var changed = false;

    if (conditions["AGNABBR"] != values["AGNABBR"]) {
      values["AGNABBR"] = conditions["AGNABBR"];
      changed = true;
    }

    if (conditions["AGNNAME"] != values["AGNNAME"]) {
      values["AGNNAME"] = conditions["AGNNAME"];
      changed = true;
    }

    if (conditions["FORM_CODE"] != values["FORM_CODE"]) {
      values["FORM_CODE"] = conditions["FORM_CODE"];
      changed = true;
    }

    if (conditions["DATE_FROM"] && conditions["DATE_TO"] && (conditions["DATE_FROM"].substring(2, 1000) == conditions["DATE_TO"].substring(2, 1000))) {
      if (values["BDATE"] != conditions["DATE_FROM"].substring(2, 1000)) {
        values["BDATE"] = conditions["DATE_FROM"].substring(2, 1000);
        changed = true;
      }
    }

    else {

      if (conditions["DATE_FROM"] != values["DATE_FROM"]) {
        values["DATE_FROM"] = conditions["DATE_FROM"];
        changed = true;
      };

      if (conditions["DATE_TO"] != values["DATE_TO"]) {
        values["DATE_TO"] = conditions["DATE_TO"];
        changed = true;
      };

      if (values["BDATE"]) {
        values["BDATE"] = "";
        changed = true;
      };
    }

    if (conditions["CHECKED"]) {
      var v = dojo.map(conditions["CHECKED"].split(";"), function(v) {
        return parus.parus8.formatBoolean(v);
      }).join(";");
      if (v != values["CHECKED"]) {
        values["CHECKED"] = v;
        changed = true;
      }
    }

    if (conditions["SENT"]) {
      var v = dojo.map(conditions["SENT"].split(";"), function(v) {
        return parus.parus8.formatBoolean(v);
      }).join(";");
      if (v != values["SENT"]) {
        values["SENT"] = v;
        changed = true;
      }
    }

    if (conditions["ONLY_LAST_HISTORY"]) {
      var v = dojo.map(conditions["ONLY_LAST_HISTORY"].split(";"), function(v) {
        return parus.parus8.formatBoolean(v);
      }).join(";");
      if (v != values["ONLY_LAST_HISTORY"]) {
        values["ONLY_LAST_HISTORY"] = v;
        changed = true;
      }
    }

    if (conditions["USE_HISTORY"]) {
      var v = dojo.map(conditions["USE_HISTORY"].split(";"), function(v) {
        return parus.balance.formatReportHistory(v);
      }).join(";");
      if (v != values["USE_HISTORY"]) {
        values["USE_HISTORY"] = v;
        changed = true;
      }
    }

    if (conditions["STATE"]) {
      var v = dojo.map(conditions["STATE"].split(";"), function(v) {
        return parus.balance.formatReportStatus(v);
      }).join(";");
      if (v != values["STATE"]) {
        values["STATE"] = v;
        changed = true;
      }
    }

    if (conditions.DOCPROPS) {
      dojo.forEach(parus.balance._docprops, function(docprop) {

        var rn = parus.parus8.nodeField(docprop, "RN");
        if (conditions.DOCPROPS["P" + rn]) {

          if (parus.parus8.nodeField(docprop, "DICTIONARY") || parus.parus8.nodeField(docprop, "DATATYPE") == "0") {
            if (conditions.DOCPROPS["P" + rn].value != values["prop" + rn]) {
              values["prop" + rn] = conditions.DOCPROPS["P" + rn].value || "";
              changed = true;
            }
          }
          else {

            if (conditions.DOCPROPS["P" + rn].from && conditions.DOCPROPS["P" + rn].to && (conditions.DOCPROPS["P" + rn].from == conditions.DOCPROPS["P" + rn].to)) {
              if (values["BDATE"] != conditions.DOCPROPS["P" + rn].from) {
                values["prop" + rn] = conditions.DOCPROPS["P" + rn].from || "";
                changed = true;
              }
            }
            else {
              if (values["prop" + rn]) {
                values["prop" + rn] = "";
                changed = true;
              }
            }

          }
        }

      });
    }

    return changed;

  },

  _translateFiltersToConditions: function(values, conditions) {

    //    console.log("_translateFiltersToConditions", values, conditions);
    var changed = false;

    if (values["AGNABBR"] && (conditions["AGNABBR"] != values["AGNABBR"])) {
      conditions["AGNABBR"] = values["AGNABBR"];
      changed = true;
    }
    else {
      if (!values["AGNABBR"] && conditions["AGNABBR"]) {
        conditions["AGNABBR"] = "";
        changed = true;
      }
    }

    if (values["AGNNAME"] && (conditions["AGNNAME"] != values["AGNNAME"])) {
      conditions["AGNNAME"] = values["AGNNAME"];
      changed = true;
    }
    else {
      if (!values["AGNNAME"] && conditions["AGNNAME"]) {
        conditions["AGNNAME"] = "";
        changed = true;
      }
    }

    if (values["FORM_CODE"] && (conditions["FORM_CODE"] != values["FORM_CODE"])) {
      conditions["FORM_CODE"] = values["FORM_CODE"];
      changed = true;
    }
    else {
      if (!values["FORM_CODE"] && conditions["FORM_CODE"]) {
        conditions["FORM_CODE"] = "";
        changed = true;
      }
    }

    if (values["BDATE"] && (values["BDATE"].split(";").length == 1) && (values["BDATE"].indexOf("*") < 0)) {
      if (conditions["DATE_FROM"] != ">=" + values["BDATE"]) {
        conditions["DATE_FROM"] = ">=" + values["BDATE"];
        changed = true;
      }
      if (conditions["DATE_TO"] != "<=" + values["BDATE"]) {
        conditions["DATE_TO"] = "<=" + values["BDATE"];
        changed = true;
      }
    }
    else {

      if (values["DATE_FROM"] && (conditions["DATE_FROM"] != values["DATE_FROM"])) {
        conditions["DATE_FROM"] = values["DATE_FROM"];
        changed = true;
      }
      else {
        if (!values["DATE_FROM"] && conditions["DATE_FROM"]) {
          conditions["DATE_FROM"] = "";
          changed = true;
        }
      }


      if (values["DATE_TO"] && (conditions["DATE_TO"] != values["DATE_TO"])) {
        conditions["DATE_TO"] = values["DATE_TO"];
        changed = true;
      }
      else {
        if (!values["DATE_TO"] && conditions["DATE_TO"]) {
          conditions["DATE_TO"] = "";
          changed = true;
        }
      }

    }

    if (values["CHECKED"]) {
      var cond = [];
      dojo.forEach(values["CHECKED"].split(";"), function(v) {
        var idx = dojo.indexOf(["Нет", "Да"], v);
        if (idx >= 0) cond.push(idx);
      });
      if (cond.join(";") != conditions["CHECKED"]) {
        conditions["CHECKED"] = cond.join(";");
        changed = true;
      }
    }
    else {
      if (conditions["CHECKED"]) {
        conditions["CHECKED"] = "";
        changed = true;
      }
    }

    if (values["SENT"]) {
      var cond = [];
      dojo.forEach(values["SENT"].split(";"), function(v) {
        var idx = dojo.indexOf(["Нет", "Да"], v);
        if (idx >= 0) cond.push(idx);
      });
      if (cond.join(";") != conditions["SENT"]) {
        conditions["SENT"] = cond.join(";");
        changed = true;
      }
    }
    else {
      if (conditions["SENT"]) {
        conditions["SENT"] = "";
        changed = true;
      }
    }

    if (values["ONLY_LAST_HISTORY"]) {
      var cond = [];
      dojo.forEach(values["ONLY_LAST_HISTORY"].split(";"), function(v) {
        var idx = dojo.indexOf(["Нет", "Да"], v);
        if (idx >= 0) cond.push(idx);
      });
      if (cond.join(";") != conditions["ONLY_LAST_HISTORY"]) {
        conditions["ONLY_LAST_HISTORY"] = cond.join(";");
        changed = true;
      }
    }
    else {
      if (conditions["ONLY_LAST_HISTORY"]) {
        conditions["ONLY_LAST_HISTORY"] = "";
        changed = true;
      }
    }

    if (values["USE_HISTORY"]) {
      var cond = [];
      dojo.forEach(values["USE_HISTORY"].split(";"), function(v) {
        var idx = dojo.indexOf(["Нет", "Да", "По запросу"], v);
        if (idx >= 0) cond.push(idx);
      });
      if (cond.join(";") != conditions["USE_HISTORY"]) {
        conditions["USE_HISTORY"] = cond.join(";");
        changed = true;
      }
    }
    else {
      if (conditions["USE_HISTORY"]) {
        conditions["USE_HISTORY"] = "";
        changed = true;
      }
    }

    if (values["STATE"]) {
      var cond = [];
      dojo.forEach(values["STATE"].split(";"), function(v) {
        var idx = dojo.indexOf(["Новый", "Изменен", "Рассчитан", "В своде", "Сведен без итогов", "Сведен с итогами", "Загружен", "Сведен предварительно"], v);
        if (idx >= 0) cond.push(idx);
      });
      if (cond.join(";") != conditions["STATE"]) {
        conditions["STATE"] = cond.join(";");
        changed = true;
      }
    }
    else {
      if (conditions["STATE"]) {
        conditions["STATE"] = "";
        changed = true;
      }
    }

    if (conditions.DOCPROPS) {
      dojo.forEach(parus.balance._docprops, function(docprop) {

        var rn = parus.parus8.nodeField(docprop, "RN");
        if (conditions.DOCPROPS["P" + rn]) {
          if (parus.parus8.nodeField(docprop, "DICTIONARY") || parus.parus8.nodeField(docprop, "DATATYPE") == "0") {
            if (values["prop" + rn] && (conditions.DOCPROPS["P" + rn].value != values["prop" + rn])) {
              conditions.DOCPROPS["P" + rn].value = values["prop" + rn];
              changed = true;
            }
          }
          else {

            if (values["prop" + rn] && (values["prop" + rn].split(";").length == 1) && (values["prop" + rn].indexOf("*") < 0)) {
              if (conditions.DOCPROPS["P" + rn].from != values["prop" + rn]) {
                conditions.DOCPROPS["P" + rn].from = values["prop" + rn];
                changed = true;
              }
              if (conditions.DOCPROPS["P" + rn].to != values["prop" + rn]) {
                conditions.DOCPROPS["P" + rn].to = values["prop" + rn];
                changed = true;
              }
            }
            else {
              if (conditions.DOCPROPS["P" + rn].from) {
                conditions.DOCPROPS["P" + rn].from = "";
                changed = true;
              }
              if (conditions.DOCPROPS["P" + rn].to) {
                conditions.DOCPROPS["P" + rn].to = "";
                changed = true;
              }
            }
          }
        }

      });
    }

    return changed;

  },

  gridFilterChanged: function(section, values, sortInfo) {

    if (section == "parus.balance.primaryMasterGrid") {
      if (parus.balance._translateFiltersToConditions(values, parus.balance._primaryConditions)) {
        parus.userdata.set("primaryConditions", parus.balance._primaryConditions);
        parus.balance.primaryMasterGrid.setQuery(parus.balance.primaryMasterGrid.query);
      }
    } else if (section == "parus.balance.consolidatedMasterGrid") {
      if (parus.balance._translateFiltersToConditions(values, parus.balance._consolidatedConditions)) {
        parus.userdata.set("consolidatedConditions", parus.balance._consolidatedConditions);
        parus.balance.consolidatedMasterGrid.setQuery(parus.balance.consolidatedMasterGrid.query);
      }
    }


    var settings = parus.userdata.get(section);
    settings.filterValues = values;
    settings.sortInfo = sortInfo || null;
    parus.userdata.set(section, settings, true);
  },

  executeUserCalc: function(rn, buildParamsProc, setParamsProc) {
    parus.database.execute("ExecuteUserCalc", {
      "USERCALC": rn,
      "PARAMS": {
        "PARAMS": buildParamsProc()
      }
    }, function(response) {
      var params = {};
      var nodes = response.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes;
      dojo.forEach(nodes, function(node) {
        params[node.nodeName] = parus.parus8.nodeField(node.parentNode, node.nodeName);
      });
      setParamsProc(params);
    });
  },

  executeUserCalcs: function(calcs, onInsert, onUpdate, buildParamsProc, setParamsProc) {

    var toexec = [];
    dojo.forEach(calcs, function(calc) {
      if ((onInsert && onUpdate) || (parus.parus8.nodeField(calc, "EXECINSERT") == "1" && onInsert) || (parus.parus8.nodeField(calc, "EXECUPDATE") == "1" && onUpdate)) toexec.push(calc)
    });

    if (!toexec.length) return;

    if (toexec.length == 1) parus.balance.executeUserCalc(parus.parus8.nodeField(toexec[0], "RN"), buildParamsProc, setParamsProc)
    else {
      var dialog = new parus.balanceUserCalcsDialog({
        calcs: toexec,
        onApply: dojo.hitch(this, function() {
          dojo.forEach(dialog.calcsGrid.selection.getSelected(), function(item) {
            parus.balance.executeUserCalc(dialog.calcsGrid.store.getValue(item, "RN"), buildParamsProc, setParamsProc);
          });
          return true;
        })
      });
      dialog.show();
    }
  },

  exportGrid: function(grid, detailGrid, subDetailGrid) {
    var dialog = new parus.exportGridDialog({
      grid: grid
    });

    dialog.show();

  },

  describeReport: function(report, subreport, template, index, value, date, authid, purpose) {
    return parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("describeAll", {
      "REPORT": report || "",
      "SUBREPORT": subreport || "",
      "TEMPLATE": template || "",
      "INDEX": index || "",
      "VALUE": value || "",
      "DATE": date || "",
      "AUTHID": authid || "",
      "PURPOSE": purpose
    }))[0], "TEXT");
  },


  formatTextAsFloat: function(data, rowIndex, column) {
    if (data) {
      var v = dojo.number.parse((data.toString()).split(".").join(","));
      if (!isNaN(v) && (data.charAt(0) != "0") && (v.toString().indexOf("e") == -1)) return dojo.number.format(v);
    };
    return data;
  },


  logout: function() {
    if (parus.balance && parus.balance.TabContainer && parus.balance.TabContainer.selectedChildWidget && parus.balance.TabContainer.selectedChildWidget.closable) parus.balance.TabContainer.closeChild(parus.balance.TabContainer.selectedChildWidget);
    else parus.parus8.logout();
  }

});

dojo.mixin(parus.database, {

  getTemplateUrl: function(template) {
    return this._buildUrl("/template.html?template=" + template)
  },

  getDesignTemplateUrl: function(template) {
    return this._buildUrl("/designertemplate.js?template=" + template)
  },

  getDesignTemplateWorkBookUrl: function() {
    return this._buildUrl("/designertemplateworkbook.xlsm")
  },

  getDesignTemplateUploadUrl: function() {
    return this._buildUrl("/designertemplateupload.xml")
  },

  getDesignTemplateSaveUrl: function() {
    return this._buildUrl("/designertemplatesave.xml")
  },

  getReportExcelUrl: function(extension) {
    return this._buildUrl("/report." + extension)
  },

  getReportXmlUrl: function() {
    return this._buildUrl("/report.xml")
  },

  getReportXmlDataUrl: function() {
    return this._buildUrl("/reportdata.xml")
  },

  getLoadReportsUrl: function() {
    return this._buildUrl("/loadreports.html")
  },

  getHelpUrl: function() {
    var h = this.connected.split(";");
    if (h.length > 1) {
      h = h[0];
    }
    else h = this.connected;

    return "../" + h + "/help/";
  },

  getLoadAttachedDocumentUrl: function() {
    return this._buildUrl("/loadattach.xml")
  },

  getLoadAttachedDocumentsUrl: function() {
    return this._buildUrl("/loadattachs.xml")
  },

  getDownloadAttachedDocumentUrl: function() {
    return this._buildUrl("/downloadattach.xml")
  },

  getCustomDownloadDataUrl: function() {
    return this._buildUrl("/customdownloaddata")
  },

  getFileExportUrl: function() {
    return this._buildUrl("/fileexport")
  },

  getFileImportUrl: function() {
    return this._buildUrl("/fileimport.xml")
  },

  getDownloadSignedReportPackageUrl: function() {
    return this._buildUrl("/signedreportpackage.zip")
  },

  getHistoryUrl: function(extension, rn) {
    var stem = "/valueshistory." + extension;
    if (rn) stem = stem + "?rn=" + rn;

    return this._buildUrl(stem);
  },

  getExportDataUrl: function(extension) {
    return this._buildUrl("/exportdata." + extension);
  },

  getDiagramUrl: function(template, report, subreport, index) {
    return this._buildUrl("/diagram.png?" + "parus.preventCache=" + (new Date().valueOf()) + "&template=" + template + "&report=" + report + "&subreport=" + (subreport ? subreport : "") + "&index=" + index)
  },

  getUserReportUrl: function(userReport, extension) {
    return this._buildUrl("/userReport." + extension + "?" + "userreport=" + userReport + "&parus.preventCache=" + (new Date().valueOf()))
  },

  getUserReportDataUrl: function() {
    return this._buildUrl("/userreportdata")
  },

  getLogoutUrl: function() {
    if (this.connected) {
      return this._buildUrl("/logout.xml");
    }
    else {
      return "../.system/logout.xml";
    }
  },

  getBufferUrl: function(rn) {
    return this._buildUrl("/frombuffer?rn=" + rn);
  },

  getExchangeImportUrl: function() {
    return this._buildUrl("/exchangeimport.xml")
  },

  getExchangeImportLogUrl: function() {
    return this._buildUrl("/exchangeimportlog")
  },

  getEnqueuedReportUrl: function(queue) {
    var stem = "/userreportqueue";
    if (queue) stem = stem + "?queue=" + queue;
    return this._buildUrl(stem)
  }

});

dojo.mixin(parus.parus8, {

  _attrDescriptors: false

});