dojo.provide("parus.abonent");

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

dojo.require("dojox.layout.ScrollPane");

dojo.require("parus.confirmationDialog");
dojo.require("parus.treeDialog");
dojo.require("parus.balanceCheckReportDialog");
dojo.require("parus.balanceReportCheckProtocolTabPage");

dojo.require("parus.abonentSpecialActions");
dojo.require("parus.abonentReportDialog");
dojo.require("parus.abonentSelectFormDialog");
dojo.require("parus.abonentCustomLoadReportsDialog");
dojo.require("parus.abonentMoveReportDialog");
dojo.require("parus.abonentCopyReportDialog");
dojo.require("parus.abonentReportRecalculateValuesDialog");

if (!parus) parus = {};

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

dojo.mixin(parus.abonent, {

  currentAgent: function() {
    return parus.abonent.agentLine.selectedChildWidget.rn;
  },

  currentAgentCode: function() {
    return parus.abonent.agentLine.selectedChildWidget.code;
  },

  currentYear: function() {
    return parus.abonent.timeLine.selectedChildWidget.rn;
  },

  currentMonth: function() {
    return (parus.abonent._lastIndex == parus.abonent.timeLine.selectedChildWidget.index) ? parus.abonent.timelinePane.getChildren()[0].selectedChildWidget.rn : null;
  },

  currentDay: function() {
    if (!this.currentMonth()) return null;
    var children = parus.abonent.timelinePane.getChildren()[0].selectedChildWidget.getChildren();
    return children.length ? children[0].selectedChildWidget.rn : (parus.abonent.timelinePane.getChildren()[0].selectedChildWidget.day || "*");
  },

  curentDate: function(forServer) {
    var y = parus.abonent.currentYear();
    var m = parus.abonent.currentMonth();
    var d = parus.abonent.currentDay() || "1";
    while (y.toString().length < 4)
    y = "0" + y;
    while (m.toString().length < 2)
    m = "0" + m;
    if (d != "*") while (d.toString().length < 2) d = "0" + d;

    return forServer ? (y + "-" + m + "-" + d) : (d + "." + m + "." + y);
  },

  _loaded: false,

  _conditionsChangedID: null,

  _conditionsChanged: function() {
    if (parus.abonent._conditionsChangedID) clearTimeout(parus.abonent._conditionsChangedID);
    parus.abonent._conditionsChangedID = setTimeout(dojo.hitch(parus.abonent, parus.abonent.loadContent), 300);
  },


  _lastIndex: null,

  loadContent: function() {

    if (parus.abonent._lastIndex != parus.abonent.timeLine.selectedChildWidget.index) {

      parus.abonent._lastIndex = parus.abonent.timeLine.selectedChildWidget.index;
      var nodes = parus.abonent._monthNodes[parus.abonent.timeLine.selectedChildWidget.index];

      dojo.forEach(parus.abonent.timelinePane.getChildren(), function(widget) {
        widget.destroyRecursive();
      });

      var saved = parus.userdata.get("parus.abonent.selectedTimeLine") || {};

      var content = "<div style=\"width:100%;height:100%\" region=\"center\" nested=\"true\" controllerWidget=\"parus.abonent.SmallScrollingTabController\" dojoType=\"dijit.layout.TabContainer\">";

      dojo.forEach(nodes, function(monthRow, idx) {

        var title = parus.parus8.monthNames()[parus.parus8.nodeField(monthRow, "MONTH") - 1];


        var dayNodes = parus.parus8.rowNodes(parus.parus8.nodeField(monthRow, "XMLDAYS"));


        var selected = "false";
        if (!saved.month) {
          if (idx == (nodes.length - 1)) selected = "true";
        }
        else if (saved.month == parus.parus8.nodeField(monthRow, "MONTH")) selected = "true";

        var day = (dayNodes.length > 1) ? "" : "day=" + parus.parus8.nodeField(dayNodes[0], "DAY").toString();

        content = content + "<div " + day + " selected=\"" + selected + "\" rn=\"" + parus.parus8.nodeField(monthRow, "MONTH") + "\" onShow=\"parus.abonent._conditionsChanged\" dojoType=\"parus.abonentSelectContentPane\" title=\"" + title + "\">";

        if (dayNodes.length > 1) {

          content = content + "<div nested=\"true\" controllerWidget=\"parus.abonent.SmallScrollingTabController\" dojoType=\"dijit.layout.TabContainer\">";

          dojo.forEach(dayNodes, function(dayRow, idx) {
            var d = parus.parus8.nodeField(dayRow, "DAY").toString();
            while (d.length < 2)
            d = "0" + d;
            var m = parus.parus8.nodeField(monthRow, "MONTH");
            while (m.length < 2)
            m = "0" + m;

            var selected = "false";
            if (!saved.day) {
              if (idx == (dayNodes.length - 1)) selected = "true";
            }
            else if (saved.day == parus.parus8.nodeField(dayRow, "DAY").toString()) selected = "true";


            content = content + "<div  selected=\"" + selected + "\" rn=\"" + parus.parus8.nodeField(dayRow, "DAY") + "\" onShow=\"parus.abonent._conditionsChanged\" dojoType=\"parus.abonentSelectContentPane\" title=\"" + d + "." + m + "." + parus.abonent.timeLine.selectedChildWidget.rn + "\"></div>";
          });

          content = content + "</div>"
        }

        content = content + "</div>"

      });

      content = content + "</div>"

      parus.abonent.timelinePane.setContent(content);

      parus.abonent.applicationWindow.layout();

      return;
    }

    var pages = parus.abonent.timelinePane.getChildren();

    if (pages.length && pages[0].selectedChildWidget && pages[0].selectedChildWidget.getChildren().length) {
      if (parus.abonent.timelinePane.domNode.style.height != "55px") {
        parus.abonent.timelinePane.domNode.style.height = "55px";
        parus.abonent.applicationWindow.layout();
      }
    }
    else if (parus.abonent._lastIndex != null) {
      if (parus.abonent.timelinePane.domNode.style.height != "25px") {
        parus.abonent.timelinePane.domNode.style.height = "25px";
        parus.abonent.applicationWindow.layout();
      }
    }

    var selected = [];



    if (!parus.abonent._loaded || !parus.abonent.currentAgent() || !parus.abonent.currentYear() || !parus.abonent.currentMonth()) {
      dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
        var widget = dijit.byNode(node);
        if (widget) {
          if (widget.reportRN && widget.checked) selected.push(widget.reportRN);
          widget.destroyRecursive();
        }
      });
      parus.abonent.checkActions();
      return;
    };

    dojo.fadeOut({
      node: parus.abonent.listView.domNode,
      duration: 100,
      onEnd: function() {


        dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) {
            if (widget.reportRN && widget.checked) selected.push(widget.reportRN);
            widget.destroyRecursive();
          }
        });

        dojo.place("<div></div>", parus.abonent.statusBar.containerNode, "only");

        parus.userdata.set("parus.abonent.selectedTimeLine", {
          year: parus.abonent.currentYear(),
          month: parus.abonent.currentMonth(),
          day: parus.abonent.currentDay()
        }, true);

        dojo.forEach(parus.parus8.rowNodes(parus.database.query("abonentReports", {
          "AGENT": parus.abonent.currentAgent(),
          "YEAR": parus.abonent.currentYear(),
          "MONTH": parus.abonent.currentMonth(),
          "DAY": parus.abonent.currentDay()
        })) || [], function(row) {
          (new parus.abonentTile({
            reportRN: parus.parus8.nodeField(row, "RN"),
            templateRN: parus.parus8.nodeField(row, "TEMPLATE"),
            editionRN: parus.parus8.nodeField(row, "BLREPFORMED"),
            catalogRN: parus.parus8.nodeField(row, "CRN"),
            formCode: parus.parus8.nodeField(row, "FORM_CODE"),

            attachments: parus.parus8.nodeField(row, "ATTACHMENTS"),
            subreports: parus.parus8.nodeField(row, "SUBREPORTS"),

            reportState: parus.parus8.nodeField(row, "STATE"),
            reportChecked: parus.parus8.nodeField(row, "CHECKED"),
            reportSent: parus.parus8.nodeField(row, "SENT"),
            reportStatus: parus.parus8.nodeField(row, "STATUS_NAME"),
            reportAccepted: parus.parus8.nodeField(row, "ACCEPTED"),

            dataRow: row,

            checked: dojo.indexOf(selected, parus.parus8.nodeField(row, "RN")) != -1,

            onCheck: dojo.hitch(parus.abonent, parus.abonent.checkActions)

          }, dojo.place("<div></div>", parus.abonent.listView.containerNode, "last"))).startup();

        });

        parus.abonent.checkActions();

        parus.abonent.loadStatus();

        dojo.fadeIn({
          node: parus.abonent.listView.domNode,
          duration: 300
        }).play();

      }
    }).play();

  },

  checkActions: function() {
    var checkCount = 0;

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) checkCount++;
    });

    dojo.query("*[widgetId]", parus.abonent.actionsPane.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.declaredClass == "dijit.form.Button") {
        widget.attr("disabled", !((widget.itemsPerAction == 0) || ((widget.itemsPerAction == 1) && (checkCount == 1)) || ((widget.itemsPerAction == 2) && (checkCount >= 1))));
      }
    });

  },

  _agentChangedID: null,

  _agentChanged: function() {
    if (parus.abonent._agentChangedID) clearTimeout(parus.abonent._agentChangedID);
    parus.abonent._agentChangedID = setTimeout(dojo.hitch(parus.abonent, function() {
      var saved = parus.userdata.get("parus.abonent.selectedTimeLine") || {};
      parus.userdata.set("parus.abonent.selectedAgent", {
        agent: parus.abonent.currentAgent()
      });
      parus.abonent.loadTimeline(saved.year, saved.month, saved.day);
    }), 300);
  },

  _monthNodes: null,

  loadTimeline: function(ayear, amonth, aday) {
    parus.abonent._loaded = false;

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) widget.destroyRecursive();
    });

    dojo.forEach(parus.abonent.timeLine.getChildren(), function(widget) {
      parus.abonent.timeLine.removeChild(widget);
      widget.destroyRecursive();
    });

    dojo.forEach(parus.abonent.timelinePane.getChildren(), function(widget) {
      widget.destroyRecursive();
    });

    parus.abonent._monthNodes = [];
    parus.abonent._lastIndex = null;

    dojo.place("<div></div>", parus.abonent.statusBar.containerNode, "only");

    var selected = null;

    var abonentYears = [];

    dojo.forEach(parus.parus8.rowNodes(parus.database.query("abonentYears", {
      "AGENT": parus.abonent.currentAgent()
    })) || [], function(row) {
      var y = parus.parus8.nodeField(row, "Y");
      var m = parus.parus8.nodeField(row, "M");
      var d = parus.parus8.nodeField(row, "D");

      var Y = null;
      dojo.forEach(abonentYears, function(ay) {
        if (ay["YEAR"] == y) Y = ay;
      });
      if (!Y) {
        abonentYears.push({
          "YEAR": y,
          "XMLMONTHS": [{
            "MONTH": m,
            "XMLDAYS": [{
              "DAY": d
            }]
          }]
        });
      }
      else {
        var M = null;
        dojo.forEach(Y["XMLMONTHS"], function(am) {
          if (am["MONTH"] == m) M = am;
        });
        if (!M) {
          Y["XMLMONTHS"].push({
            "MONTH": m,
            "XMLDAYS": [{
              "DAY": d
            }]
          });
        }
        else M["XMLDAYS"].push({
          "DAY": d
        });
      }
    });

    dojo.forEach(parus.parus8.rowNodes(abonentYears) || [], function(row, idx) {

      parus.abonent._monthNodes[idx] = parus.parus8.rowNodes(parus.parus8.nodeField(row, "XMLMONTHS"));

      var pane = new parus.abonentSelectContentPane({
        title: parus.parus8.nodeField(row, "YEAR"),
        rn: parus.parus8.nodeField(row, "YEAR"),
        selected: false,
        index: idx,
        onShow: parus.abonent._conditionsChanged
      });
      if (!ayear) selected = pane;
      if (ayear == parus.parus8.nodeField(row, "YEAR")) selected = pane;
      parus.abonent.timeLine.addChild(pane);
    });

    parus.abonent.timeLine.addChild(
    new parus.abonentSelectContentPane({
      title: (dojo.isIE) ? "<span onclick=\"parus.abonent.newDate()\" style=\"height:15px;font-weight:bold;font-size:120%;margin-top:-3px;cursor:pointer\">+</span>" : "<div onclick=\"parus.abonent.newDate()\" style=\"height:15px;font-weight:bold;font-size:120%;margin-top:-3px;cursor:pointer\">+</div>"
    }));

    if (selected) parus.abonent.timeLine.selectChild(selected);


    if (!parus.abonent._monthNodes.length) {

      if (parus.abonent.timelinePane.domNode.style.height != "1px") {
        parus.abonent.timelinePane.domNode.style.height = "1px";
        parus.abonent.applicationWindow.layout();
      };

      dojo.fadeOut({
        node: parus.abonent.listView.domNode,
        duration: 100,
        onEnd: function() {


          dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
            var widget = dijit.byNode(node);
            if (widget) widget.destroyRecursive();
          });

          dojo.place("<div></div>", parus.abonent.statusBar.containerNode, "only");

          (new parus.abonentTile({
            addReport: true
          }, dojo.place("<div></div>", parus.abonent.listView.containerNode, "last"))).startup();

          (new parus.abonentTile({
            loadReport: true
          }, dojo.place("<div></div>", parus.abonent.listView.containerNode, "last"))).startup();



          dojo.fadeIn({
            node: parus.abonent.listView.domNode,
            duration: 300
          }).play();

        }
      }).play();

    }

    parus.abonent.checkActions();

    parus.abonent._loaded = true;



  },

  newDate: function() {

    dojo.forEach(parus.abonent.timelinePane.getChildren(), function(widget) {
      widget.destroyRecursive();
    });


    var dialog = new parus.abonentCopyReportDialog({
      title: "Создание отчета в новом периоде",
      onShow: function() {
        dialog.formCode = "*";
        dialog.reportDateEdit.attr("value", parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("abonentDefaultDate", {}))[0], "VALUE"));
      },

      onApply: function() {

        if (!dialog.validate()) return false;

        var adate = dojo.date.locale.parse(
        dialog.reportDateEdit.value, {
          datePattern: "dd.MM.yyyy",
          selector: "date"
        });

        parus.abonent.addReport(dialog.reportDateEdit.value);

        return true;
      },

      onClose: function() {
        if (!dialog.applied) {
          var saved = parus.userdata.get("parus.abonent.selectedTimeLine") || {};
          parus.abonent.loadTimeline(saved.year, saved.month, saved.day);
        }
      }

    });

    dialog.show();

  },

  loadStatus: function() {

    dojo.forEach(parus.parus8.rowNodes(parus.database.execute("abonentStatus", {
      "AGENT": parus.abonent.currentAgent(),
      "YEAR": parus.abonent.currentYear(),
      "MONTH": parus.abonent.currentMonth(),
      "DAY": parus.abonent.currentDay()
    })) || [], function(row) {

      dojo.place("<div class=\"abonentStatusBar\">" + " Отчетов: <span class=\"abonentStatusBarInfoItem\">" + parus.parus8.nodeField(row, "REPORTS") + "</span>" + " Принято: <span class=\"abonentStatusBarInfoItem abonentStatusBarInfoItemAccepted\">" + parus.parus8.nodeField(row, "ACCEPTED") + "</span>" + " Отклонено: <span class=\"abonentStatusBarInfoItem abonentStatusBarInfoItemRejected\">" + parus.parus8.nodeField(row, "NOTACCEPTED") + "</span>" + "</div>",

      parus.abonent.statusBar.containerNode, "only");

      if (parus.parus8.nodeField(row, "CANCREATE") != "0")(new parus.abonentTile({
        addReport: true
      }, dojo.place("<div></div>", parus.abonent.listView.containerNode, "last"))).startup();
    });

    (new parus.abonentTile({
      loadReport: true
    }, dojo.place("<div></div>", parus.abonent.listView.containerNode, "last"))).startup();
  },


  _reportRowStatus: function(dataRow) {
    return "";
  },

  _subReportRowStatus: function(dataRow) {
    return "";
  },


  showTooltip: function(node) {

    dijit.showTooltip("<span class=\"abonentTileStatusToolTip\">" + node.innerHTML + "</span>", node);

    setTimeout(function() {
      dijit.hideTooltip(node);
    }, 5000);

    return false;

  },

  excludedButtons: [],

  includedButtons: [],

  userAppButtons: [],

  userProcButtons: [],

  userReportButtons: [],

  excludedSubreportButtons: [],

  includedSubreportButtons: [],

  subreportUserAppButtons: [],

  subreportUserProcButtons: [],

  subreportUserReportButtons: [],

  startup: function() {

    parus.abonent._lastIndex = null;
    parus.abonent._monthNodes = null;

    parus.abonent.excludedButtons = [];
    parus.abonent.includedButtons = [];
    parus.abonent.userAppButtons = [];
    parus.abonent.userProcButtons = [];
    parus.abonent.userReportButtons = [];

    parus.abonent.excludedSubreportButtons = [];
    parus.abonent.includedSubreportButtons = [];
    parus.abonent.subreportUserAppButtons = [];
    parus.abonent.subreportUserProcButtons = [];
    parus.abonent.subreportUserReportButtons = [];


    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, "BalanceNotifications") != -1) {
      parus.parus8.checkNotifications();
    };

    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.dictionaries._autoCompleteLimit = parus.parus8.optionValue("BalanceOnlineAutoCompleteUnitSize");

    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._detailAttrDescriptors = parus.parus8._attrDescriptors ? parus.parus8.rowNodes(parus.database.execute("attrDescriptors", {
      "UNITCODE": "BalanceSubReports"
    }).documentElement.childNodes[0].childNodes[0].childNodes[0]) || [] : [];

    var abonentFields = parus.userdata.get("parus.balance.primaryMasterGrid").abonentFields || ["STATUS_NAME"];
    var subreportAbonentFields = parus.userdata.get("parus.balance.primaryDetailGrid").abonentFields || ["STATUS_NAME"];

    var preDefinedButtonLabels = [{
      balance: "Добавить...",
      abonent: "Добавить"
    },
    {
      balance: "Размножить...",
      abonent: "Скопировать"
    },
    {
      balance: "Исправить...",
      abonent: "Свойства"
    },
    {
      balance: "Переместить...",
      abonent: "Переместить"
    },
    {
      balance: "Удалить...",
      abonent: "Удалить"
    },
    {
      balance: "Обновить...",
      abonent: "Обновить"
    },
    {
      balance: "Исправить значения...",
      abonent: "Открыть"
    },
    {
      balance: "Пересчитать значения...",
      abonent: "Пересчитать"
    },
    {
      balance: "Проверить значения...",
      abonent: "Проверить"
    },
    {
      balance: "Загрузить отчеты в пользовательском формате...",
      abonent: "Загрузить"
    },
    {
      balance: "Отправить в центр учета...",
      abonent: "Отправить"
    },
    {
      balance: "Выгрузить отчеты в Excel",
      abonent: "Excel"
    },
    {
      balance: "Присоединенные документы",
      abonent: "Вложения"
    }];


    var postDefinedButtonLabels = [{
      label: "Очистить значения",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportsClearValues
    },
    {
      label: "Протокол проверки значений...",
      itemsPerAction: 2,
      event: parus.abonent.balanceCheckReportProtocol
    },
    {
      label: "Принять отчеты...",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportSetReportAccepted
    },
    {
      label: "Отклонить отчеты...",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportSetReportUnaccepted
    },
    {
      label: "Изменить статус...",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportChangeStatus
    },
    {
      label: "История состояний...",
      itemsPerAction: 1,
      event: parus.abonent.balanceStatesHistory
    },

    {
      label: "История статусов...",
      itemsPerAction: 1,
      event: parus.abonent.balanceStatusesHistory
    },

    {
      label: "История значений...",
      itemsPerAction: 1,
      event: parus.abonent.balanceValuesHistory
    },
    {
      label: "Сводные отчеты...",
      itemsPerAction: 1,
      event: parus.abonent.balanceShowReportContents
    },
    {
      label: "Проверить наличие отчетов...",
      itemsPerAction: 0,
      event: parus.abonent.balanceCheckAbsentReports
    },
    {
      label: "Загрузить отчеты из файла...",
      itemsPerAction: 0,
      event: parus.abonent.balanceReportsLoadReports
    },
    {
      label: "Выгрузить отчеты для центра учета...",
      itemsPerAction: 2,
      event: parus.abonent.downloadReport
    },
    {
      label: "Выгрузить отчеты в пользовательском формате...",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportsCustomFormatDownloadReports
    },
    {
      label: "Отменить выгрузку",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportsUndoExport
    },
    {
      label: "Выгрузить отчеты в формате PDF",
      itemsPerAction: 2,
      event: parus.abonent.downloadExcelReportPDF
    },
    {
      label: "Выгрузить отчеты в формате HTML",
      itemsPerAction: 2,
      event: parus.abonent.downloadExcelReportHTML
    },

    {
      label: "Выгрузить...",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportsExchangeExport
    },

    {
      label: "Загрузить...",
      itemsPerAction: 0,
      event: parus.abonent.balanceReportsExchangeImport
    },


    {
      label: "Пользовательские приложения...",
      itemsPerAction: 0,
      event: parus.abonent.userApplications
    },
    {
      label: "Пользовательские процедуры...",
      itemsPerAction: 0,
      event: parus.abonent.userProcedures
    },
    {
      label: "Пользовательские отчеты...",
      itemsPerAction: 0,
      event: parus.abonent.userReports
    },

    {
      label: "Логины внешних провайдеров...",
      itemsPerAction: 0,
      event: parus.abonent.userExternalAccounts
    },

    {
      label: "Электронные подписи...",
      itemsPerAction: 1,
      event: parus.abonent.balanceReportsDigitalSignatures
    },
    {
      label: "Подписать...",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportsSign
    },
    {
      label: "Удалить подпись",
      itemsPerAction: 2,
      event: parus.abonent.balanceReportsRemoveSign
    },
    {
      label: "Экспорт в файл...",
      itemsPerAction: 2,
      event: parus.abonent.exportToFile
    },
    {
      label: "Импорт из файла...",
      itemsPerAction: 0,
      event: parus.abonent.importFromFile
    },
    {
      label: "Экспорт в файл с электронной подписью...",
      itemsPerAction: 2,
      event: parus.abonent.exportToSignedFile
    }];

    var preDefinedSubreportButtonLabels = [{
      balance: "Добавить...",
      abonent: "Добавить"
    },
    {
      balance: "Размножить...",
      abonent: "Скопировать"
    },
    {
      balance: "Исправить...",
      abonent: "Свойства"
    },
    {
      balance: "Удалить...",
      abonent: "Удалить"
    },
    {
      balance: "Обновить...",
      abonent: "Обновить"
    },
    {
      balance: "Исправить значения...",
      abonent: "Открыть"
    },
    {
      balance: "Пересчитать значения...",
      abonent: "Пересчитать"
    },
    {
      balance: "Проверить значения...",
      abonent: "Проверить"
    },
    {
      balance: "Выгрузить подотчеты в Excel",
      abonent: "Excel"
    },
    {
      balance: "Присоединенные документы",
      abonent: "Вложения"
    }];

    var postDefinedSubreportButtonLabels = [{
      label: "Очистить значения",
      itemsPerAction: 2,
      event: parus.abonent.balanceSubReportsClearValues
    },
    {
      label: "Протокол проверки значений...",
      itemsPerAction: 2,
      event: parus.abonent.balanceCheckSubReportProtocol
    },
    {
      label: "Изменить статус...",
      itemsPerAction: 2,
      event: parus.abonent.balanceSubReportChangeStatus
    },
    {
      label: "История значений...",
      itemsPerAction: 1,
      event: parus.abonent.balanceSubReportValuesHistory
    },
    {
      label: "История статусов...",
      itemsPerAction: 1,
      event: parus.abonent.balanceSubReportStatusesHistory
    },
    {
      label: "Выгрузить подотчеты в формате PDF",
      itemsPerAction: 2,
      event: parus.abonent.downloadExcelSubReportPDF
    },
    {
      label: "Выгрузить подотчеты в формате HTML",
      itemsPerAction: 2,
      event: parus.abonent.downloadExcelSubReportHTML
    },
    {
      label: "Пользовательские приложения...",
      itemsPerAction: 0,
      event: parus.abonent.userApplicationsSubReport
    },
    {
      label: "Пользовательские процедуры...",
      itemsPerAction: 0,
      event: parus.abonent.userProceduresSubReport
    },
    {
      label: "Пользовательские отчеты...",
      itemsPerAction: 0,
      event: parus.abonent.userReportsSubReport
    },
    {
      label: "Электронные подписи...",
      itemsPerAction: 1,
      event: parus.abonent.balanceSubReportsDigitalSignatures
    },
    {
      label: "Подписать...",
      itemsPerAction: 2,
      event: parus.abonent.balanceSubReportsSign
    },
    {
      label: "Удалить подпись",
      itemsPerAction: 2,
      event: parus.abonent.balanceSubReportsRemoveSign
    }];


    var settings = parus.userdata.get("parus.balance.primaryMasterGrid") || {};

    if (settings.additions) parus.balance.showTemplateGutter = settings.additions.showGutter;

    dojo.forEach(settings.actionSettings || [], function(menuSetting) {
      dojo.forEach(preDefinedButtonLabels, function(preDefinedButtonLabel) {
        if ((menuSetting.hash == parus.parus8.hash(preDefinedButtonLabel.balance)) && !menuSetting.inabonent) {
          parus.abonent.excludedButtons.push(preDefinedButtonLabel.abonent);
        }
      });

      dojo.forEach(postDefinedButtonLabels, function(postDefinedButtonLabel) {
        if ((menuSetting.hash == parus.parus8.hash(postDefinedButtonLabel.label)) && menuSetting.inabonent) {
          dojo.mixin(postDefinedButtonLabel, {
            customIcon: menuSetting.customIcon
          });
          parus.abonent.includedButtons.push(postDefinedButtonLabel);
        }
      });
    });

    if (settings.userAppsActions) dojo.forEach(parus.parus8.rowNodes(parus.database.query("userApps", {
      UNITCODE: "BalanceReports"
    })), function(node) {

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

      parus.abonent.userAppButtons.push({
        label: parus.parus8.nodeField(node, "NAME"),
        event: function() {
          parus.abonent._userApplication(parus.abonent._selectedReports(), "BalanceReports", rn, (parus.parus8.nodeField(node, "GROUP_RECORDS") != "0"));
        }

      })
    });

    if (settings.userProcsActions) dojo.forEach(parus.parus8.rowNodes(parus.database.query("userProcs", {
      UNITCODE: "BalanceReports"
    })), function(node) {

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

      parus.abonent.userProcButtons.push({
        label: parus.parus8.nodeField(node, "NAME"),
        event: function() {
          parus.abonent._userProcedure(parus.abonent._selectedReports(), "BalanceReports", rn, parus.parus8.nodeField(node, "CONFIRM_TEXT"), parus.parus8.nodeField(node, "PERRECORD") != "0", parus.parus8.nodeField(node, "PERSELECTION") != "0");
        }
      })
    });

    if (settings.userReportsActions) dojo.forEach(parus.parus8.rowNodes(parus.database.query("userReports", {
      UNITCODE: "BalanceReports"
    })), function(node) {

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

      parus.abonent.userReportButtons.push({
        label: parus.parus8.nodeField(node, "NAME"),
        event: function() {
          parus.abonent._userReport(parus.abonent._selectedReports(), "BalanceReports", rn, parus.parus8.nodeField(node, "NAME"), parus.parus8.nodeField(node, "REPORT_TYPE"));
        }
      })
    });



    var settings = parus.userdata.get("parus.balance.primaryDetailGrid");

    dojo.forEach(settings.actionSettings || [], function(menuSetting) {
      dojo.forEach(preDefinedSubreportButtonLabels, function(preDefinedSubreportButtonLabel) {
        if ((menuSetting.hash == parus.parus8.hash(preDefinedSubreportButtonLabel.balance)) && !menuSetting.inabonent) {
          parus.abonent.excludedSubreportButtons.push(preDefinedSubreportButtonLabel.abonent);
        }
      });


      dojo.forEach(postDefinedSubreportButtonLabels, function(postDefinedButtonLabel) {
        if ((menuSetting.hash == parus.parus8.hash(postDefinedButtonLabel.label)) && menuSetting.inabonent) {
          dojo.mixin(postDefinedButtonLabel, {
            customIcon: menuSetting.customIcon
          });
          parus.abonent.includedSubreportButtons.push(postDefinedButtonLabel);
        }
      });
    });


    if (settings.userAppsActions) dojo.forEach(parus.parus8.rowNodes(parus.database.query("userApps", {
      UNITCODE: "BalanceSubReports"
    })), function(node) {

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

      parus.abonent.subreportUserAppButtons.push({
        label: parus.parus8.nodeField(node, "NAME"),
        event: function() {
          parus.abonent._userApplication(parus.abonent._selectedSubReports(), "BalanceSubReports", rn, (parus.parus8.nodeField(node, "GROUP_RECORDS") != "0"));
        }

      })
    });

    if (settings.userProcsActions) dojo.forEach(parus.parus8.rowNodes(parus.database.query("userProcs", {
      UNITCODE: "BalanceSubReports"
    })), function(node) {

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

      parus.abonent.subreportUserProcButtons.push({
        label: parus.parus8.nodeField(node, "NAME"),
        event: function() {
          parus.abonent._userProcedure(parus.abonent._selectedSubReports(), "BalanceSubReports", rn, parus.parus8.nodeField(node, "CONFIRM_TEXT"), parus.parus8.nodeField(node, "PERRECORD") != "0", parus.parus8.nodeField(node, "PERSELECTION") != "0");
        }
      })
    });

    if (settings.userReportsActions) dojo.forEach(parus.parus8.rowNodes(parus.database.query("userReports", {
      UNITCODE: "BalanceSubReports"
    })), function(node) {

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

      parus.abonent.subreportUserReportButtons.push({
        label: parus.parus8.nodeField(node, "NAME"),
        event: function() {
          parus.abonent._userReport(parus.abonent._selectedSubReports(), "BalanceSubReports", rn, parus.parus8.nodeField(node, "NAME"), parus.parus8.nodeField(node, "REPORT_TYPE"));
        }
      })
    });







    //settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions
    var balanceCache = document.createElement("div");
    dojo.place(dojo.cache("parus", "balancePrimaryReportPane.html"), balanceCache, "only");

    parus.abonent._subReportRowStatus = function(rowData) {


      var fields = [];

      dojo.forEach(subreportAbonentFields, function(field) {


        var preDefined = dojo.query("*[jsid='parus.balance.primaryDetailGrid'] th[field='" + field + "']", balanceCache);
        if (preDefined.length) {
          var data = parus.parus8.nodeField(rowData, field);
          var formatter = preDefined[0].getAttribute("formatter");
          if (formatter) data = eval(formatter + "(" + dojo._escapeString(data) + ")");
          if (data) fields.push({
            name: parus.parus8.getTextContent(preDefined[0]),
            value: data
          });
        }

        else {


          dojo.forEach(parus.balance._detailDocprops, function(docprop) {
            if ("prop" + parus.parus8.nodeField(docprop, "RN") == field) {
              var data = parus._docPropsValueForGrid(parus.parus8.docPropValue(rowData, parus.parus8.nodeField(docprop, "RN")), parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));

              if (data) fields.push({
                name: parus.parus8.nodeField(docprop, "CODE"),
                value: data
              });
            }

          });

          dojo.forEach(parus.balance._detailAttrDescriptors, function(descriptor) {
            if ("attr" + parus.parus8.nodeField(descriptor, "RN") == field) {

              var data = parus._docPropsValueForGrid(parus.parus8.docPropValue(rowData, parus.parus8.nodeField(descriptor, "RN")), parus.parus8.nodeField(descriptor, "DATATYPE"), 0);

              if (data) fields.push({
                name: parus.parus8.nodeField(descriptor, "NAME"),
                value: data
              });
            }

          });

        }
      });

      var result = "";
      if (fields.length == 1) result = fields[0].value;
      else {

        dojo.forEach(fields, function(field) {
          if (result) result = result + "<br/>";
          result = result + dojo.trim(field.name) + ": " + field.value;
        });

        if (result) result = "<a onclick=\"parus.abonent.showTooltip(this)\" href=\"javascript:void(0)\">" + result + "</a>";
      }

      return result;




    };

    parus.abonent._reportRowStatus = function(rowData) {
      var fields = [];

      dojo.forEach(abonentFields, function(field) {


        var preDefined = dojo.query("*[jsid='parus.balance.primaryMasterGrid'] th[field='" + field + "']", balanceCache);
        if (preDefined.length) {
          var data = parus.parus8.nodeField(rowData, field);
          var formatter = preDefined[0].getAttribute("formatter");
          if (formatter) data = eval(formatter + "(" + dojo._escapeString(data) + ")");
          if (data) fields.push({
            name: parus.parus8.getTextContent(preDefined[0]),
            value: data
          });
        }

        else {
          dojo.forEach(parus.balance._docprops, function(docprop) {
            if ("prop" + parus.parus8.nodeField(docprop, "RN") == field) {
              var data = parus._docPropsValueForGrid(parus.parus8.docPropValue(rowData, parus.parus8.nodeField(docprop, "RN")), parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));

              if (data) fields.push({
                name: parus.parus8.nodeField(docprop, "CODE"),
                value: data
              });
            }

          });


          dojo.forEach(parus.balance._masterAttrDescriptors, function(descriptor) {
            if ("attr" + parus.parus8.nodeField(descriptor, "RN") == field) {

              var data = parus._docPropsValueForGrid(parus.parus8.docPropValue(rowData, parus.parus8.nodeField(descriptor, "RN")), parus.parus8.nodeField(descriptor, "DATATYPE"), 0);

              if (data) fields.push({
                name: parus.parus8.nodeField(descriptor, "NAME"),
                value: data
              });
            }

          });

        }
      });

      var result = "";
      if (fields.length == 1) result = fields[0].value;
      else {

        dojo.forEach(fields, function(field) {
          if (result) result = result + "<br/>";
          result = result + dojo.trim(field.name) + ": " + field.value;
        });

        if (result) result = "<a onclick=\"parus.abonent.showTooltip(this)\" href=\"javascript:void(0)\">" + result + "</a>";
      }

      return result;

    }

    var saved = parus.userdata.get("parus.abonent.selectedAgent") || {};

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


        dojo.query("*[widgetId]", parus.abonent.actionsPane.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.declaredClass == "dijit.form.Button") {
            if (dojo.indexOf(parus.abonent.excludedButtons, widget.label) >= 0) {
              var parent = node.parentNode;
              widget.destroyRecursive();
              parent.parentNode.removeChild(parent);
            }
          }
        });


        if (parus.abonent.includedButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", parus.abonent.actionsPane.domNode)[0];
          var maxwidth = parus.parus8.styleSize(parus.abonent.actionsPane.domNode.style.width) - 25;

          dojo.forEach(parus.abonent.includedButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: includedButton.itemsPerAction,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              iconClass: includedButton.customIcon + "Big",
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          parus.abonent.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        };


        if (parus.abonent.userAppButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", parus.abonent.actionsPane.domNode)[0];
          var maxwidth = parus.parus8.styleSize(parus.abonent.actionsPane.domNode.style.width) - 25;

          dojo.place("<div class=\"abonentToolBarSeparator\"></div>", toolbarNode, "last");

          dojo.forEach(parus.abonent.userAppButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: 0,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          parus.abonent.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        }

        if (parus.abonent.userProcButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", parus.abonent.actionsPane.domNode)[0];
          var maxwidth = parus.parus8.styleSize(parus.abonent.actionsPane.domNode.style.width) - 25;

          dojo.place("<div class=\"abonentToolBarSeparator\"></div>", toolbarNode, "last");

          dojo.forEach(parus.abonent.userProcButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: 0,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          parus.abonent.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        }

        if (parus.abonent.userReportButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", parus.abonent.actionsPane.domNode)[0];
          var maxwidth = parus.parus8.styleSize(parus.abonent.actionsPane.domNode.style.width) - 25;

          dojo.place("<div class=\"abonentToolBarSeparator\"></div>", toolbarNode, "last");

          dojo.forEach(parus.abonent.userReportButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: 0,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          parus.abonent.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        }


        dojo.query("*.abonentToolBarSeparator", parus.abonent.actionsPane.domNode).forEach(function(node) {
          if (!(node.previousElementSibling && node.nextElementSibling && !dojo.hasClass(node.nextElementSibling, "abonentToolBarSeparator"))) node.parentNode.removeChild(node);
        });

        var selected = null;

        var skipped = [];

        dojo.forEach(parus.parus8.rowNodes(parus.database.query("AGNLIST", {
          "CRN": "*"
        })) || [], function(row, idx) {

          if ((idx >= 20) && (selected || !saved.agent)) {
            skipped.push(row);
            return;
          }

          var pane = new parus.abonentSelectContentPane({
            title: "<span style=\"\">" + parus.parus8.nodeField(row, "AGNABBR") + "</span>",
            rn: parus.parus8.nodeField(row, "RN"),
            code: parus.parus8.nodeField(row, "AGNABBR"),
            onShow: parus.abonent._agentChanged,
            selected: false
          });
          if (saved.agent == parus.parus8.nodeField(row, "RN")) selected = pane;
          parus.abonent.agentLine.addChild(pane);
        });

        if (skipped.length) {

          var morePane = new dijit.layout.ContentPane({
            title: "<span style=\"cursor:pointer;font-weight:bold\"><span>Еще " + (skipped.length) + "...</span></span>",
            onShow: function() {


              var progressIndicator = new parus.progressDialog({
                message: "Загрузка контрагентов..."
              });
              progressIndicator.show();

              setTimeout(function() {


                dojo.forEach(skipped, function(row) {

                  var pane = new parus.abonentSelectContentPane({
                    title: "<span style=\"\">" + parus.parus8.nodeField(row, "AGNABBR") + "</span>",
                    rn: parus.parus8.nodeField(row, "RN"),
                    code: parus.parus8.nodeField(row, "AGNABBR"),
                    onShow: parus.abonent._agentChanged,
                    selected: false
                  });
                  parus.abonent.agentLine.addChild(pane);
                });

                parus.abonent.agentLine.removeChild(morePane);
                parus.abonent.agentLine.layout();

                progressIndicator.close();
                progressIndicator.destroyRecursive();
              }, 1000);


            }
          });
          parus.abonent.agentLine.addChild(morePane);

        };

        if (selected) parus.abonent.agentLine.selectChild(selected);

        parus.parus8.showApplication();

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


  addReport: function(currentDate) {

    if (!currentDate && !parus.abonent.currentYear()) {
      parus.abonent.newDate();
      return;
    };

    var forms = [];

    var d = currentDate || parus.abonent.curentDate();

    var formrows = parus.parus8.rowNodes(parus.database.query("abonentForms", {
      "AGENT": parus.abonent.currentAgent(),
      "DATE": d
    })) || [];

    if (!formrows.length) {
      parus.parus8.notificationMessage("Отсутствуют формы отчетов для добавления в текущем отчетном периоде.");
      return;
    };

    var dialog = new parus.abonentSelectFormDialog({

      onShow: function() {

        dojo.forEach(formrows, function(row) {

          var form = new parus.abonentTile({
            isForm: true,
            templateRN: parus.parus8.nodeField(row, "TEMPLATE"),
            formCode: parus.parus8.nodeField(row, "FORM_CODE"),
            reportStatus: parus.parus8.nodeField(row, "FORM_NAME"),
            onThumbnailDblClick: function() {
              dialog.apply();
            }
          }, dojo.place("<div></div>", dialog.dataPane.containerNode, "last"));
          forms.push(form);
          form.startup();

        });
      },

      onApply: function() {

        var selectedForms = [];

        dojo.forEach(forms, function(form) {
          if (form.checked) selectedForms.push(form.formCode);
        });

        if (!selectedForms.length) {
          parus.parus8.notificationMessage("Выберите хотя бы одну форму.");
          return false;
        };

        var reportDate = d;
        var reportAgent = parus.abonent.currentAgentCode();
        var reportUseHistory = parus.parus8.optionValue("BalanceUseHistory");
        var reportLastHistory = parus.parus8.optionValue("BalanceOnlyLastHistory");


        (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() {
            return parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("singleCatalog", {
              "UNITCODE": "BalanceReports",
              "ACTION_CODE": "BLREPORTS_INSERT"
            }))[0], "CATALOG");
          },

          onPerform: function(catalog) {

            dojo.forEach(selectedForms, function(form) {
              response = parus.database.execute("insertReport", {
                CRN: catalog,

                FORM_CODE: form,

                AGENT_CODE: reportAgent,
                BDATE: reportDate,

                AGENT_NAME: null,
                NOTE: null,
                KIND: 0,

                USE_HISTORY: reportUseHistory,
                ONLY_LAST_HISTORY: reportLastHistory,

                DOCPROPS: {
                  DOCPROPS: {}
                }
              });
            });

            dialog.applied = true;

            if (currentDate) {
              var adate = dojo.date.locale.parse(
              currentDate, {
                datePattern: "dd.MM.yyyy",
                selector: "date"
              });

              parus.userdata.set("parus.abonent.selectedTimeLine", {
                year: adate.getFullYear(),
                month: adate.getMonth() + 1,
                day: adate.getDate()
              });

              parus.abonent._lastIndex = null;

              parus.abonent.loadTimeline(adate.getFullYear(), adate.getMonth() + 1, adate.getDate());

            }
            else if (dialog.applied) parus.abonent.loadContent();


            dialog.close();
            return true;
          }

        })).show();
        return false;
      }
    });

    dialog.show();
  },

  refresh: function() {
    if (parus.abonent.currentYear()) parus.abonent.loadContent();
    else {
      var saved = parus.userdata.get("parus.abonent.selectedTimeLine") || {};
      parus.abonent.loadTimeline(saved.year, saved.month, saved.day);
    }

  },

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

    var tiles = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        tiles.push(widget);
      };
    });

    if (tiles.length > 1) {

      (new parus.confirmationDialog({

        message: "Выбрано несколько отчетов (" + tiles.length + "). Открыть их все?",

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


          dojo.forEach(tiles, function(widget) {
            window.open(dojo.moduleUrl("parus", "report.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([widget.reportRN, widget.subreportRN /*, widget.templateRN */ ]), "_blank");
          });

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

    }
    else if (tiles.length > 0) {
      window.open(dojo.moduleUrl("parus", "report.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([tiles[0].reportRN, tiles[0].subreportRN /*, tiles[0].templateRN */ ]), "_blank");
    }

    parus.parus8.registerAction();

  },

  loadReports: function() {
    var dialog = new parus.abonentCustomLoadReportsDialog({

      onApply: function() {

        if (!dialog.validate()) return false;

        if (!dialog.fileData.value) return false;

        (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() {
            return parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("singleCatalog", {
              "UNITCODE": "BalanceReports",
              "ACTION_CODE": "BLREPORTS_CUSTOM_IMPORT"
            }))[0], "CATALOG");
          },

          onPerform: function(catalog) {

            parus.parus8.registerAction();

            var form = document.createElement("form");

            form.method = "POST";
            form.action = "../.system/session.xml";
            form.encoding = "multipart/form-data";

            var parent = dialog.fileData.parentNode;
            form.appendChild(dialog.fileData);
            document.body.appendChild(form);

            var reportDate = parus.abonent.curentDate(true);
            var reportAgent = parus.abonent.currentAgentCode();

            dojo.io.iframe.send({

              method: "POST",
              form: form,
              handleAs: "xml",

              handle: function(response, ioArgs) {
                document.body.removeChild(form);
                parent.appendChild(dialog.fileData);
                dialog.applied = true;

                if (parus.parus8._themeEditorMode) {
                  dialog.applied = true;
                  dialog.close();
                  return;
                }

                var logWindow = window.open(dojo.moduleUrl("parus", "loadreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([dialog.formatCode.value, reportDate, reportAgent, catalog]), "_blank");
                logWindow.parentParus = parus;

                dialog.applied = true;
                dialog.close();
              }
            });
            return true;
          }
        })).show();
        return false;
      }
    });
    dialog.show();
  },

  deleteReports: function() {

    var rns = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) rns.push(widget.reportRN);
    });

    if (!rns.length) return;

    (new parus.confirmationDialog({

      message: "Удалить отчеты?",

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

        dojo.forEach(rns, function(rn) {
          parus.database.execute("deleteReport", {
            RN: rn
          });
        });

        var saved = parus.userdata.get("parus.abonent.selectedTimeLine") || {};
        parus.abonent.loadTimeline(saved.year, saved.month, saved.day);

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

  moveReports: function() {

    var tiles = [];
    var forms = [];
    var response;

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        forms.push(widget.formCode);
        tiles.push(widget);

      }
    });

    if (!tiles.length) return;


    var dialog = new parus.abonentMoveReportDialog({
      onShow: function() {
        dialog.formCode = forms.join(";");

        dojo.forEach(parus.parus8.rowNodes(parus.database.query("AGNLIST", {
          "CRN": "*"
        })) || [], function(row) {
          dialog.reportAgent.addOption({
            value: parus.parus8.nodeField(row, "AGNABBR"),
            label: parus.parus8.nodeField(row, "AGNABBR")
          })
        });

        dialog.reportAgent.attr("value", parus.abonent.currentAgentCode());
        dialog.reportDateEdit.attr("value", parus.abonent.curentDate());
      },

      onApply: function() {

        if (!dialog.validate()) return false;

        var adate = dojo.date.locale.parse(
        dialog.reportDateEdit.value, {
          datePattern: "dd.MM.yyyy",
          selector: "date"
        });

        dojo.forEach(tiles, function(tile) {
          response = parus.database.execute("abonentMoveReport", {
            RN: tile.reportRN,
            AGENT_CODE: dialog.reportAgent.value,
            BDATE: dialog.reportDateEdit.value
          });
        });

        if (!response) return false;

        var selected = null;
        dojo.forEach(parus.abonent.agentLine.getChildren(), function(widget) {
          if (widget.code == dialog.reportAgent.value) selected = widget;
        });

        if (selected && (selected.code != parus.abonent.currentAgentCode())) parus.abonent.agentLine.selectChild(selected);

        parus.abonent.loadTimeline(adate.getFullYear(), adate.getMonth() + 1, adate.getDate());

        return true;
      }
    });

    dialog.show();
  },

  copyReports: function() {

    var tiles = [];
    var forms = [];
    var response;

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        forms.push(widget.formCode);
        tiles.push(widget);
      }
    });

    if (!tiles.length) return;

    var dialog = new parus.abonentCopyReportDialog({
      onShow: function() {
        dialog.formCode = forms.join(";");
        dialog.reportDateEdit.attr("value", parus.abonent.curentDate());
      },

      onApply: function() {

        if (!dialog.validate()) return false;

        var adate = dojo.date.locale.parse(
        dialog.reportDateEdit.value, {
          datePattern: "dd.MM.yyyy",
          selector: "date"
        });

        dojo.forEach(tiles, function(tile) {
          response = parus.database.execute("abonentCopyReport", {
            RN: tile.reportRN,
            BDATE: dialog.reportDateEdit.value
          });
        });

        if (!response) return false;

        parus.abonent.loadTimeline(adate.getFullYear(), adate.getMonth() + 1, adate.getDate());

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

  },

  calculateReports: function() {

    var tiles = [];
    var rns = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        tiles.push(widget);
        rns.push(widget.reportRN);
      }
    });

    if (!tiles.length) return;

    var dialog = new parus.abonentReportRecalculateValuesDialog({

      rns: rns,

      onShow: function() {

        dialog.recalculateTypeEdit.attr("value", parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("getReportDefaultsRecalculateType", {
          "RN": rns[0]
        }))[0], "CALCTYPECODE"));
      },

      onApply: function() {

        if (!dialog.validate()) return false;

        dojo.forEach(rns, function(rn) {
          parus.database.execute("abonentRecalculateReportValues", {
            "RN": rn,
            "CALCTYPE_CODE": dialog.recalculateTypeEdit.value
          });
        });

        parus.abonent.loadContent();

        return true;

      }
    });

    dialog.show();

  },

  checkReports: function() {

    var tiles = [];
    var rns = [];
    var editions = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        tiles.push(widget);
        rns.push(widget.reportRN);
        editions.push(widget.editionRN);
      }
    });

    if (!tiles.length) return;

    var dialog = new parus.balanceCheckReportDialog({

      grid: null,
      kind: 0,
      isSubReport: false,

      rn: rns,
      formedRn: editions,
      reportRn: rns,

      showProtocol: function() {
        if (parus.parus8._themeEditorMode) {
          return;
        }

        parus.parus8.registerAction();

        var url = dojo.moduleUrl("parus", "checkreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([
        dialog.kind, (dialog.isSubReport ? 1 : 0), (dialog.showResultReportCheckBox.checked ? 1 : 0), rns.join(";"), dialog.checks || ""]);
        window.open(url, "_blank");
      },

      onClose: function() {
        if (dialog.applied) parus.abonent.loadContent();
      }
    });

    dialog.show();
  },

  sendReports: function() {

    var rns = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) rns.push(widget.reportRN);
    });

    if (!rns.length) return;

    (new parus.confirmationDialog({

      message: "Отправить выделенные отчеты в центр учета?",

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

        dojo.forEach(rns, function(rn) {
          parus.database.execute("DoReportExport", {
            RN: rn
          });
        });

        parus.abonent.loadContent();

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

  downloadReports: function() {

    var rns = [];
    var editions = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        rns.push(widget.reportRN);
        if (dojo.indexOf(editions, widget.editionRN) == -1) editions.push(widget.editionRN);
      }
    });

    if (!rns.length) return;

    if (rns.length == 1) parus.balance.downloadExcelWorkBook("BalanceReports", rns[0], null, null, "xls");
    else parus.balance.downloadExcelWorkBook("BalanceReports", rns, "*", (editions.length > 1) ? "*" : null, "xls");
  },

  attachmentsReports: function() {

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

    var rns = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        rns.push(widget.reportRN);
      }
    });

    if (rns.length != 1) return;

    (new parus.balanceReportAttachedDocumentsDialog({
      rn: rns[0],
      unitcode: "BalanceReports",
      onClose: function() {
        parus.abonent.loadContent();
      }

    })).show();
  },

  propertiesReports: function() {

    var rns = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        rns.push(widget.reportRN);
      }
    });

    if (rns.length != 1) return;

    var props = parus.parus8.rowNodes(parus.database.query("abonentReportProperties", {
      "RN": rns[0]
    }))[0];

    var dialog = new parus.abonentReportDialog({

      title: "Свойства",

      onShow: function() {

        dialog.noteEdit.attr("value", parus.parus8.nodeField(props, "NOTE"));
        dialog.historySelect.attr("value", parus.parus8.nodeField(props, "USE_HISTORY"));
        dialog.historyLastCheckBox.attr("checked", parus.parus8.nodeField(props, "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(props, rn), parus.parus8.nodeField(docprop, "DATATYPE") == "3" ? "4" : parus.parus8.nodeField(docprop, "DATATYPE"), parus.parus8.nodeField(docprop, "SUBTYPE"));
        });
      },

      onApply: function() {

        response = parus.database.execute("editReport", {
          "RN": rns[0],
          "AGENT_CODE": parus.parus8.nodeField(props, "AGNABBR"),
          "AGENT_NAME": null,
          "BDATE": parus.parus8.nodeField(props, "BDATE"),
          "NOTE": dialog.noteEdit.value,
          "KIND": parus.parus8.nodeField(props, "KIND"),
          "FORM_CODE": parus.parus8.nodeField(props, "FORM_CODE"),
          "USE_HISTORY": dialog.historySelect.value,
          "ONLY_LAST_HISTORY": (dialog.historyLastCheckBox.checked ? 1 : 0),
          "DOCPROPS": dialog.propValues()

        });

        if (!response) return false;

        parus.abonent.loadContent();

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

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

dojo.mixin(parus.checkReport, {

  startup: function() {

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

    var params = null;

    dojo.xhrGet({

      url: "../.system/session.xml",
      handleAs: "xml",
      sync: true,
      preventCache: true,

      load: function(response) {

        if (!dojo.isIE) response.normalize();

        var LNodes = response.documentElement.getElementsByTagName("*");

        for (var i = 0; i != LNodes.length; i++) {
          if (LNodes[i].nodeName == "params") params = LNodes[i].childNodes.item(0).nodeValue;
        }

        return (response);
      }
    });

    params = parus.parus8.hexDecodeParams(params);

    var pageTitle = "Протокол проверок";

    var isSubReport = (params[1] == "1");
    var rn = params[3].split(";");

    if (rn.length == 1) {
      var checkReportTitle = parus.balance.checkReportTitle(
      isSubReport ? null : rn[0], isSubReport ? rn[0] : null);

      pageTitle = parus.parus8.nodeField(checkReportTitle, "CAPTION");

    };

    var templateGridPane = parus.balanceReportCheckProtocolTabPage({
      region: "center",

      autonomousMode: true,

      title: pageTitle,

      kind: params[0],

      showResultReportOnly: params[2],
      checklist: params[4],

      rn: isSubReport ? [] : rn,
      subRn: isSubReport ? rn : null,

      style: "height:100%;width:100%;padding:0;opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"


    }, dojo.place("<div></div>", dojo.body(), "last"));

    templateGridPane.show();

    loadingDiv.style.display = "none";

    dojo.fadeIn({
      node: templateGridPane.domNode,
      duration: 300
    }).play();
  }
});


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

dojo.mixin(parus.loadLog, {

  startup: function() {

    var params = null;

    dojo.xhrGet({

      url: "../.system/session.xml",
      handleAs: "xml",
      sync: true,
      preventCache: true,

      load: function(response) {

        if (!dojo.isIE) response.normalize();

        var LNodes = response.documentElement.getElementsByTagName("*");

        for (var i = 0; i != LNodes.length; i++) {
          if (LNodes[i].nodeName == "params") params = LNodes[i].childNodes.item(0).nodeValue;
        }

        return (response);

      }
    });

    params = parus.parus8.hexDecodeParams(params);

    var container;

    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 = "Протокол загрузки отчетов в пользовательском формате";

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

    borderContainer.addChild(headingContentPane);

    var templateGridPane = new dijit.layout.ContentPane({
      region: "center",
      href: parus.database.getLoadReportsUrl(),
      ioMethod: dojo.xhrPost,
      ioArgs: {
        content: {
          custom: "1",
          kind: "0",
          logKind: "0",
          encodingType: "0",
          canOverWrite: "2",
          recalcReports: "on",
          formatCode: params[0],
          reportDate: params[1],
          agentCode: params[2],
          catalog: params[3]
        }
      },

      onLoad: function() {
        if (window.parentParus) window.parentParus.abonent.refresh();

        dojo.fadeIn({
          node: container.domNode,
          duration: 300
        }).play();
      }
    });

    borderContainer.addChild(templateGridPane);

    contentPane = new dijit.layout.ContentPane({
      title: title,
      closable: true,
      region: "center",
      "class": "balanceTemplateContentPane"
    });
    contentPane.setContent(borderContainer);

    loadingDiv.style.display = "none";

    container = new dijit.layout.BorderContainer({
      design: "headline",
      gutters: false,
      "class": "balanceTemplateContentPane",
      style: "height:100%;width:100%;padding:0;opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"
    }, dojo.place("<div></div>", dojo.body(), "last"))

    container.addChild(contentPane);
    container.startup();
  }
});

dojo.declare("parus.abonent.SmallScrollingTabController", [dijit.layout.ScrollingTabController], {

  buildRendering: function() {
    this.inherited(arguments);
    dojo.addClass(this.domNode, "abonentSmallScrollingTabController");
  }
});


dojo.declare("parus.abonent.ScrollingTabController", [dijit.layout.ScrollingTabController], {

  buildRendering: function() {
    this.inherited(arguments);
    dojo.addClass(this.domNode, "abonentScrollingTabController");
  }
});


dojo.declare("parus.abonent.agentScrollingTabController", [parus.abonent.ScrollingTabController], {

  resize: function(dim) {
    var result = this.inherited(arguments);
    if (!dojo.isIE) {
      var enable = this._enableBtn(this._contentBox.w);
      if (enable) {
        this.containerNode.align = "";
      }
      else {
        this.containerNode.align = "right";
        this.containerNode.style.width = "100%";
        this.containerNode.style.textAlign = "right";
      }
    };
    this._selectedTab = null;
    if (parus.abonent.agentLine.selectedChildWidget) this.onSelectChild(parus.abonent.agentLine.selectedChildWidget);

    return result;
  }

});

dojo.declare("parus.abonentTile", [dijit._Widget, dijit._Templated, dijit._CssStateMixin], {

  addReport: false,
  loadReport: false,
  isForm: false,

  reportRN: null,
  subreportRN: null,
  templateRN: null,
  editionRN: null,
  formCode: null,
  catalogRN: null,

  attachments: 0,
  subreports: 0,

  reportState: null,
  reportChecked: null,
  reportSent: null,
  reportStatus: null,
  reportAccepted: null,

  note: null,
  sectionCode: null,

  dataRow: null,

  onThumbnailClick: null,

  onThumbnailDblClick: null,

  templateString: dojo.cache("parus", "abonentTile.html"),

  baseClass: "abonentTile",

  attributeMap: dojo.delegate(dijit._WidgetBase, {
    checked: false
  }),

  checked: false,

  _setCheckedAttr: function(value) {
    this.checked = value;
    if (this.checked) {
      dojo.addClass(this.checkboxNode, "abonentTileCheckBoxChecked")
      dojo.addClass(this.domNode, "abonentTileChecked")
    }
    else {
      dojo.removeClass(this.checkboxNode, "abonentTileCheckBoxChecked");
      dojo.removeClass(this.domNode, "abonentTileChecked")
    }
    this.onCheck();
  },

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

    if (this.addReport) {
      dojo.addClass(this.domNode, "abonentTileAbsent");
      dojo.addClass(this.loadingNode, "abonentTileAddReport");
      if (this.onThumbnailClick) dojo.connect(this.anchorNode, "onclick", this, this.onThumbnailClick);
      else this.anchorNode.href = "javascript:parus.abonent.addReport()";
      if (this.onThumbnailDblClick) dojo.connect(this.anchorNode, "ondblclick", this, this.onThumbnailDblClick);
    }
    else if (this.loadReport) {
      dojo.addClass(this.domNode, "abonentTileAbsent");
      dojo.addClass(this.loadingNode, "abonentTileLoadReport");
      if (this.onThumbnailClick) dojo.connect(this.anchorNode, "onclick", this, this.onThumbnailClick);
      else this.anchorNode.href = "javascript:parus.abonent.loadReports()";
      if (this.onThumbnailDblClick) dojo.connect(this.anchorNode, "ondblclick", this, this.onThumbnailDblClick);
    }
    else {

      dojo.place("<span>" + this.formCode + "</span>", this.tileCaptionNode, "only");

      if (!this.sectionCode && !this.isForm && this.reportRN && !this.subreportRN && this.dataRow) this.tileStatusNode.innerHTML = parus.abonent._reportRowStatus(this.dataRow)
      else if (this.sectionCode && this.subreportRN && this.dataRow) this.tileStatusNode.innerHTML = parus.abonent._subReportRowStatus(this.dataRow)
      else if (this.reportStatus) {
        this.tileStatusNode.innerHTML = this.reportStatus;
        this.tileStatusNode.style.whiteSpace = "normal";
      }

      if (this.templateRN) {
        if (this.reportState == -1) {
          dojo.addClass(this.domNode, "abonentTileStateAbsent");
        }
        else if (this.reportState == 0) {
          dojo.addClass(this.domNode, "abonentTileStateNew");
        }
        else if (this.reportState == 6) {
          dojo.addClass(this.domNode, "abonentTileStateLoaded");
        }
        else this.thumbNode.style.backgroundImage = "url(" + parus.database.getThumbnailUrl(this.templateRN) + ")";

      }


      if (!this.isForm && !this.reportRN && !this.subreportRN) {
        dojo.addClass(this.domNode, "abonentTileAbsent");
        dojo.addClass(this.domNode, "abonentTileCanCreate");


        if (this.onThumbnailClick) dojo.connect(this.anchorNode, "onclick", this, this.onThumbnailClick);
        else {

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

            var reportDate = parus.abonent.curentDate();
            var reportAgent = parus.abonent.currentAgentCode();
            var reportUseHistory = parus.parus8.optionValue("BalanceUseHistory");
            var reportLastHistory = parus.parus8.optionValue("BalanceOnlyLastHistory");
            var reportForm = this.formCode;
            var reportCRN = this.catalogRN;
            var templateRN = this.templateRN;


            (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 (reportCRN) return reportCRN;
                else return parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("singleCatalog", {
                  "UNITCODE": "BalanceReports",
                  "ACTION_CODE": "BLREPORTS_INSERT"
                }))[0], "CATALOG");
              },

              onPerform: function(catalog) {

                response = parus.database.execute("insertReport", {
                  CRN: catalog,

                  FORM_CODE: reportForm,

                  AGENT_CODE: reportAgent,
                  BDATE: reportDate,

                  AGENT_NAME: null,
                  NOTE: null,
                  KIND: 0,

                  USE_HISTORY: reportUseHistory,
                  ONLY_LAST_HISTORY: reportLastHistory,

                  DOCPROPS: {
                    DOCPROPS: {}
                  }
                });

                parus.abonent.loadContent();


                if (parus.parus8._themeEditorMode) {
                  return true;
                }
                window.open(dojo.moduleUrl("parus", "report.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"), null /*, templateRN */ ]), "_blank");
                parus.parus8.registerAction();
                return true;
              }

            })).show();
            return false;
          });

          dojo.connect(this.anchorNode, "onclick", this, function(evt) {
            //??
          });

          dojo.connect(this.anchorNode, "ondblclick", this, function() {
            createproc();
          });

        }
      }
      else {

        if (this.onThumbnailClick) dojo.connect(this.anchorNode, "onclick", this, this.onThumbnailClick);
        else {

          dojo.connect(this.anchorNode, "onclick", this, function(evt) {



            if (!evt.shiftKey && !evt.ctrlKey) dojo.query("*[widgetId]", this.domNode.parentNode).forEach(function(node) {
              var widget = dijit.byNode(node);
              if (widget) if (widget.checked) widget.attr("checked", false);
            });

            if (!evt.shiftKey && !evt.ctrlKey) this.attr("checked", true);
            else this.attr("checked", !this.checked);

            if (!evt.shiftKey && !evt.ctrlKey) if (this.subreports != "0") setTimeout(dojo.hitch(this, this._onSubreportsClick), 100);
          });

        };


        if (this.onThumbnailDblClick) dojo.connect(this.anchorNode, "ondblclick", this, this.onThumbnailDblClick);
        else {



          dojo.connect(this.anchorNode, "ondblclick", this, function() {

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

            window.open(dojo.moduleUrl("parus", "report.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([this.reportRN, this.subreportRN /*, this.templateRN */ ]), "_blank");
            parus.parus8.registerAction();
          });
        };

      };

      if (this.reportAccepted == "1") dojo.addClass(this.domNode, "abonentTileAccepted")
      else if (this.reportAccepted == "2") dojo.addClass(this.domNode, "abonentTileRejected")

      if (this.subreports == "0") {
        this.subreportsNode.style.display = "none";
        this.subreportsNode.parentNode.style.display = "none";
      }

      if (this.attachments == "0") {
        this.attachmentsNode.style.display = "none";
      }
      else

      dojo.connect(this.attachmentsNode, "onclick", this, function() {

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

        (new parus.balanceReportAttachedDocumentsDialog({
          rn: this.subreportRN || this.reportRN,
          unitcode: this.subreportRN ? "BalanceSubReports" : "BalanceReports"
        })).show();

      });


      if (this.reportChecked != "1") {
        this.checkedNode.style.display = "none";
        this.checkedNode.parentNode.style.display = "none";
      }

      if (this.reportSent != "1") {
        this.sentNode.style.display = "none";
        this.sentNode.parentNode.style.display = "none";
      }

      if (this.reportState != "2") {
        this.calculatedNode.style.display = "none";
        this.calculatedNode.parentNode.style.display = "none";
      }

      var f = dojo.hitch(this, function() {
        var w = dojo.marginBox(this.tileStatusNode.parentNode).w;
        if (w) this.tileStatusNode.style.maxWidth = dojo.marginBox(this.tileStatusNode.parentNode).w + "px";
        else setTimeout(f, 100);
      });

      f();

    }

  },

  onCheck: function() {
    //placeholder
  },

  _onCheckClick: function() {
    this.attr("checked", !this.checked);
  },

  _onSubreportsClick: function() {

    var popup = new dijit.TooltipDialog({

      around: this.subreportsNode,

      tile: this,

      inDialog: false,

      content: dojo.cache("parus", "abonentSubreports.html"),

      onBlur: function() {
        if (!this.inDialog) this.closeClick();
      },

      parseOnLoad: false,

      closeClick: function() {
        dijit.popup.close(this);
        parus.abonent.subreportsPopup = null;
        setTimeout(dojo.hitch(this, this.destroyRecursive), 1);
      },

      checkActions: function() {
        var checkCount = 0;

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) checkCount++;
        });

        dojo.query("*[widgetId]", this.actionsPane.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.declaredClass == "dijit.form.Button") {
            widget.attr("disabled", !((widget.itemsPerAction == 0) || ((widget.itemsPerAction == 1) && (checkCount == 1)) || ((widget.itemsPerAction == 2) && (checkCount >= 1))));
          }
        });
      },

      onOpen: function() {
        parus.abonent.subreportsPopup = this;

        var wrapper = dijit.popup._createWrapper(this);

        dijit.placeOnScreenAroundElement(wrapper, this.around, {
          "BR": "TR",
          "BL": "TL",
          "TR": "BR",
          "TL": "BL"
        }, dojo.hitch(this, "orient"));

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

        dojo.forEach(parsed, dojo.hitch(this, function(widget) {
          var attachPoint = widget.dojoAttachPoint;
          if (attachPoint) this[attachPoint] = widget;
          dojo.mixin(widget, {
            dialogObject: this
          });
        }));


        dojo.query("*[widgetId]", this.actionsPane.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.declaredClass == "dijit.form.Button") {

            if (dojo.indexOf(parus.abonent.excludedSubreportButtons, widget.label) >= 0) {
              var parent = node.parentNode;
              widget.destroyRecursive();
              parent.parentNode.removeChild(parent);
            }
          }
        });

        if (parus.abonent.includedSubreportButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", this.containerNode)[0];
          var maxwidth = parus.parus8.styleSize(this.actionsPane.domNode.style.width) - 25;

          dojo.forEach(parus.abonent.includedSubreportButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: includedButton.itemsPerAction,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              iconClass: includedButton.customIcon + "Big",
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          this.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        };

        if (parus.abonent.subreportUserAppButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", this.containerNode)[0];
          var maxwidth = parus.parus8.styleSize(this.actionsPane.domNode.style.width) - 25;

          dojo.place("<div class=\"abonentToolBarSeparator\"></div>", toolbarNode, "last");

          dojo.forEach(parus.abonent.subreportUserAppButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: 0,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          this.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        };


        if (parus.abonent.subreportUserProcButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", this.containerNode)[0];
          var maxwidth = parus.parus8.styleSize(this.actionsPane.domNode.style.width) - 25;

          dojo.place("<div class=\"abonentToolBarSeparator\"></div>", toolbarNode, "last");

          dojo.forEach(parus.abonent.subreportUserProcButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: 0,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          this.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        };

        if (parus.abonent.subreportUserReportButtons.length) {

          var toolbarNode = dojo.query("*.abonentToolBar", this.containerNode)[0];
          var maxwidth = parus.parus8.styleSize(this.actionsPane.domNode.style.width) - 25;

          dojo.place("<div class=\"abonentToolBarSeparator\"></div>", toolbarNode, "last");

          dojo.forEach(parus.abonent.subreportUserReportButtons, function(includedButton) {
            var button = new dijit.form.Button({
              itemsPerAction: 0,
              label: includedButton.label.replace(/[\.\.\.]/g, ""),
              onClick: includedButton.event,
              showLabel: true,
              "class": "balanceToolBarButton"
            }, dojo.place("<div></div>", dojo.place("<div class=\"abonentToolBarItem\"></div>", toolbarNode, "last"), "last"));

            if (button.containerNode.offsetWidth > maxwidth) maxwidth = button.containerNode.offsetWidth;
          });

          this.actionsPane.domNode.style.width = (maxwidth + 25) + "px";
        };

        dojo.query("*.abonentToolBarSeparator", this.actionsPane.domNode).forEach(function(node) {
          if (!(node.previousElementSibling && node.nextElementSibling && !dojo.hasClass(node.nextElementSibling, "abonentToolBarSeparator"))) node.parentNode.removeChild(node);
        });

        this._loadSubreports();

        this.mainBorderContainer.resize();

        dijit.focus(this.domNode.children[0]);

        dojo.style(wrapper, {
          zIndex: 940
        });
      },


      subreportsEditValues: function() {

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

        var tiles = [];

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) {
            tiles.push(widget);
          };
        });

        if (tiles.length > 1) {

          (new parus.confirmationDialog({

            message: "Выбрано несколько подотчетов (" + tiles.length + "). Открыть их все?",

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


              dojo.forEach(tiles, function(widget) {
                window.open(dojo.moduleUrl("parus", "report.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([widget.reportRN, widget.subreportRN /*, widget.templateRN */ ]), "_blank");
              });

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

        }
        else if (tiles.length > 0) {
          window.open(dojo.moduleUrl("parus", "report.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([tiles[0].reportRN, tiles[0].subreportRN /*, tiles[0].templateRN */ ]), "_blank");
        };

        parus.parus8.registerAction();

      },

      subreportsRefresh: function() {

        dojo.fadeOut({
          node: this.dataContainer.domNode,
          duration: 100,
          onEnd: dojo.hitch(this, function() {

            this._loadSubreports();

            dojo.fadeIn({
              node: this.dataContainer.domNode,
              duration: 300
            }).play();

          })
        }).play();
      },

      subreportsAdd: function() {

        var dialog = new parus.balanceSubReportDialog({

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

          formCode: this.tile.formCode,

          edition: this.tile.editionRN,

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

            response = parus.database.execute("insertSubReport", {
              PRN: this.tile.reportRN,
              CODE: dialog.sectionCodeEdit.value,
              NOTE: dialog.noteEdit.value,
              DOCPROPS: dialog.propValues()

            });

            if (!response) return false;

            this._loadSubreports();

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

          }),


          onClose: dojo.hitch(this, function() {
            this.inDialog = false;
          })
        });

        this.inDialog = true;
        dialog.show();
      },

      subreportsDelete: function() {
        var rns = [];

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) rns.push(widget.subreportRN);
        });

        if (!rns.length) return;

        this.inDialog = true;

        (new parus.confirmationDialog({

          message: "Удалить подотчеты?",

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

            dojo.forEach(rns, function(rn) {
              parus.database.execute("deleteSubReport", {
                RN: rn
              });
            });

            this._loadSubreports();

            return true;
          }),

          onClose: dojo.hitch(this, function() {
            this.inDialog = false;
          })
        })).show();
      },

      subreportsCopy: function() {

        var rns = [];
        var note = null;
        var sectionCode = null;

        var item = null;

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) {
            rns.push(widget.subreportRN);
            note = widget.note;
            sectionCode = widget.sectionCode;
            item = widget.dataRow;
          }
        });

        if (rns.length != 1) return;


        var dialog = new parus.balanceSubReportDialog({

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

          formCode: this.tile.formCode,

          edition: this.tile.editionRN,

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

            dialog.sectionCodeEdit.attr("value", sectionCode);
            dialog.noteEdit.attr("value", 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: rns[0],
              PRN: this.tile.reportRN,
              CODE: dialog.sectionCodeEdit.value,
              NOTE: dialog.noteEdit.value,
              DOCPROPS: dialog.propValues()

            });

            if (!response) return false;

            this._loadSubreports();

            return true;
          }),

          onClose: dojo.hitch(this, function() {
            this.inDialog = false;
          })
        });

        this.inDialog = true;

        dialog.show();
      },

      subreportsCalculate: function() {
        var rns = [];

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) {
            rns.push(widget.subreportRN);
          }
        });

        if (!rns.length) return;

        var dialog = new parus.abonentReportRecalculateValuesDialog({

          isSubReport: true,

          rns: [this.tile.reportRN],

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

            dialog.recalculateTypeEdit.attr("value", parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("getReportDefaultsRecalculateType", {
              "RN": this.tile.reportRN
            }))[0], "CALCTYPECODE"));

          }),

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

            if (!dialog.validate()) return false;

            dojo.forEach(rns, dojo.hitch(this, function(rn) {

              parus.database.execute("abonentRecalculateSubReportValues", {
                "RN": rn,
                "PRN": this.tile.reportRN,
                "CALCTYPE_CODE": dialog.recalculateTypeEdit.value
              });

            }));

            this._loadSubreports();

            return true;

          }),

          onClose: dojo.hitch(this, function() {
            this.inDialog = false;
          })

        });

        this.inDialog = true;

        dialog.show();

      },

      subreportsCheck: function() {
        var tiles = [];
        var rns = [];

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) {
            tiles.push(widget);
            rns.push(widget.subreportRN);
          }
        });

        if (!tiles.length) return;

        var dialog = new parus.balanceCheckReportDialog({

          grid: null,
          kind: 0,
          isSubReport: true,

          rn: rns,
          formedRn: [this.tile.editionRN],
          reportRn: [this.tile.reportRN],

          showProtocol: function() {
            var url = dojo.moduleUrl("parus", "checkreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([
            dialog.kind, (dialog.isSubReport ? 1 : 0), (dialog.showResultReportCheckBox.checked ? 1 : 0), rns.join(";"), dialog.checks || ""]);

            if (parus.parus8._themeEditorMode) {
              return;
            }

            window.open(url, "_blank");
            parus.parus8.registerAction();
          },

          onClose: dojo.hitch(this, function() {
            if (dialog.applied) this._loadSubreports();
            this.inDialog = false;
          })

        });

        this.inDialog = true;

        dialog.show();
      },

      subreportsAttachments: function() {

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

        var rns = [];

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) {
            rns.push(widget.subreportRN);
          }
        });

        if (rns.length != 1) return;

        this.inDialog = true;

        var dialog = new parus.balanceReportAttachedDocumentsDialog({
          rn: rns[0],
          unitcode: "BalanceSubReports",
          onClose: dojo.hitch(this, function() {
            this.inDialog = false;
          })
        });

        dialog.show();

      },

      subreportsExcel: function() {
        var rns = [];

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) {
            rns.push(widget.subreportRN);
          }
        });

        if (!rns.length) return;
        parus.balance.downloadExcelWorkBook("BalanceSubReports", this.tile.reportRN, rns, null, "xls");
      },

      subreportsProperties: function() {

        var rns = [];
        var note = null;
        var sectionCode = null;
        var item = null;

        dojo.query("*[widgetId]", this.dataContainer.domNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) if (widget.checked) {
            rns.push(widget.subreportRN);
            note = widget.note;
            sectionCode = widget.sectionCode;
            item = widget.dataRow;
          }
        });

        if (rns.length != 1) return;


        var dialog = new parus.balanceSubReportDialog({

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

          formCode: this.tile.formCode,

          edition: this.tile.editionRN,

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

            dialog.sectionCodeEdit.attr("value", sectionCode);
            dialog.noteEdit.attr("value", 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: rns[0],
              CODE: dialog.sectionCodeEdit.value,
              NOTE: dialog.noteEdit.value,
              DOCPROPS: dialog.propValues()
            });

            if (!response) return false;

            this._loadSubreports();

            return true;
          }),

          onClose: dojo.hitch(this, function() {
            this.inDialog = false;
          })
        });

        this.inDialog = true;

        dialog.show();
      },

      _loadSubreports: function() {


        var selected = [];

        dojo.query("*[widgetId]", this.dataContainer.containerNode).forEach(function(node) {
          var widget = dijit.byNode(node);
          if (widget) {
            if (widget.subreportRN && widget.checked) selected.push(widget.subreportRN);
            widget.destroyRecursive();
          }
        });

        dojo.forEach(parus.parus8.rowNodes(parus.database.query("abonentSubreports", {
          "PRN": this.tile.reportRN,
          "RESULT": "0"
        })) || [], dojo.hitch(this, function(row) {
          (new parus.abonentTile({
            reportRN: this.tile.reportRN,
            templateRN: this.tile.templateRN,
            subreportRN: parus.parus8.nodeField(row, "RN"),
            formCode: parus.parus8.nodeField(row, "CODE"),
            attachments: parus.parus8.nodeField(row, "ATTACHMENTS"),
            subreports: 0,
            reportState: parus.parus8.nodeField(row, "STATE"),
            reportChecked: parus.parus8.nodeField(row, "CHECKED"),
            reportSent: this.tile.reportSent,
            reportStatus: parus.parus8.nodeField(row, "STATUS_NAME"),
            reportAccepted: this.tile.reportAccepted,
            note: parus.parus8.nodeField(row, "NOTE"),
            sectionCode: parus.parus8.nodeField(row, "CODE"),
            checked: dojo.indexOf(selected, parus.parus8.nodeField(row, "RN")) != -1,
            dataRow: row,
            onCheck: dojo.hitch(this, this.checkActions)
          }, dojo.place("<div></div>", this.dataContainer.containerNode, "last"))).startup();

        }));

        (new parus.abonentTile({
          addReport: true,
          onThumbnailClick: dojo.hitch(this, this.subreportsAdd)
        }, dojo.place("<div></div>", this.dataContainer.containerNode, "last"))).startup();

        this.checkActions();
      }
    });

    dijit.popup.open({
      parent: this,
      popup: popup,
      around: popup.around
    });
  }
});

dojo.declare("parus.abonentSelectContentPane", [dijit.layout.ContentPane], {

  rn: null,

  day: null,

  code: null

});


dojo.mixin(parus.database, {


  getThumbnailUrl: function(template) {
    return this._buildUrl("/templatethumb.png?template=" + template);
  }

});