dojo.provide("parus.balanceFolderDialog");

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

dojo.require("parus.parus8");
dojo.require("parus.dialog");
dojo.require("parus.groupBox");
dojo.require("parus.balanceFolderQueryDialog");

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

  schema: null,

  folder: null,

  _boxes: null,

  query: null,

  name: null,

  note: null,

  customQuery: false,

  processSchemaParam: function(param, box) {

    var rn = param["RN"][0]["#text"];
    var vparams = param["VISUALPARAMS"][0]["#text"];
    var datatype = param["DATATYPE"][0]["#text"];
    var subtype = param["SUBTYPE"][0]["#text"];
    var issystem = param["ISSYSTEM"][0]["#text"];
    var linking = param["LINKING"][0]["#text"];
    var name = param["NAME"][0]["#text"];

    var values = [];
    if (param["VALUES"]) dojo.forEach(param["VALUES"][0]["VALUE"], function(value) {
      values.push(value["#text"]);
    });

    var unitcode = param["UNITCODE"] ? param["UNITCODE"][0]["#text"] : null;
    var showmethod = param["SHOWMETHOD"] ? param["SHOWMETHOD"][0]["#text"] : null;
    var inparam = param["PARAMETER_IN"] ? param["PARAMETER_IN"][0]["#text"] : null;
    var outparam = param["PARAMETER_OUT"] ? param["PARAMETER_OUT"][0]["#text"] : null;

    var dictionary = unitcode ? ([unitcode, showmethod, inparam, outparam]).join("#") : null;

    var extradict = param["EXTRADICT"] ? param["EXTRADICT"][0]["#text"] : null;

    var intpart = param["INTPART"] ? param["INTPART"][0]["#text"] : null;
    var fracpart = param["FRACPART"] ? param["FRACPART"][0]["#text"] : null;

    var def = param["DEFAULT"] ? param["DEFAULT"][0] : null;

    var widget1 = null;
    var widget2 = null;
    var widget3 = null;

    var row = box._contentTable.insertRow(-1);
    var cell = row.insertCell(-1);
    dojo.place("<b>" + name + ":" + "</b>", cell, "only");

    cell = row.insertCell(-1);
    var mainSelect = new parus.conditionFolderSelect({

      intermediateChanges: true,

      style: "width:100%",

      isSystem: issystem == "1",

      rn: rn,

      row: row,


      buildValue: function() {
        var obj = {
          "RN": rn
        };

        if (mainSelect.value == "0") {
          return null;
        }
        else if ((mainSelect.value == "1") || (mainSelect.value == "2")) {

          if (values.length) {
            obj["VALUES"] = [{
              "VALUE": widget1.attr("value")
            }]
          }
          else {
            if (datatype == "2") obj["VALUE"] = Math.round((widget1.attr("value") - new Date(1899, 11, 30)) / 1000 / 60 / 60 / 24)
            else obj["VALUE"] = widget1.attr("value");
          }

          if (mainSelect.value == "2") obj["USENOT"] = 1;
        }
        else if ((mainSelect.value == "3") || (mainSelect.value == "4")) {
          if (values.length) {
            obj["VALUES"] = dojo.map(widget1.attr("value").split(";"), function(v) {
              return {
                "VALUE": v
              }
            });
          }
          else if (extradict || dictionary) {
            obj["VALUE"] = widget1.attr("value");
          }
          else {
            if (datatype == "2") {
              obj["BEGVAL"] = Math.round((widget1.attr("value") - new Date(1899, 11, 30)) / 1000 / 60 / 60 / 24)
              obj["ENDVAL"] = Math.round((widget2.attr("value") - new Date(1899, 11, 30)) / 1000 / 60 / 60 / 24)
            }
            else {
              obj["BEGVAL"] = widget1.attr("value");
              obj["ENDVAL"] = widget2.attr("value");
            }
          }

          if (mainSelect.value == "4") obj["USENOT"] = 1;

        }
        else if (mainSelect.value == "6") {
          obj["USENOT"] = 1;
        }
        else if (mainSelect.value == "7") {
          obj["SHIFTDATE"] = Math.round((widget1.attr("value") - new Date(1899, 11, 30)) / 1000 / 60 / 60 / 24);
          obj["SHIFTPERIOD"] = widget2.attr("value");
          obj["SHIFTVALUE"] = widget3.attr("value");
        }
        else if (mainSelect.value == "8") {
          obj["SHIFTPERIOD"] = widget1.attr("value");
          obj["SHIFTVALUE"] = widget2.attr("value");
        }
        return obj;
      },

      setFolderValue: function(value) {


        if (value) {

          var usenot = value["USENOT"][0]["#text"];
          var single = value["VALUE"] ? value["VALUE"][0]["#text"] : null;
          var begval = value["BEGVAL"] ? value["BEGVAL"][0]["#text"] : null;
          var endval = value["ENDVAL"] ? value["ENDVAL"][0]["#text"] : null;
          var valvalues = [];
          if (value["VALUES"]) dojo.forEach(value["VALUES"][0]["VALUE"], function(value) {
            valvalues.push(value["#text"]);
          });
          var shiftperiod = value["SHIFTPERIOD"] ? value["SHIFTPERIOD"][0]["#text"] : null;
          var shiftvalue = value["SHIFTVALUE"] ? value["SHIFTVALUE"][0]["#text"] : null;
          var shiftdate = value["SHIFTDATE"] ? value["SHIFTDATE"][0]["#text"] : null;

          if (values.length) {
            var v = 0;

            if (valvalues.length == 0) v = 5
            else if (valvalues.length == 1) v = 1
            else v = 3;
            if (usenot == "1") v++;

            mainSelect.attr("value", v);
            setTimeout(function() {
              widget1.attr("value", valvalues.join(";"));
            }, 100);
          }
          else if (shiftdate && (datatype == "2")) {

            var d = new Date(1899, 11, 30);
            d.setDate(d.getDate() + parseInt(shiftdate));
            mainSelect.attr("value", 7);
            setTimeout(function() {
              widget1.attr("value", d);
              widget2.attr("value", shiftperiod);
              widget3.attr("value", shiftvalue);
            }, 100);

          }
          else if (shiftperiod && (datatype == "2")) {

            mainSelect.attr("value", 8);
            setTimeout(function() {
              widget1.attr("value", shiftperiod);
              widget2.attr("value", shiftvalue);
            }, 100);

          }
          else if (single /*&& (single.indexOf(";") < 0)*/ ) {

            if (usenot == "1") mainSelect.attr("value", 2);
            else mainSelect.attr("value", 1);

            setTimeout(function() {
              if (datatype == "2") {
                var d = new Date(1899, 11, 30);
                d.setDate(d.getDate() + parseInt(single));
                widget1.attr("value", d);
              }
              else widget1.attr("value", single);
            }, 100);

          }
          /*          else if (single && (single.indexOf(";") >= 0) && (datatype == "0")) {
           if (usenot == "1") mainSelect.attr("value", 4);
           else mainSelect.attr("value", 3);
           setTimeout(function() {
           widget1.attr("value", single);
           }, 100);
           } */
          else if (begval && endval) {

            if (usenot == "1") mainSelect.attr("value", 4);
            else mainSelect.attr("value", 3);

            setTimeout(function() {
              if (datatype == "2") {
                var d = new Date(1899, 11, 30);
                d.setDate(d.getDate() + parseInt(begval));
                widget1.attr("value", d);
                var d = new Date(1899, 11, 30);
                d.setDate(d.getDate() + parseInt(endval));
                widget2.attr("value", d);
              }
              else {
                widget1.attr("value", begval);
                widget2.attr("value", endval);
              };
            }, 100);

          }
          else {

            if (usenot == "1") mainSelect.attr("value", 6);
            else mainSelect.attr("value", 5);

          }

        }
        else {
          var v = mainSelect.options[0].value;
          if (v == mainSelect.attr("value")) mainSelect.onChange();
          else mainSelect.attr("value", v);
        }
      },

      revert: dojo.hitch(this, function() {
        mainSelect.setFolderValue(def);
      }),

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

        dojo.forEach([widget1, widget2, widget3], function(widget) {
          if (widget) widget.destroyRecursive();
        });

        widget1 = null;
        widget2 = null;
        widget3 = null;

        while (row.cells.length > 2)
        row.removeChild(row.cells[2]);

        if ((mainSelect.value == "8")) {

          var cell = row.insertCell(-1);
          cell.colSpan = 4;
          dojo.style(cell, {
            paddingLeft: "5px",
            paddingRight: "5px"
          });
          widget1 = new dijit.form.Select({
            intermediateChanges: true,
            style: "width:100%",
            options: [{
              label: "День",
              value: "0"
            },
            {
              label: "Неделя",
              value: "1"
            },
            {
              label: "Декада",
              value: "2"
            },
            {
              label: "Месяц",
              value: "3"
            },
            {
              label: "Год",
              value: "4"
            }]
          }, dojo.place("<select></select>", cell, "only"));

          cell = row.insertCell(-1);
          cell.width = "30px";
          dojo.style(cell, {
            paddingLeft: "5px",
            paddingRight: "5px"
          });
          widget2 = new dijit.form.NumberTextBox({
            intermediateChanges: true,
            style: "width:100%",
            constraints: {
              min: -99,
              max: 99,
              fractional: false
            }
          }, dojo.place("<select></select>", cell, "only"));


        }
        else if ((mainSelect.value == "7")) {

          var cell = row.insertCell(-1);
          cell.colSpan = 2;
          dojo.style(cell, {
            paddingLeft: "5px",
            paddingRight: "5px"
          });
          widget1 = new dijit.form.DateTextBox({
            style: "width:100%",
            required: true,
            value: new Date()
          }, dojo.place("<input></input>", cell, "only"));


          cell = row.insertCell(-1);
          cell.colSpan = 2;
          dojo.style(cell, {
            paddingLeft: "5px",
            paddingRight: "5px"
          });
          widget2 = new dijit.form.Select({
            intermediateChanges: true,
            style: "width:100%",
            options: [{
              label: "День",
              value: "0"
            },
            {
              label: "Неделя",
              value: "1"
            },
            {
              label: "Декада",
              value: "2"
            },
            {
              label: "Месяц",
              value: "3"
            },
            {
              label: "Год",
              value: "4"
            }]
          }, dojo.place("<select></select>", cell, "only"));

          cell = row.insertCell(-1);
          cell.width = "30px";
          dojo.style(cell, {
            paddingLeft: "5px",
            paddingRight: "5px"
          });
          widget3 = new dijit.form.NumberTextBox({
            intermediateChanges: true,
            style: "width:100%",
            constraints: {
              min: -99,
              max: 99,
              fractional: false
            }
          }, dojo.place("<select></select>", cell, "only"));


        }
        else if ((mainSelect.value == "3") || (mainSelect.value == "4")) {


          if (values.length) {

            var cell = row.insertCell(-1);
            cell.colSpan = 5;
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });


            widget1 = new parus.dictEdit({
              style: "width:100%",
              required: true,
              multiselect: true,
              dictionary: "ConditionSchemesElementsParamsValues",
              onGetGridConditions: function() {
                return {
                  "RN": rn
                }
              }

            }, dojo.place("<input></input>", cell, "only"));


          }
          else if (extradict) {

            var cell = row.insertCell(-1);
            cell.colSpan = 5;
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            widget1 = new parus.extraDictEdit({
              style: "width:100%",
              multiselect: true,
              arbitrary: true,
              extraDictionaryCode: extradict,
              multiselect: true,
              required: true
            }, dojo.place("<input></input>", cell, "only"));

          }

          else if (dictionary) {

            var cell = row.insertCell(-1);
            cell.colSpan = 5;
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            if (dictionary == "BalanceReports#catalog#pos_ctlgname#ctlgname") {

              widget1 = new parus.catalogDictEdit({
                unitCode: "BalanceReports",
                multiselect: true,
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));


            }
            else if (dictionary == "AGNLIST#agents#pos_agnmnemo#agnmnemo") {

              widget1 = new parus.dictEdit({
                multiselect: true,
                dictionary: "AGNLISTByAGNABBR",
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));


            }
            else if (dictionary == "BalanceReportForms#normal#pos_code#code") {

              widget1 = new parus.dictEdit({
                multiselect: true,
                dictionary: "BalanceReportForms",
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));


            }
            else {
              widget1 = new parus.designerDictEdit({
                multiselect: true,
                unitCode: unitcode,
                methodCode: showmethod,
                inCode: inparam,
                outCode: outparam,
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));

            }
          }
          else if (datatype == 1) {

            var pattern = ""

            if (parseInt(intpart)) {
              for (var i = 0; i < intpart; i++)
              pattern = pattern + "#";
              if (parseInt(fracpart)) {
                pattern = pattern + ".";
                for (var i = 0; i < fracpart; i++)
                pattern = pattern + "#";
              };
            };

            var cell = row.insertCell(-1);
            cell.width = "20px";
            cell.align = "right";
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });
            cell.appendChild(document.createTextNode("c:"));

            cell = row.insertCell(-1);
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            widget1 = new dijit.form.NumberTextBox({
              constraints: {
                pattern: pattern
              },
              maxLength: pattern.length,
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));

            cell = row.insertCell(-1);
            cell.width = "20px";
            cell.align = "right";
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });
            cell.appendChild(document.createTextNode("по:"));

            cell = row.insertCell(-1);
            cell.colSpan = 2;
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            widget2 = new dijit.form.NumberTextBox({
              constraints: {
                pattern: pattern
              },
              maxLength: pattern.length,
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));



          }
          else if (datatype == 2) {

            var cell = row.insertCell(-1);
            cell.width = "20px";
            cell.align = "right";
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });
            cell.appendChild(document.createTextNode("c:"));

            cell = row.insertCell(-1);
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            widget1 = new dijit.form.DateTextBox({
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));

            cell = row.insertCell(-1);
            cell.width = "20px";
            cell.align = "right";
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });
            cell.appendChild(document.createTextNode("по:"));

            cell = row.insertCell(-1);
            cell.colSpan = 2;
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            widget2 = new dijit.form.DateTextBox({
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));

          }
          else {

            var cell = row.insertCell(-1);
            cell.width = "20px";
            cell.align = "right";
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });
            cell.appendChild(document.createTextNode("c:"));

            cell = row.insertCell(-1);
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            widget1 = new dijit.form.ValidationTextBox({
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));

            cell = row.insertCell(-1);
            cell.width = "20px";
            cell.align = "right";
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });
            cell.appendChild(document.createTextNode("по:"));

            cell = row.insertCell(-1);
            cell.colSpan = 2;
            dojo.style(cell, {
              paddingLeft: "5px",
              paddingRight: "5px"
            });

            widget2 = new dijit.form.ValidationTextBox({
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));
          }
        } else if ((mainSelect.value == "1") || (mainSelect.value == "2")) {

          var cell = row.insertCell(-1);
          cell.colSpan = 5;
          dojo.style(cell, {
            paddingLeft: "5px",
            paddingRight: "5px"
          });

          if (values.length) {

            widget1 = new dijit.form.Select({
              intermediateChanges: true,
              style: "width:100%",
              options: dojo.map(values, function(value) {
                return {
                  value: value,
                  label: value
                }
              })
            }, dojo.place("<select></select>", cell, "only"));

          }
          else if (extradict) {

            widget1 = new parus.extraDictEdit({
              style: "width:100%",
              extraDictionaryCode: extradict,
              multiselect: true,
              required: true
            }, dojo.place("<input></input>", cell, "only"));

          }

          else if (dictionary) {

            if (dictionary == "BalanceReports#catalog#pos_ctlgname#ctlgname") {

              widget1 = new parus.catalogDictEdit({
                multiselect: true,
                unitCode: "BalanceReports",
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));
            }
            else if (dictionary == "AGNLIST#agents#pos_agnmnemo#agnmnemo") {

              widget1 = new parus.dictEdit({
                multiselect: true,
                dictionary: "AGNLISTByAGNABBR",
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));
            }
            else if (dictionary == "BalanceReportForms#normal#pos_code#code") {

              widget1 = new parus.dictEdit({
                multiselect: true,
                dictionary: "BalanceReportForms",
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));
            }
            else {
              widget1 = new parus.designerDictEdit({
                multiselect: true,
                unitCode: unitcode,
                methodCode: showmethod,
                inCode: inparam,
                outCode: outparam,
                style: "width:100%",
                required: true
              }, dojo.place("<input></input>", cell, "only"));

            }
          }
          else if (datatype == 1) {

            var pattern = ""

            if (parseInt(intpart)) {
              for (var i = 0; i < intpart; i++)
              pattern = pattern + "#";
              if (parseInt(fracpart)) {
                pattern = pattern + ".";
                for (var i = 0; i < fracpart; i++)
                pattern = pattern + "#";
              };
            };

            widget1 = new dijit.form.NumberTextBox({
              constraints: {
                pattern: pattern
              },
              maxLength: pattern.length,
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));

          }
          else if (datatype == 2) {

            widget1 = new dijit.form.DateTextBox({
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"));

          }
          else {

            widget1 = new dijit.form.ValidationTextBox({
              style: "width:100%",
              required: true
            }, dojo.place("<input></input>", cell, "only"))
          }

        }
        this.paramsContainer.layout();

      })
    }, dojo.place("<select></select>", cell, "only"));

    if (vparams.substr(5, 1) != "1") mainSelect.addOption({
      value: "0",
      label: "Не задано"
    });

    if (vparams.substr(0, 1) == "1") {
      mainSelect.addOption({
        value: "1",
        label: "Значение равно"
      });

      if (vparams.substr(2, 1) == "1") mainSelect.addOption({
        value: "2",
        label: "Значение не равно"
      });
    };

    if (vparams.substr(1, 1) == "1") {
      mainSelect.addOption({
        value: "3",
        label: "Значение в диапазоне"
      });

      if (vparams.substr(2, 1) == "1") mainSelect.addOption({
        value: "4",
        label: "Значение вне диапазона"
      });
    };

    if (vparams.substr(3, 1) == "1") {
      mainSelect.addOption({
        value: "5",
        label: "Пусто"
      });

      if (vparams.substr(2, 1) == "1") mainSelect.addOption({
        value: "6",
        label: "Не пусто"
      });
    };

    if ((datatype == "2") && (values.length == 0)) {

      mainSelect.addOption({
        value: "7",
        label: "Смещение"
      });

      mainSelect.addOption({
        value: "8",
        label: "Относительное смещение"
      });
    };


    return mainSelect;

  },

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

    this._boxes = [];

    dojo.forEach(this.schema["SCHEMA"][0]["ELEMENT"], dojo.hitch(this, function(element) {

      var box = parus.conditionFolderContentBox({
        region: "top",
        title: element["NAME"][0]["#text"]
      }, dojo.place("<div><table width=\"100%\"></table></div>", this.paramsContainer.containerNode, "last"));

      box._contentTable = dojo.query("table", box.containerNode)[0];

      dojo.forEach(element["PARAMS"][0]["PARAM"], dojo.hitch(this, function(param) {
        box.params.push(this.processSchemaParam(param, box));
      }));

      box.startup();

      this._boxes.push(box);

    }));

    new dijit.layout.ContentPane({
      region: "top",
      style: "height:8px;overflow-x:hidden;overflow-x:hidden"
    }, dojo.place("<div>&#160;</div>", this.paramsContainer.containerNode, "last"));

    if (this.folder) {
      dojo.forEach(this.folder["FOLDER"][0]["PARAM"], dojo.hitch(this, function(value) {
        var param = this._findParam(value["RN"][0]["#text"]);
        if (param) param.setFolderValue(value);
      }));
      this.nameEdit.attr("value", this.name);
      this.noteEdit.attr("value", this.note);

    } else this.revertAll();

    this.showValues(true, false);

  },

  _findParam: function(rn) {
    var found = null;
    dojo.forEach(this._boxes, function(box) {
      dojo.forEach(box.params, function(param) {
        if (param.rn == rn) found = param;
      });
    });
    return found;
  },

  showValues: function(users, system) {

    dojo.forEach(this._boxes, function(box) {
      var visible = 0;

      dojo.forEach(box.params, function(param) {
        if ((param.isSystem && system) || (!param.isSystem && users)) {
          param.row.style.display = "";
          visible++;
        }
        else param.row.style.display = "none";
      });

      box.domNode.style.display = visible ? "" : "none";

    });

    this.paramsContainer.layout();

    dojo.forEach(this._boxes, function(box) {
      box.resize();
    });

  },

  revertAll: function() {

    dojo.forEach(this._boxes, function(box) {
      dojo.forEach(box.params, function(param) {
        param.revert();
      });
    });

  },

  buildFolder: function() {
    var folder = {
      "FOLDER": []
    };

    dojo.forEach(this._boxes, function(box) {
      dojo.forEach(box.params, function(param) {
        var value = param.buildValue();
        if (value) folder["FOLDER"].push({
          "PARAM": param.buildValue()
        });
      });
    });

    return folder;
  },

  editQuery: function() {
    var dialog = new parus.balanceFolderQueryDialog({
      onShow: dojo.hitch(this, function() {
        dialog.noteEdit.attr("value", this.query);
      }),

      onApply: dojo.hitch(this, function() {
        this.query = dialog.noteEdit.attr("value");
        this.customQuery = true;
        return true;
      })
    });

    dialog.show();

  },

  apply: function() {


    var args = arguments;
    var inherited = dojo.hitch(this, function() {
      this.inherited(args);
    });

    if (this.customQuery)(new parus.confirmationDialog({

      message: "Запрос был изменен пользователем. Перестроить запрос на основе заданных параметров отбора?",

      onApply: dojo.hitch(this, function() {
        this.customQuery = false;
        return true;
      }),

      onClose: inherited

    })).show();
    else inherited();

  }



});


dojo.declare("parus.conditionFolderSelect", dijit.form.Select, {

  isSystem: false

});

dojo.declare("parus.conditionFolderContentBox", parus.groupBox, {

  params: null,

  _contentTable: null,

  postCreate: function() {
    this.inherited(arguments);
    this.params = [];
  }

});