dojo.provide("parus.balanceAdvReportPane");

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("dojox.grid.DataGrid");
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.grid.enhanced._PluginManager");
dojo.require("dojox.grid.enhanced.plugins.IndirectSelection");

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.balanceAdvReportCompareDialog");
dojo.require("parus.balanceAdvReportSelectDialog");

if (!parus) parus = {};

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

dojo.mixin(parus.balance, {

  advCheckGridStore: function(catalogTree, masterGridID) {

    return parus.gridData({
      queryid: "advCheckGridData",
      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: "BalanceCompareReports"
            });

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

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

          catalogTree.attr("path", path);

          if (selectedCatalog.checks) {
            catalogTree.setCheckedPaths(

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

            )
          };


        };

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


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

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


        var item = catalogTree.selectedItem;

        dojo.forEach(grid.headerMenu.getChildren(), function(menuItem) {
          if (menuItem.actionCode) if (menuItem.declaredClass != "dijit.MenuSeparator")

          menuItem.attr("disabled", !catalogTree.model.hasAction(item, menuItem.actionCode));
        });

        return conditions;
      }),

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

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

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

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

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

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

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

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

            }

          });

        };

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


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

      })
    });
  },

  advCheckSettingsAdditions: function() {
    return [{
      widget: parus.balance.advCheckDetailGridPane,
      title: "Скрыть строки",
      id: "advCheckDetailGridPaneHiddenMode"
    }];
  },


  advCheckMove: function(grid) {

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

    (new parus.treeDialog({

      model: new(dojo.getObject(parus.balance.advCheckCatalogTree.model.declaredClass, false))({
        queryid: parus.balance.advCheckCatalogTree.model.queryid,
        onGetConditions: parus.balance.advCheckCatalogTree.model.onGetConditions
      }),

      key: "BalanceCompareReports",

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

        parus.balance.refreshGrid(grid);

        return true;

      }

    })).show();

  },

  advCheckDelete: 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("deleteAdvCheck", {
            RN: store.getValue(item, "RN")
          });
          item = grid.selection.getNextSelected(item);
        };

        this.refreshGrid(grid);

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

  advCheckCompareReports: function(catalogTree, grid) {
    var dialog = new parus.balanceAdvReportCompareDialog({

      _lastValues: {
        params: null
      },

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

        dialog.saveFormLastValues();



        (new parus.treeDialog({

          model: new(dojo.getObject(parus.balance.advCheckCatalogTree.model.declaredClass, false))({
            queryid: parus.balance.advCheckCatalogTree.model.queryid,
            onGetConditions: parus.balance.advCheckCatalogTree.model.onGetConditions
          }),

          key: "BalanceCompareReports",

          onDefaultNeeded: function() {
            var response = parus.database.execute("findAvailableCatalog", {
              UNITCODE: "BalanceCompareReports"
            });
            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": "BalanceCompareReports",
              "ACTION_CODE": "BLCOMPREP_COMPARE"
            }))[0], "CATALOG");

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

          },

          onPerform: function(catalog) {

            response = parus.database.execute("BalanceCompareReportCompare", {
              RN: null,
              CRN: catalog,
              RULE_CODE: dialog.ruleEdit.value,
              KIND: dialog.reportType.value,
              DATE_FROM: parus.parus8.valueToExternalString(dialog.fromDateEdit.attr("value")),
              DATE_TO: parus.parus8.valueToExternalString(dialog.toDateEdit.attr("value")),
              AGENTS: dialog.agentCodeEdit.value,
              CONDFOLDER: dialog._conditionFolderRN || null,
              PARAMS: dialog.buildParams(),
              SAVE_EQUALS: 0,
              SAVE_EXCLUDES: 0
            });

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

  },

  advCheckReCompareReports: function(grid) {

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

    var params = [];

    var node = document.createElement("div");
    node.innerHTML = store.getValue(item, "PARAMS");
    node = dojo.query("criteria", node)[0];
    if (node) {
      dojo.forEach(parus.parus8.getTextContent(node).split("<Сriterion>"), function(cr) {
        if (cr) params.push({
          "Criterion": cr
        });
      });
    };

    params = {
      "Conditions": {
        "Criteria": params
      }
    };

    var dialog = new parus.balanceAdvReportCompareDialog({

      rn: store.getValue(item, "RN"),

      _lastValues: {
        "conditionFolderRN": store.getValue(item, "CONDFOLDER"),
        "conditionFolder": store.getValue(item, "FOLDER_NAME"),
        "reportType": store.getValue(item, "KIND"),
        "fromDate": store.getValue(item, "DATE_FROM"),
        "toDate": store.getValue(item, "DATE_TO"),
        "agentCode": store.getValue(item, "AGENTS"),
        "rule": store.getValue(item, "RULE_CODE"),
        "groups": store.getValue(item, "SECTION_GROUPS"),
        "params": params
      },

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

        dialog.saveFormLastValues();

        response = parus.database.execute("BalanceCompareReportCompare", {
          RN: store.getValue(item, "RN"),
          CRN: store.getValue(item, "CRN"),
          RULE_CODE: dialog.ruleEdit.value,
          KIND: dialog.reportType.value,
          DATE_FROM: parus.parus8.valueToExternalString(dialog.fromDateEdit.attr("value")),
          DATE_TO: parus.parus8.valueToExternalString(dialog.toDateEdit.attr("value")),
          AGENTS: dialog.agentCodeEdit.value,
          CONDFOLDER: dialog._conditionFolderRN || null,
          PARAMS: dialog.buildParams(),
          SAVE_EQUALS: dialog.saveEqualsCheckBox.checked ? 1 : 0,
          SAVE_EXCLUDES: dialog.saveExcludesCheckBox.checked ? 1 : 0
        });

        if (response) parus.balance.refreshGrid(grid, "RN", store.getValue(item, "RN"));

        return !!response;
      })


    });

    dialog.show();

  },

  advCheckEqualSettingsAdditions: function() {
    return [{
      widget: parus.balance.advCheckEqualSubDetailPane,
      title: "Скрыть подобранные строки",
      id: "advCheckEqualPaneHiddenMode"
    }];

  },


  advCheckUnEqualSettingsAdditions: function() {
    return [{
      widget: parus.balance.advCheckUnEqualSubDetailPane,
      title: "Скрыть подобранные строки",
      id: "advCheckUnEqualPaneHiddenMode"
    }];

  },

  _advGridStructureSortClause: function(datatype, rn) {
    var r = "from BLTBLVALUES V " + "inner join  BLTABLESIND TI on TI.RN =   V.BLTABLESIND " + "inner join BLCOMPREPRULATR A on  TI.BALANCEINDEXES =  A.BALANCEINDEX " + "inner join BALANCEINDEXES I on I.RN = A.BALANCEINDEX " + "where V.PRN =  TR.RN " + "and A.PRN =  RL.RN ";

    if (datatype == 2) r = "V.DATEVAL " + r;
    else if (datatype == 1) r = "V.NUMVAL " + r;
    else r = "V.STRVAL " + r;

    return "(select " + r + " and I.RN = " + rn + ")";
  },


  advGridBuildStructure: function(grid, gridID) {

    var store = parus.balance.advCheckMasterGrid.store;
    var index = parus.balance.advCheckMasterGrid.selection.getSelectedIndex();
    var item = (index >= 0) ? parus.balance.advCheckMasterGrid.getItem(index) : null;

    if (!item) return null;

    var structure = [];
    dojo.forEach(parus.parus8.nodeField(item, "XMLATTRS"), function(attr) {
      structure.push({
        colSpan: 1,
        propRN: parus.parus8.nodeField(attr, "RN"),
        dataType: parus.parus8.nodeField(attr, "DATATYPE"),
        dataSubType: parus.parus8.nodeField(attr, "SUBTYPE"),
        field: "prop" + parus.parus8.nodeField(attr, "RN"),
        name: parus.parus8.nodeField(attr, "CODE"),
        formatter: parus.balance.formatDocPropValue,
        width: "121px",
        styles: "text-align:" + ((parus.parus8.nodeField(attr, "DATATYPE") == 0) ? "left" : "right") + ";",
        sortField: parus.balance._advGridStructureSortClause(
        parus.parus8.nodeField(attr, "DATATYPE"), parus.parus8.nodeField(attr, "RN"))
      });
    });



    if (structure.length) {
      var str = dojo.clone(grid.structure);
      str[0].cells[0] = dojo.filter(str[0].cells[0], function(attr) {
        return !attr.propRN;
      });

      str[0].cells[0] = str[0].cells[0].concat(structure);

      var settings = parus.userdata.get(gridID);
      if (settings) str = parus.gridSettingsDialog._mergeStructures(str, settings.gridSettings);
      grid.setStructure(str);
    }

  },



  advSubDetailGridStore: function(rn, grid, gridID, masterGrid) {


    return new parus.gridData({
      queryid: "advCheckGridSubDetailData",
      parentUnitCode: "BalanceCompareReportSpecs",
      onGetConditions: dojo.hitch(this, function(store) {

        parus.balance.advGridBuildStructure(grid, gridID);

        var conditions = {
          "PRN": rn
        };

        store.parentRN = rn;

        return conditions;
      }),

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

        var item = parus.balance.advCheckCatalogTree.selectedItem;
        var catalogTree = parus.balance.advCheckCatalogTree;

        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()) {
                menuItem.domNode.style.display = disabled ? "none" : "";
              }

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

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

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

            }

          });

        };

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

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

        setTimeout(function() {
          if (dojo.marginBox(masterGrid.domNode).w) masterGrid.focus.focusGrid();
        }, 0);


      })
    });
  },

  advDetailGridStore: function(excludeSign, equalSign, grid, gridID) {

    return new parus.gridData({
      queryid: "advCheckGridDetailData",
      parentUnitCode: "BalanceCompareReports",

      onGetConditions: dojo.hitch(this, function(store) {
        parus.balance.advGridBuildStructure(grid, gridID);

        var store = parus.balance.advCheckMasterGrid.store;
        var index = parus.balance.advCheckMasterGrid.selection.getSelectedIndex();
        var item = (index >= 0) ? parus.balance.advCheckMasterGrid.getItem(index) : null;

        var conditions = {
          "PRN": store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData,
          "EXCLUDE_SIGN": excludeSign,
          "EQUAL_SIGN": equalSign
        };
        store.parentRN = store.getValue(item, "RN");
        return conditions;
      }),

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

        var item = parus.balance.advCheckCatalogTree.selectedItem;
        var catalogTree = parus.balance.advCheckCatalogTree;

        var checkMenu = function(menu) {
          dojo.forEach(menu.getChildren(), function(menuItem) {
            menuItem.userObjectsGrid = grid;
            var disabled = catalogTree.listMode ? false : !catalogTree.model.hasAction(item, menuItem.actionCode);
            if (!disabled && (items.length == 0) && menuItem.itemAction) disabled = true;
            if (!parus.balance.advCheckMasterGrid.store.getValue(parus.balance.advCheckMasterGrid.getItem(parus.balance.advCheckMasterGrid.selection.getSelectedIndex()), "RN")) disabled = true;
            if (menuItem.declaredClass != "dijit.MenuSeparator") menuItem.attr("disabled", disabled);
            if (menuItem.popup) checkMenu(menuItem.popup);
          });
        };

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

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

        setTimeout(function() {
          if (dojo.marginBox(parus.balance.advCheckMasterGrid.domNode).w) parus.balance.advCheckMasterGrid.focus.focusGrid();
        }, 1000);


      })


    });

  },



  advCheckGridChange: function() {

    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;



      var grid = parus.balance.advCheckMasterGrid;
      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[grid.id] != selectedMaster) {
        this._catalogChangeBuffer[grid.id] = selectedMaster;
      }
      else return;



      //NEXCLUDE_SIGN = 0 and NEQUAL_SIGN = 1
      //Совпавшие
      if (parus.balance.advCheckActiveDetailGridIndex() == 0)

      parus.balance.advCheckEqualDetailGrid.setStore(
      parus.balance.advDetailGridStore(0, 1, parus.balance.advCheckEqualDetailGrid, "parus.balance.advCheckEqualDetailGrid"));


      //NEXCLUDE_SIGN = 0 and NEQUAL_SIGN = 0
      //Несовпавшие
      else if (parus.balance.advCheckActiveDetailGridIndex() == 1) parus.balance.advCheckUnEqualDetailGrid.setStore(
      parus.balance.advDetailGridStore(0, 0, parus.balance.advCheckUnEqualDetailGrid, "parus.balance.advCheckUnEqualDetailGrid"));
      //   parus.balance.advCheckEqualDetailGrid.setStore(
      //     parus.balance.advDetailGridStore(0, 0));
      //NEXCLUDE_SIGN = 1 and NEQUAL_SIGN = 0
      //Исключенные
      else if (parus.balance.advCheckActiveDetailGridIndex() == 2) parus.balance.advCheckExcludedDetailGrid.setStore(
      parus.balance.advDetailGridStore(1, 0, parus.balance.advCheckExcludedDetailGrid, "parus.balance.advCheckExcludedDetailGrid"));


    }), 300);



  },

  advCheckActiveDetailGridIndex: function() {
    if (parus.balance.advCheckDetailPages.selectedChildWidget.id == parus.balance.advCheckEqualDetailPage.id) return 0;
    else if (parus.balance.advCheckDetailPages.selectedChildWidget.id == parus.balance.advCheckUnEqualDetailPage.id) return 1;
    else if (parus.balance.advCheckDetailPages.selectedChildWidget.id == parus.balance.advCheckExcludedDetailPage.id) return 2;


  },

  advCheckDetailGridChange: function(grid, targetGrid, targetGridID) {

    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;

      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[grid.id] != selectedMaster) {
        this._catalogChangeBuffer[grid.id] = selectedMaster;
      }
      else return;


      targetGrid.setStore(parus.balance.advSubDetailGridStore(
      item ? store.getValue(item, "RN") : parus.parus8.CLASS_EmptyData, targetGrid, targetGridID, grid))

    }), 300);



  },


  advCheckDetailShowPage: function(page) {
    parus.balance.advCheckGridChange();
  },

  advCheckDetailExecuteEdit: function(grid, fieldName) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = (index >= 0) ? grid.getItem(index) : null;

    if (!item) return;


    var info = parus.parus8.rowNodes(parus.database.execute("GetEditInfoByAdvCheckRow", {
      RN: store.getValue(item, fieldName)
    }))[0];

    parus.balance.executeEditValues(
    parus.parus8.nodeField(info, "REPORT"), parus.parus8.nodeField(info, "SUBREPORT"), parus.parus8.nodeField(info, "BDATE"), parus.parus8.nodeField(info, "FORM_CODE"), parus.parus8.nodeField(info, "AGENT_CODE"), parus.parus8.nodeField(info, "SECTION_CODE"), parus.parus8.nodeField(info, "KIND"), parus.parus8.nodeField(info, "AGENT"),


    function(pane) {
      var rn = parus.parus8.nodeField(info, "NUMB");
      dojo.forEach(pane._tables, function(table) {
        var clone = table.clones.byKey[rn];
        if (clone) pane.followCell(clone.cells[0]);
        dojo.forEach(table.totals, function(total) {
          var clone = total.clones.byKey[rn];
          if (clone) pane.followCell(clone.cells[0]);
        });
      });
    }

    );

  },


  advCheckDetailFollowReport: function(grid, fieldName) {

    if (parus.parus8._embeddedMode) return;

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = (index >= 0) ? grid.getItem(index) : null;

    if (!item) return;

    var info = parus.parus8.rowNodes(parus.database.execute("GetEditInfoByAdvCheckRow", {
      RN: store.getValue(item, fieldName)
    }))[0];

    if (parus.parus8.nodeField(info, "KIND") == "0") {
      parus.balance.TabContainer.selectChild(parus.balance.primaryPage);
      parus.balance.primaryCatalogTree.attr("path", parus.parus8.nodeField(info, "PATH").split(";")).
      then(function() {
        parus.balance.refreshGrid(parus.balance.primaryMasterGrid, "RN", parus.parus8.nodeField(info, "REPORT"));
      });
    }
    else {
      parus.balance.TabContainer.selectChild(parus.balance.consolidatedPage);
      parus.balance.consolidatedCatalogTree.attr("path", parus.parus8.nodeField(info, "PATH").split(";")).
      then(function() {
        parus.balance.refreshGrid(parus.balance.consolidatedMasterGrid, "RN", parus.parus8.nodeField(info, "REPORT"));
      });
    }


  },

  advCheckDetailExclude: function(grid) {

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

    parus.balance.refreshGrid(grid);
  },


  advCheckDetailUndoExclude: function(grid) {

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

    parus.balance.refreshGrid(grid);
  },

  advCheckDetailSelect: function(grid) {

    var rn = [];


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

    if (!rn.length) return;

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

    var params = [];

    var node = document.createElement("div");
    node.innerHTML = store.getValue(item, "PARAMS");
    node = dojo.query("criteria", node)[0];
    if (node) {
      dojo.forEach(parus.parus8.getTextContent(node).split("<Сriterion>"), function(cr) {
        if (cr) params.push({
          "Criterion": cr
        });
      });
    };

    params = {
      "Conditions": {
        "Criteria": params
      }
    };

    var dialog = new parus.balanceAdvReportSelectDialog({

      protocol: store.getValue(item, "RN"),

      _lastValues: {
        "rule": store.getValue(item, "RULE_CODE"),
        "groups": store.getValue(item, "SECTION_GROUPS"),
        "params": params
      },

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

        dialog.saveFormLastValues();


        response = parus.database.execute("advCheckGridDetailSelect", {
          RN: rn.join(";"),
          PRN: store.getValue(item, "RN"),
          PARAMS: dialog.buildParams()
        });

        if (response && rn.length == 1) parus.parus8.notificationMessage("Подобрано строк: " + parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "RESULT") + ".");

        parus.balance.refreshGrid(grid, "RN", rn.length ? rn[0] : null);

        return !!response;
      })


    });

    dialog.show();
  },

  advCheckSubDetailDelete: 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("advCheckGridSubDetailDelete", {
            RN: store.getValue(item, "RN")
          });
          item = grid.selection.getNextSelected(item);
        };

        this.refreshGrid(grid);

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


  },

  advCheckSubDetailSetEqual: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();
    parus.database.execute("advCheckGridSubDetailSetEqual", {
      RN: store.getValue(item, "RN")
    });
    var grid = parus.balance.advCheckUnEqualDetailGrid;
    var store = grid.store;
    var item = grid.selection.getFirstSelected();
    parus.balance.refreshGrid(grid, "RN", store.getValue(item, "RN"));

  }


});