dojo.provide("parus.customEdit");

dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.form.NumberTextBox");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.form.TimeTextBox");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.SimpleTextarea");

dojo.require("parus.parus8");
dojo.require("parus.designerEdit");


if (!parus) parus = {};

dojo.mixin(parus, {

  _docPropsValueForGrid: function(value, dataType, dataSubType) {
    return (value && (dataType == "1")) ? dojo.number.format(dojo.number.parse((value.toString()).split(".").join(","))) : value;
  },


  _docPropsValueValueForWidget: function(widget, value, dataType, dataSubType) {
    dojo.mixin(widget, {
      _docPropsDataType: dataType,
      _docPropsDataSubType: dataSubType
    });

    if (dataType == "0") {
      widget.attr("value", value || null);
    }
    else if (dataType == "1") {
      widget.attr("value", value ? dojo.number.parse((value.toString()).split(".").join(",")) : value);
    }
    else if (dataType == "2") {
      var dateValue;

      if (value) dateValue = dojo.date.locale.parse((value.toString()).slice(0, 10), {
        selector: "date",
        datePattern: "dd.MM.yyyy"
      });
      else dateValue = null;

      widget.attr("value", dateValue);

      if (dataSubType == "1") {
        if (!widget.subWidget) dojo.mixin(widget, {
          subWidget: new dijit.form.TimeTextBox({
            constraints: {
              formatLength: "short"
            },
            disabled: widget.disabled,
            style: "width:80px"
          }, widget.domNode.parentNode.appendChild(document.createElement("div")))
        });

        if (value) widget.subWidget.attr("value", dojo.date.stamp.fromISOString("T" + (value.toString().slice(11)), new Date()))
        else widget.subWidget.attr("value", null);
      } else if (dataSubType == "2") {

        if (!widget.subWidget) dojo.mixin(widget, {
          subWidget: new dijit.form.TimeTextBox({
            constraints: {
              timePattern: "HH:mm:ss"
            },
            disabled: widget.disabled,
            style: "width:80px"
          }, widget.domNode.parentNode.appendChild(document.createElement("div")))
        });

        if (value) widget.subWidget.attr("value", dojo.date.stamp.fromISOString("T" + (value.toString().slice(11)), new Date()))
        else widget.subWidget.attr("value", null);

      }
    }
    else if (dataType == "4") {

      if (value) widget.attr("value", dojo.date.stamp.fromISOString("T" + value.toString(), new Date()))
      else widget.attr("value", null);

    };

  },

  _docPropsValueValueFromWidget: function(widget) {
    var dataType = widget._docPropsDataType;
    var dataSubType = widget._docPropsDataSubType;

    if (dataType == "0") {
      return widget.attr("value") || widget.value || ""
    }
    else if (dataType == "1") {
      var v = widget.attr("value");
      if (undefined === v || isNaN(v)) return "";
      return dojo.number.parse(v.toString().split(".").join(","));
    }
    else if (dataType == "2") {
      var v = widget.attr("value");
      if (!v) return "";
      if (widget._isInvalidDate(v)) return "";

      if (dataSubType == "0") return dojo.date.locale.format(v, {
        selector: "date",
        datePattern: "dd.MM.yyyy"
      });

      else if (dataSubType == "1") {
        var sv = widget.subWidget.attr("value");

        if (sv && !widget.subWidget._isInvalidDate(sv)) {
          sv = dojo.date.locale.format(sv, {
            selector: "time",
            formatLength: "short"
          });
          while (sv.length < 5)
          sv = "0" + sv;
          sv = " " + sv;
        }
        else sv = "";
        return dojo.date.locale.format(v, {
          selector: "date",
          datePattern: "dd.MM.yyyy"
        }) + sv;
      }
      else if (dataSubType == "2") {
        var sv = widget.subWidget.attr("value");

        if (sv && !widget.subWidget._isInvalidDate(sv)) {
          sv = dojo.date.locale.format(sv, {
            selector: "time",
            timePattern: "HH:mm:ss"
          });
          while (sv.length < 8)
          sv = "0" + sv;
          sv = " " + sv;
        }
        else sv = "";

        return dojo.date.locale.format(v, {
          selector: "date",
          datePattern: "dd.MM.yyyy"
        }) + sv;

      }

    }
    else if (dataType == "4") {

      var v = widget.attr("value");

      if (!v) return "";
      if (widget._isInvalidDate(v)) return "";

      if (dataSubType == "0") {

        var v = dojo.date.locale.format(v, {
          selector: "time",
          formatLength: "short"
        });
        while (v.length < 5)
        v = "0" + v;
        return v;
      }
      else if (dataSubType == "1") {

        var v = dojo.date.locale.format(v, {
          selector: "time",
          timePattern: "HH:mm:ss"
        });
        while (v.length < 8)
        v = "0" + v;
        return v;

      }

    }

  },

  customEditProperties: function(dictionary, dataType, dataSubType, required, strLen, intPart, fracPart) {
    var result = {

      constructor: function() {
        if (dictionary) {
          if ((dictionary == "BalanceReports#catalog#pos_ctlgname#ctlgname") || (dictionary == "AGNLIST#agents#pos_agnmnemo#agnmnemo") || (dictionary == "BalanceReportForms#normal#pos_code#code")) return parus.dictEdit;
          else if (dictionary.indexOf("#") != -1) return parus.designerDictEdit;
          else return parus.extraDictEdit;

        }
        else if ((dataType == "0") && (strLen > 255)) return parus.parus8.validationTextArea;
        else if (dataType == "1") return dijit.form.NumberTextBox;
        else if (dataType == "2") return dijit.form.DateTextBox;
        else if (dataType == "3") return dijit.form.CheckBox;
        else if (dataType == "4") return dijit.form.TimeTextBox;
        else if (dataType == "5") return parus.parus8.blobEditor;
        else if (dataType == "6") return parus.parus8.clobEditor;
        else return dijit.form.ValidationTextBox;
      },

      params: {
        required: required
      }

    };

    if (dictionary) {


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

        dojo.mixin(result.params, {
          onDictButtonClick: function() {
            var _this = this;

            var path = [];

            if (_this.value) {
              var response = parus.database.query("CatalogsPath", {
                UNITCODE: "BalanceReports",
                NAME: _this.value
              });
              dojo.forEach(parus.parus8.rowNodes(response), function(item) {
                path.push(parus.parus8.nodeField(item, "RN"));
              });
            }

            (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;
              },

              value: path.length ? path.join(";") : null,

              onPerform: function(identity, label) {
                _this.attr("value", label);
                return true;
              }


            })).show();

            return true;

          },

          style: "width:100%"
        });


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

        dojo.mixin(result.params, {
          dictionary: "AGNLISTByAGNABBR",
          style: "width:100%"
        });


      }

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


        dojo.mixin(result.params, {
          dictionary: "BalanceReportForms",
          style: "width:100%"
        });


      }
      else if (dictionary.indexOf("#") != -1) {

        var dicParams = dictionary.split("#");

        dojo.mixin(result.params, {

          unitCode: dicParams[0],
          methodCode: dicParams[1],
          inCode: dicParams[2],
          outCode: dicParams[3],
          style: "width:100%"

        });


      }
      else dojo.mixin(result.params, {
        extraDictionaryCode: dictionary,
        style: "width:100%"
      });

    }
    else if ((dataType == "0") && (strLen > 255)) {

      dojo.mixin(result.params, {
        rows: 5,
        intermediateChanges: true
      });

    }
    else if (dataType == "1") {

      if (parseInt(intPart)) {
        var pattern = ""
        for (var i = 0; i < intPart; i++)
        pattern = pattern + "#";
        if (parseInt(fracPart)) {
          pattern = pattern + ".";
          for (var i = 0; i < fracPart; i++)
          pattern = pattern + "#";
        };
        dojo.mixin(result.params, {
          constraints: {
            pattern: pattern
          },
          maxLength: pattern.length
        });
      }

    }
    else if (dataType == "2") {
      dojo.mixin(result.params, {
        constraints: {
          selector: "date",
          datePattern: "dd.MM.yyyy"
        },
        style: "width:100px"

      });

    }
    else if (dataType == "3") {

    }

    else if (dataType == "4") {

      if (dataSubType == "1") {

        dojo.mixin(result.params, {
          constraints: {
            timePattern: "HH:mm:ss"
          },
          style: "width:80px"
        });


      }
      else {

        dojo.mixin(result.params, {
          constraints: {
            formatLength: "short"
          },
          style: "width:80px"
        });
      }

    }
    else {
      dojo.mixin(result.params, {
        maxLength: strLen || 255,
        style: "width:100%"
      });

    }

    return result;

  }

});


dojo.declare("parus.parus8.blobEditor", [dijit._Widget, dijit._Templated], {

  templateString: "<input onchange=\"dijit.byNode(this).onChange()\"  type=\"file\"/>",

  type: "blob",

  onChange: function() {
    //placeholder
  }

});

dojo.declare("parus.parus8.clobEditor", [parus.parus8.blobEditor], {

  type: "clob"

});

dojo.declare("parus.parus8.validationTextArea", [dijit.form.SimpleTextarea], {

  required: false,

  validate: function() {
    if (!this.required) {
      dojo.removeClass(this.domNode, "dijitError");
      return true;
    };

    var v = !! this.attr("value");

    if (v) {
      dojo.removeClass(this.domNode, "dijitError")
    }
    else {
      dojo.addClass(this.domNode, "dijitError");
    }

    return v;
  },

  _refreshState: function() {
    this.inherited(arguments);
    this.validate();
  }

});