// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator = (function(superClass) {
  extend(PdfCreator, superClass);

  function PdfCreator() {
    return PdfCreator.__super__.constructor.apply(this, arguments);
  }

  PdfCreator.VERSION = 2;

  PdfCreator.prototype.initOpts = function() {
    PdfCreator.__super__.initOpts.call(this);
    this.addOpts({
      data: {
        check: "PlainObject",
        "default": {}
      },
      idObjecttype: {
        check: "Integer",
        mandatory: true
      },
      idMask: {
        check: "Integer"
      }
    });
    return this;
  };

  PdfCreator.prototype.readOpts = function() {
    var i, len, name, pdfCreatorPlugin, plugin, plugins, promiseCssPlugin, promiseCssPrint, ref, ref1, ref2, ref3, url;
    PdfCreator.__super__.readOpts.call(this);
    if (!ez5.PdfCreator.nodePlugins) {
      plugins = {};
      ref = ez5.PdfCreator.plugins.getPlugins();
      for (i = 0, len = ref.length; i < len; i++) {
        plugin = ref[i];
        name = plugin.getName();
        if (plugins[name]) {
          console.warn("PdfCreator :: Skipping plugin with duplicated name: " + name);
          continue;
        }
        plugins[name] = plugin;
      }
      ez5.PdfCreator.nodePlugins = plugins;
    }
    if (!ez5.PdfCreator.fetchPrintCSSPromise) {
      ez5.PdfCreator.printSyles = "";
      pdfCreatorPlugin = ez5.pluginManager.getPlugin("pdf-creator");
      promiseCssPlugin = new CUI.XHR({
        url: ez5.getAbsoluteURL(pdfCreatorPlugin.getBaseURL() + pdfCreatorPlugin.getWebfrontend().print_css),
        responseType: "text"
      }).start().done((function(_this) {
        return function(styles) {
          return ez5.PdfCreator.printSyles += styles;
        };
      })(this));
      promiseCssPrint = new CUI.XHR({
        url: Start.getCSSUrl("print", ez5.session.getCSSMode()),
        responseType: "text"
      }).start().done((function(_this) {
        return function(styles) {
          return ez5.PdfCreator.printSyles += styles;
        };
      })(this));
      ez5.PdfCreator.fetchPrintCSSPromise = CUI.whenAll(promiseCssPlugin, promiseCssPrint);
    }
    url = (ref1 = ez5.session.getConfigPicture("logo")) != null ? (ref2 = ref1.versions) != null ? (ref3 = ref2.original) != null ? ref3.url : void 0 : void 0 : void 0;
    if (url && !ez5.PdfCreator.logoImage) {
      promiseCssPlugin = new CUI.XHR({
        method: "GET",
        url: url,
        responseType: "blob"
      });
      promiseCssPlugin.start().done((function(_this) {
        return function(blob) {
          var fileReader;
          fileReader = new FileReader();
          fileReader.readAsDataURL(blob);
          return fileReader.onloadend = function() {
            ez5.PdfCreator.logoImage = fileReader.result;
            return promiseCssPlugin.destroy();
          };
        };
      })(this));
    }
    if (!this._data.templates) {
      this._data.templates = [];
    }
    return this;
  };

  PdfCreator.prototype.renderList = function() {
    var _, cols, copyButton, data, downloadTemplatesButton, editButton, header, i, j, len, len1, minusButton, pane, plusButton, ref, ref1, uploadTemplatesButton;
    header = ez5.PdfCreator.Template.Row.getHeader();
    cols = [];
    ref = header.getColumns();
    for (i = 0, len = ref.length; i < len; i++) {
      _ = ref[i];
      cols.push("auto");
    }
    this.__listView = new CUI.ListView({
      rowMove: false,
      cols: cols,
      selectableRows: true,
      fixedRows: 1,
      onSelect: (function(_this) {
        return function() {
          minusButton.enable();
          editButton.enable();
          return copyButton.enable();
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          minusButton.disable();
          editButton.disable();
          return copyButton.disable();
        };
      })(this)
    });
    this.__listView.appendRow(header);
    plusButton = new CUI.Button({
      icon: "plus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          return _this.__showModal();
        };
      })(this)
    });
    minusButton = new CUI.Button({
      icon: "minus",
      group: "plus-minus",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          CUI.confirm({
            text: $$("pdf-creator.list.confirmation.remove-template|text")
          }).done(function() {
            var data, selectedRow;
            selectedRow = _this.__getSelectedRow();
            data = selectedRow.getData();
            selectedRow.remove();
            CUI.util.removeFromArray(data, _this._data.templates);
            CUI.Events.trigger({
              type: "data-changed",
              node: _this.__listView
            });
            minusButton.disable();
            editButton.disable();
            return copyButton.disable();
          });
        };
      })(this)
    });
    editButton = new CUI.Button({
      icon: "edit",
      group: "edit-copy",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var data;
          data = _this.__getSelectedRow().getData();
          _this.__showModal(data);
        };
      })(this)
    });
    copyButton = new CUI.Button({
      icon: "fa-files-o",
      group: "edit-copy",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var copiedData;
          copiedData = CUI.util.copyObject(_this.__getSelectedRow().getData(), true);
          _this.__addRow(copiedData);
          _this._data.templates.push(copiedData);
          CUI.Events.trigger({
            type: "data-changed",
            node: _this.__listView
          });
        };
      })(this)
    });
    downloadTemplatesButton = new LocaButton({
      loca_key: "pdf-creator.list.download-templates.button",
      group: "download-upload",
      onClick: (function(_this) {
        return function() {
          var data;
          data = {
            version: ez5.PdfCreator.VERSION,
            templates: _this._data.templates
          };
          return CUI.FileReader.save(ez5.session.getEasydbName() + "-pdf-templates.json", JSON.stringify(data, null, "    "));
        };
      })(this)
    });
    uploadTemplatesButton = new CUI.FileUploadButton({
      fileUpload: new CUI.FileReader({
        onDone: (function(_this) {
          return function(fileReaderResult) {
            var data, j, len1, ref1, template;
            try {
              data = JSON.parse(fileReaderResult.getResult());
              if (data.version !== ez5.PdfCreator.VERSION) {
                CUI.problem({
                  text: $$("pdf-creator.list.upload-templates.wrong-version-error", {
                    file_version: data.version,
                    version: ez5.PdfCreator.VERSION
                  })
                });
                return;
              }
              if (CUI.util.isEmpty(data.templates)) {
                CUI.problem({
                  text: $$("pdf-creator.list.upload-templates.no-templates-error")
                });
                return;
              }
              ref1 = data.templates;
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                template = ref1[j];
                _this.__addRow(template);
                _this._data.templates.push(template);
              }
              CUI.Events.trigger({
                type: "data-changed",
                node: _this.__listView
              });
            } catch (error) {
              CUI.problem({
                text: $$("pdf-creator.list.upload-templates.json-error")
              });
            }
          };
        })(this)
      }),
      tooltip: {
        text: $$("pdf-creator.list.upload-templates.button|tooltip")
      },
      icon: $$("pdf-creator.list.upload-templates.button|icon"),
      group: "download-upload",
      multiple: false
    });
    pane = new CUI.SimplePane({
      footer_left: new CUI.Buttonbar({
        buttons: [plusButton, minusButton, editButton, copyButton, downloadTemplatesButton, uploadTemplatesButton]
      }),
      content: this.__listView
    });
    ref1 = this._data.templates;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      data = ref1[j];
      this.__addRow(data);
    }
    this.__listView.render();
    return pane;
  };

  PdfCreator.prototype.__addRow = function(data) {
    var row, template;
    template = new ez5.PdfCreator.Template({
      data: data
    });
    row = new ez5.PdfCreator.Template.Row({
      template: template
    });
    this.__listView.appendRow(row);
  };

  PdfCreator.prototype.__getSelectedRow = function() {
    return this.__listView.getSelectedRows()[0];
  };

  PdfCreator.prototype.__showModal = function(data) {
    var pdfCreatorModal;
    pdfCreatorModal = new ez5.PdfCreator.Modal({
      idObjecttype: this._idObjecttype,
      idMask: this._idMask,
      data: data,
      onSave: (function(_this) {
        return function(dataSaved) {
          var ref;
          if (!_this._data.templates.includes(dataSaved)) {
            _this._data.templates.push(dataSaved);
            _this.__addRow(dataSaved);
          }
          CUI.Events.trigger({
            type: "data-changed",
            node: _this.__listView
          });
          if ((ref = _this.__getSelectedRow()) != null) {
            ref.reload();
          }
        };
      })(this)
    });
    pdfCreatorModal.open();
  };

  PdfCreator.prototype.getTemplateSelect = function(selectOpts) {
    var data, defaultOpts, displayName, i, len, options, ref, template;
    if (selectOpts == null) {
      selectOpts = {};
    }
    options = [
      {
        text: $$("pdf-creator.select.option.not-selected|text"),
        value: null
      }
    ];
    ref = this._data.templates;
    for (i = 0, len = ref.length; i < len; i++) {
      data = ref[i];
      template = new ez5.PdfCreator.Template({
        data: data
      });
      displayName = template.getDisplayName();
      options.push({
        text: displayName,
        value: data
      });
    }
    selectOpts.options = options;
    defaultOpts = {
      name: "pdf_creator_template"
    };
    CUI.util.mergeMap(selectOpts, defaultOpts);
    return new CUI.Select(selectOpts);
  };

  PdfCreator.print = function(data, objects, idMask) {
    var pdfCreatorTemplate;
    pdfCreatorTemplate = new ez5.PdfCreator.Template({
      data: data
    });
    return pdfCreatorTemplate.print(objects, idMask);
  };

  PdfCreator.getPlugin = function(name) {
    return this.nodePlugins[name];
  };

  PdfCreator.getTemplateFields = function(pdfTemplateData) {
    var collectFields, pdfTemplateFields, topNodes;
    pdfTemplateFields = {};
    topNodes = pdfTemplateData.documentData.children;
    collectFields = function(pdfNodes) {
      var fieldName, fieldValue, i, len, node, selectedFields;
      for (i = 0, len = pdfNodes.length; i < len; i++) {
        node = pdfNodes[i];
        if (node.data.dataFields) {
          selectedFields = ez5.PdfCreator.Node.Field.getSelectedFields(node.data);
          for (fieldName in selectedFields) {
            fieldValue = selectedFields[fieldName];
            pdfTemplateFields[fieldName] = fieldValue;
            pdfTemplateFields[fieldName].display_name = ez5.loca.getBestFrontendValue(fieldValue.label);
          }
        }
        if (node.children) {
          collectFields(node.children);
        }
      }
    };
    collectFields(topNodes);
    return pdfTemplateFields;
  };

  return PdfCreator;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Template = (function(superClass) {
  extend(Template, superClass);

  function Template() {
    return Template.__super__.constructor.apply(this, arguments);
  }

  Template.prototype.initOpts = function() {
    Template.__super__.initOpts.call(this);
    this.addOpts({
      data: {
        check: "PlainObject"
      }
    });
    return this;
  };

  Template.prototype.getDisplayName = function() {
    return ez5.loca.getBestFrontendValue(this._data.name) || $$("pdf-creator.list.template-name.default-value");
  };

  Template.prototype.getData = function() {
    return this._data;
  };

  Template.prototype.print = function(objects, idMask) {
    var data, documentData, pdfDocumentNode, printPromise;
    data = CUI.util.copyObject(this._data.documentData, true);
    documentData = ez5.PdfCreatorUtils.initDocumentData(data);
    documentData.idMask = idMask;
    pdfDocumentNode = new ez5.PdfCreator.Node.Document(documentData);
    printPromise = ez5.PdfCreatorUtils.print(objects, pdfDocumentNode).fail(function(errorMessage) {
      if (CUI.util.isString(errorMessage)) {
        return CUI.problem({
          text: errorMessage
        });
      }
    });
    return printPromise;
  };

  return Template;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Template.Row = (function(superClass) {
  extend(Row, superClass);

  function Row() {
    return Row.__super__.constructor.apply(this, arguments);
  }

  Row.prototype.initOpts = function() {
    Row.__super__.initOpts.call(this);
    this.addOpts({
      template: {
        check: ez5.PdfCreator.Template
      }
    });
    return this;
  };

  Row.prototype.readOpts = function() {
    Row.__super__.readOpts.call(this);
    this.__labelName = new CUI.Label({
      text: ""
    });
    this.__labelDateCreated = new CUI.Label({
      text: ""
    });
    this.__labelDateLastModified = new CUI.Label({
      text: ""
    });
    this.__labelUserCreate = new CUI.Label({
      text: ""
    });
    this.__labelUserLastModify = new CUI.Label({
      text: ""
    });
    this.addColumn(new CUI.ListViewColumn({
      element: this.__labelName
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: this.__labelDateCreated
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: this.__labelDateLastModified
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: this.__labelUserCreate
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: this.__labelUserLastModify
    }));
    this.reload();
  };

  Row.prototype.getData = function() {
    return this._template.getData();
  };

  Row.prototype.reload = function() {
    var data;
    data = this.getData();
    this.__labelName.setText(this._template.getDisplayName());
    this.__labelDateCreated.setText(ez5.format_date_and_time(data.date_created));
    this.__labelDateLastModified.setText(ez5.format_date_and_time(data.date_last_modified));
    this.__labelUserCreate.setText(data.user_create);
    this.__labelUserLastModify.setText(data.user_last_modify);
  };

  Row.getHeader = function() {
    var header;
    header = new CUI.ListViewRow({
      selectable: false
    });
    header.addColumn(new CUI.ListViewHeaderColumn({
      label: {
        text: $$("pdf-creator.list.header.template-name|text")
      }
    }));
    header.addColumn(new CUI.ListViewHeaderColumn({
      label: {
        text: $$("pdf-creator.list.header.date-created|text")
      }
    }));
    header.addColumn(new CUI.ListViewHeaderColumn({
      label: {
        text: $$("pdf-creator.list.header.date-last-modified|text")
      }
    }));
    header.addColumn(new CUI.ListViewHeaderColumn({
      label: {
        text: $$("pdf-creator.list.header.user-create|text")
      }
    }));
    header.addColumn(new CUI.ListViewHeaderColumn({
      label: {
        text: $$("pdf-creator.list.header.user-last-modify|text")
      }
    }));
    return header;
  };

  return Row;

})(CUI.ListViewRow);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreatorUtils = (function(superClass) {
  extend(PdfCreatorUtils, superClass);

  function PdfCreatorUtils() {
    return PdfCreatorUtils.__super__.constructor.apply(this, arguments);
  }

  PdfCreatorUtils.print = function(objects, pdfDocumentNode) {
    var deferred, fylrUrl, html2pdfUrl, ref, spinner;
    if (objects == null) {
      objects = [];
    }
    spinner = CUI.spinner({
      text: $$("pdf-creator.print.preparing.text")
    });
    if (!pdfDocumentNode || !(pdfDocumentNode instanceof ez5.PdfCreator.Node.Document)) {
      return CUI.rejectedPromise("PdfCreatorUtils.print :: pdfDocument needs to be defined and it needs to be an instance of ez5.PdfCreator.Node.Document", pdfDocumentNode);
    }
    fylrUrl = (ref = ez5.session.getBaseConfig("plugin", "pdf-creator").pdf_creator) != null ? ref.fylr_url : void 0;
    if (CUI.util.isEmpty(fylrUrl)) {
      if (!ez5.version("6")) {
        spinner.destroy();
        return CUI.rejectedPromise($$("pdf-creator.print-url-not-configured"));
      } else if (ez5.pluginManager.getPlugin("server-pdf")) {
        html2pdfUrl = CUI.parseLocation(ez5.pluginManager.getPlugin("server-pdf").getPluginURL()).path;
        fylrUrl = Session.addToken(html2pdfUrl + "/html2pdf");
      } else {
        spinner.destroy();
        return CUI.rejectedPromise($$("pdf-creator.print-url-not-configured.fylr"));
      }
    }
    deferred = new CUI.Deferred();
    this.fetchLinkedObjects(objects).done((function(_this) {
      return function() {
        var customCssUrl, header, headerPromise, html, opts, ref1;
        opts = {
          objects: objects,
          styles: ez5.PdfCreator.printSyles,
          spinner: spinner
        };
        customCssUrl = (ref1 = ez5.session.getBaseConfig("plugin", "pdf-creator").pdf_creator) != null ? ref1.custom_css_url : void 0;
        if (customCssUrl) {
          opts.custom_css_url = customCssUrl;
        }
        html = pdfDocumentNode.renderPdf(opts).outerHTML;
        html = html.replace(/loading="lazy"/g, "");
        headerPromise = pdfDocumentNode.renderHeader(opts);
        header = null;
        if (CUI.util.isPromise(headerPromise)) {
          headerPromise.done(function(headerDOM) {
            return header = headerDOM.outerHTML.replace(/loading="lazy"/g, "");
          });
        } else {
          header = headerPromise.outerHTML.replace(/loading="lazy"/g, "");
          headerPromise = CUI.resolvedPromise();
        }
        return headerPromise.done(function() {
          var data, filename, footer, margins, xhr;
          footer = pdfDocumentNode.renderFooter(opts).outerHTML;
          footer = footer.replace(/loading="lazy"/g, "");
          margins = pdfDocumentNode.getMargins();
          filename = pdfDocumentNode.getFilename(objects[0]);
          data = {
            file_name: filename,
            document: html,
            properties: {
              displayHeaderFooter: true,
              printBackground: true,
              headerTemplate: header,
              footerTemplate: footer,
              landscape: pdfDocumentNode.isLandscape(),
              paperWidth: pdfDocumentNode.getPaperWidth(),
              paperHeight: pdfDocumentNode.getPaperHeight(),
              marginTop: margins.top,
              marginBottom: margins.bottom,
              marginLeft: margins.left,
              marginRight: margins.right
            }
          };
          spinner.updateText($$("pdf-creator.print.rendering.text"));
          spinner.autoSize();
          xhr = new CUI.XHR({
            method: "POST",
            url: fylrUrl,
            body: JSON.stringify(data),
            responseType: "blob"
          });
          return xhr.start().done(function(response) {
            CUI.FileReader.save(filename, response, "application/pdf");
            return deferred.resolve();
          }).fail(deferred.reject).always(function() {
            return spinner.destroy();
          });
        });
      };
    })(this));
    return deferred.promise();
  };

  PdfCreatorUtils.initDocumentData = function(data) {
    var children, initNodes;
    initNodes = (function(_this) {
      return function(children) {
        var child, i, len, node, nodes, plugin;
        nodes = [];
        if (!children) {
          return null;
        }
        for (i = 0, len = children.length; i < len; i++) {
          child = children[i];
          plugin = ez5.PdfCreator.getPlugin(child.name);
          if (!plugin) {
            console.warn("PdfCreator :: Load :: Skipping unknown type of plugin, name: '" + child.name + "'");
            continue;
          }
          node = new plugin({
            data: child.data,
            open: child.open,
            children: initNodes(child.children)
          });
          nodes.push(node);
        }
        return nodes;
      };
    })(this);
    children = data.children;
    if (children) {
      data.children = initNodes(children);
    }
    return data;
  };

  PdfCreatorUtils.fetchLinkedObjects = function(objects) {
    var deferred, findLinkedObject, i, len, object, objectsToFetch;
    objectsToFetch = {};
    findLinkedObject = function(object) {
      var _, _value, format, formatIncomplete, globalObjectId, i, len, value;
      if (!CUI.util.isPlainObject(object)) {
        return;
      }
      globalObjectId = object._global_object_id;
      format = object._format;
      formatIncomplete = object._format_incomplete;
      if (globalObjectId && (format !== "long" || formatIncomplete)) {
        if (!objectsToFetch[globalObjectId]) {
          objectsToFetch[globalObjectId] = [];
        }
        objectsToFetch[globalObjectId].push(object);
      }
      for (_ in object) {
        value = object[_];
        if (CUI.util.isArray(value)) {
          for (i = 0, len = value.length; i < len; i++) {
            _value = value[i];
            findLinkedObject(_value);
          }
        } else {
          findLinkedObject(value);
        }
      }
    };
    for (i = 0, len = objects.length; i < len; i++) {
      object = objects[i];
      findLinkedObject(object);
    }
    if (CUI.util.isEmptyObject(objectsToFetch)) {
      return CUI.resolvedPromise();
    }
    deferred = new CUI.Deferred();
    ez5.api.search_no_limit({
      json_data: {
        limit: 1000000,
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["_global_object_id"],
            "in": Object.keys(objectsToFetch)
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var _objectLongFormat, _objects, j, k, len1, len2, ref;
        ref = data.objects;
        for (j = 0, len1 = ref.length; j < len1; j++) {
          _objectLongFormat = ref[j];
          _objects = objectsToFetch[_objectLongFormat._global_object_id] || [];
          for (k = 0, len2 = _objects.length; k < len2; k++) {
            object = _objects[k];
            CUI.util.mergeMap(object, _objectLongFormat);
            object._format = _objectLongFormat._format;
          }
        }
        return deferred.resolve();
      };
    })(this));
    return deferred.promise();
  };

  PdfCreatorUtils.replaceTextPlaceholders = function(text, object) {
    var i, key, len, ref, ref1, regexp, standardText;
    text = text.replace(/%username%/g, ez5.session.getUser().getDisplayText());
    text = text.replace(/%date%/g, ez5.format_date(CUI.util.moment()));
    if (!object) {
      return text;
    }
    ref = ["_global_object_id", "_system_object_id"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      regexp = new RegExp("%" + key + "%", "g");
      text = text.replace(regexp, object[key] || key);
    }
    standardText = ez5.loca.getBestFrontendValue((ref1 = object._standard["1"]) != null ? ref1.text : void 0) || "-";
    text = text.replace(/%_standard\.1\.text%/g, standardText);
    return text;
  };

  return PdfCreatorUtils;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Modal = (function(superClass) {
  extend(Modal, superClass);

  function Modal() {
    this.__setZoom = bind(this.__setZoom, this);
    this.__buildTree = bind(this.__buildTree, this);
    this.__onWheel = bind(this.__onWheel, this);
    this.__updatePreviewNavigation = bind(this.__updatePreviewNavigation, this);
    return Modal.__super__.constructor.apply(this, arguments);
  }

  Modal.prototype.initOpts = function() {
    Modal.__super__.initOpts.call(this);
    this.addOpts({
      data: {
        check: "PlainObject",
        "default": {}
      },
      onSave: {
        check: Function
      },
      idObjecttype: {
        check: "Integer",
        mandatory: true
      },
      idMask: {
        check: "Integer"
      }
    });
    return this;
  };

  Modal.prototype.readOpts = function() {
    var collection, content, i, len, mask, maskInstances, masks, mfs, searchPopover, selectedMaskName;
    Modal.__super__.readOpts.call(this);
    this.__currentZoom = 100;
    this.__previewObjects = [];
    this.__saveButton = new LocaButton({
      loca_key: "pdf-creator.modal.save.button",
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function() {
          _this.__save();
          if (typeof _this._onSave === "function") {
            _this._onSave(_this._data);
          }
          return _this.__modal.destroy();
        };
      })(this)
    });
    this.__printPreviewButton = new LocaButton({
      loca_key: "pdf-creator.preview.print.button",
      group: "print-preview",
      left: true,
      disabled: true,
      onClick: (function(_this) {
        return function() {
          _this.__printPreviewButton.startSpinner();
          return _this.__printPreview().fail(function(errorMessage) {
            if (!CUI.util.isString(errorMessage)) {
              errorMessage = $$("pdf-creator.preview.print.error-message");
            }
            return CUI.problem({
              text: errorMessage
            });
          }).always(function() {
            return _this.__printPreviewButton.stopSpinner();
          });
        };
      })(this)
    });
    masks = ez5.mask.CURRENT._masks_by_table_id[this._idObjecttype];
    maskInstances = [Mask.getMaskByMaskName("_all_fields", this._idObjecttype)];
    for (i = 0, len = masks.length; i < len; i++) {
      mask = masks[i];
      if (mask.mask_id === this._idMask) {
        selectedMaskName = mask.name;
      }
      maskInstances.push(ez5.mask.CURRENT._mask_instance_by_name[mask.name]);
    }
    mfs = new MaskFieldSelectorDetail({
      mask_name: selectedMaskName || "_all_fields",
      masks: maskInstances,
      show_all_fields_mask: true,
      onChanged: (function(_this) {
        return function(old_mask, new_mask) {
          var ref;
          _this._idMask = (ref = ez5.mask.CURRENT._mask_instance_by_name[new_mask]) != null ? ref._id : void 0;
          _this.__pdfDocumentNode.setMask(_this._idMask);
          _this.__updatePreview();
          return CUI.resolvedPromise();
        };
      })(this)
    });
    this.__maskSelector = mfs.getSelect().start();
    this.__previewObjectPage = 0;
    this.__previewObjectOffset = 0;
    this.__previewObjectNavigation = new NavigationToolbar({
      onLoadPage: (function(_this) {
        return function(__previewObjectPage) {
          _this.__previewObjectPage = __previewObjectPage;
          _this.__updatePreview();
        };
      })(this)
    });
    this.__searchPopoverButton = new LocaButton({
      loca_key: "pdf-creator.preview.select-objects.button",
      group: "print-preview",
      left: true,
      disabled: false,
      onClick: (function(_this) {
        return function() {
          return searchPopover.openPopover();
        };
      })(this)
    });
    content = this.__buildModalContent();
    mask = this.__pdfDocumentNode.getMask();
    collection = new CollectionMemory;
    searchPopover = new SearchPopover({
      link_mask: mask,
      popover_element: this.__searchPopoverButton,
      collection: collection,
      request_format: "long",
      onDone: (function(_this) {
        return function() {
          _this.__previewLabel.setText($$("pdf-creator.preview.selected-objects|label", {
            count: collection.getCount()
          }));
          _this.__previewObjects = collection.getObjects().map(function(object) {
            return object.getObject();
          });
          _this.__searchPopoverButton.startSpinner();
          return ez5.PdfCreatorUtils.fetchLinkedObjects(_this.__previewObjects).done(function() {
            _this.__previewObjectPage = 0;
            _this.__updatePreview();
            if (_this.__previewObjects.length > 0) {
              _this.__printPreviewButton.enable();
            } else {
              _this.__printPreviewButton.disable();
            }
            return _this.__searchPopoverButton.stopSpinner();
          });
        };
      })(this)
    });
    this.__modal = new CUI.Modal({
      fill_space: "both",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          if (!_this.__saveButton.isEnabled()) {
            return _this.__modal.destroy();
          }
          return CUI.confirm({
            text: $$("pdf-creator.modal.close.confirmation|text")
          }).done(function() {
            return _this.__modal.destroy();
          });
        };
      })(this),
      pane: {
        "class": "pdf-creator",
        header_left: new CUI.Label({
          text: $$("pdf-creator.title")
        }),
        content: content,
        footer_right: this.__saveButton,
        footer_left: new CUI.HorizontalList({
          content: new CUI.Buttonbar({
            buttons: [this.__printPreviewButton, this.__searchPopoverButton, this.__maskSelector]
          })
        })
      }
    });
    return this;
  };

  Modal.prototype.__printPreview = function() {
    var pdfCreatorTemplate;
    pdfCreatorTemplate = new ez5.PdfCreator.Template({
      data: this._data
    });
    return pdfCreatorTemplate.print(this.__previewObjects);
  };

  Modal.prototype.__checkSaveData = function() {
    var ref, saveData;
    saveData = this.__getSaveData();
    if (CUI.util.isEqual((ref = this._data) != null ? ref.documentData : void 0, saveData.documentData)) {
      this.__saveButton.disable();
    } else {
      this.__saveButton.enable();
    }
  };

  Modal.prototype.__getSaveData = function() {
    var saveData;
    saveData = {
      documentData: this.__pdfDocumentNode.getSaveData(),
      zoom: this.__currentZoom,
      name: this.__pdfDocumentNode.getTemplateName()
    };
    return saveData;
  };

  Modal.prototype.__save = function() {
    var date, saveData;
    date = CUI.util.moment().format();
    saveData = this.__getSaveData();
    this._data.documentData = saveData.documentData;
    this._data.zoom = saveData.zoom;
    this._data.name = saveData.name;
    this._data.date_last_modified = date;
    this._data.id_objecttype = this._idObjecttype;
    this._data.user_last_modify = ez5.session.user.getDisplayText();
    if (!this._data.user_create) {
      this._data.user_create = this._data.user_last_modify;
    }
    if (!this._data.date_created) {
      this._data.date_created = date;
    }
  };

  Modal.prototype.__loadData = function() {
    var documentData, saveData, tree, waitBlock;
    if (CUI.util.isEmpty(this._data)) {
      this.__pdfDocumentNode.select();
      return;
    }
    waitBlock = new CUI.WaitBlock({
      element: this.__treePane.center()
    }).show();
    saveData = CUI.util.copyObject(this._data, true);
    if (saveData.zoom) {
      this.__currentZoom = saveData.zoom;
    }
    documentData = ez5.PdfCreatorUtils.initDocumentData(saveData.documentData);
    tree = this.__buildTree(documentData);
    this.__treePane.append(tree, "center");
    this.__pdfDocumentNode.open();
    this.__pdfDocumentNode.select().done((function(_this) {
      return function() {
        _this.__updatePreview();
        return waitBlock.destroy();
      };
    })(this));
  };

  Modal.prototype.open = function() {
    this.__modal.show();
    ez5.PdfCreator.fetchPrintCSSPromise.done((function(_this) {
      return function() {
        _this.__loadData();
        return _this.__updatePreview();
      };
    })(this));
  };

  Modal.prototype.__updateSettingsForm = function() {
    var label, onDataChanged, opts, selectedNode;
    if (this.__settingsForm) {
      this.__settingsForm.destroy();
    }
    selectedNode = this.__tree.getSelectedNode();
    if (!selectedNode) {
      label = new EmptyLocaLabel({
        text: $$("pdf-creator.settings.node-not-selected"),
        centered: true
      });
      this.__settingsPane.replace(label);
      return;
    }
    onDataChanged = (function(_this) {
      return function() {
        return _this.__updatePreview();
      };
    })(this);
    opts = {
      onDataChanged: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 200,
            call: onDataChanged
          });
        };
      })(this)
    };
    this.__settingsForm = selectedNode.getSettingsForm(opts);
    this.__settingsPane.replace(this.__settingsForm);
    this.__settingsLabel.setText($$("pdf-creator.settings.title", {
      name: selectedNode.getDisplayName()
    }));
  };

  Modal.prototype.__updatePreviewNavigation = function() {
    var maxCountPerPage;
    maxCountPerPage = this.__pdfDocumentNode.getMaxCountPerPage();
    this.__previewObjectOffset = this.__previewObjectPage * maxCountPerPage;
    if (this.__previewObjectOffset > this.__previewObjects.length) {
      this.__previewObjectPage = 0;
      this.__previewObjectOffset = 0;
    }
    this.__previewObjectNavigation.update({
      count: this.__previewObjects.length,
      offset: this.__previewObjectOffset,
      limit: maxCountPerPage
    });
  };

  Modal.prototype.__updatePreview = function() {
    var count, height, html, noPreviewObjectsLabel, opts, ref, width;
    opts = {
      preview: true,
      objects: [],
      selectedNode: this.__tree.getSelectedNode(),
      styles: ez5.PdfCreator.printSyles,
      custom_css_url: (ref = ez5.session.getBaseConfig("plugin", "pdf-creator")) != null ? ref.custom_css_url : void 0
    };
    if (CUI.util.isEmpty(this.__previewObjects)) {
      noPreviewObjectsLabel = new EmptyLocaLabel({
        "class": "pdf-creator-preview-no-objects-label",
        text: $$("pdf-creator.preview.subtitle.md"),
        centered: true,
        markdown: true
      });
      CUI.dom.replace(this.__iframeWrapper, noPreviewObjectsLabel);
      this.__zoomButtonbar.disable();
      this.__checkSaveData();
      return;
    }
    if (this.__iframeWrapper.children[0] !== this.__zoomWrapper) {
      CUI.dom.replace(this.__iframeWrapper, this.__zoomWrapper);
      this.__zoomButtonbar.enable();
    }
    this.__updatePreviewNavigation();
    count = this.__pdfDocumentNode.getMaxCountPerPage();
    opts.objects = this.__previewObjects.slice(this.__previewObjectOffset, this.__previewObjectOffset + count);
    width = this.__pdfDocumentNode.getWidth();
    height = this.__pdfDocumentNode.getHeight();
    if (width !== this.__documentWidth || height !== this.__documentHeight) {
      this.__documentWidth = width;
      this.__documentHeight = height;
      CUI.dom.setStyle(this.__iframe, {
        width: this.__documentWidth + "cm",
        height: this.__documentHeight + "cm"
      });
    }
    html = this.__pdfDocumentNode.renderPdf(opts);
    this.__iframe.contentDocument.children[0].replaceWith(html);
    this.__setZoom();
    html.children[1].addEventListener("wheel", (function(_this) {
      return function(ev) {
        _this.__onWheel(ev.deltaY);
        ev.preventDefault();
      };
    })(this), {
      passive: false
    });
    this.__checkSaveData();
  };

  Modal.prototype.__buildModalContent = function() {
    var content, previewPane, tree;
    tree = this.__buildTree({
      open: true
    });
    this.__addButton = new CUI.Button({
      group: "tree_actions",
      icon: "plus",
      disabled: true,
      menu: {
        items: (function(_this) {
          return function() {
            var _, fn, items, plugin, pluginNode, ref, selectedNode;
            selectedNode = _this.__tree.getSelectedNode();
            items = [];
            ref = ez5.PdfCreator.nodePlugins;
            fn = function(pluginNode) {
              return items.push({
                text: pluginNode.getDisplayName(),
                disabled: !pluginNode.isParentAllowed(selectedNode),
                onClick: function() {
                  return _this.__tree.getSelectedNode().addNode(pluginNode).done(function() {
                    return pluginNode.select().done(function() {
                      return _this.__updatePreview();
                    });
                  });
                }
              });
            };
            for (_ in ref) {
              plugin = ref[_];
              pluginNode = new plugin();
              fn(pluginNode);
            }
            return items;
          };
        })(this)
      }
    });
    this.__removeButton = new CUI.Button({
      group: "tree_actions",
      icon: "minus",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          return CUI.confirm({
            text: $$("pdf-creator.elements.buttons.remove.confirmation")
          }).done(function() {
            _this.__tree.getSelectedNode().remove();
            return _this.__updatePreview();
          });
        };
      })(this)
    });
    this.__moveToBottomButton = new CUI.Button({
      icon: $$("tool.mask_editor.move_to_bottom|icon"),
      group: "tree_actions",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          return _this.__moveSelectedNodeToBottom();
        };
      })(this)
    });
    this.__moveToTopButton = new CUI.Button({
      icon: $$("tool.mask_editor.move_to_top|icon"),
      group: "tree_actions",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          return _this.__moveSelectedNodeToTop();
        };
      })(this)
    });
    this.__moveUpButton = new CUI.Button({
      group: "tree_actions",
      icon: "fa-angle-up",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          return _this.__moveSelectedNode(false);
        };
      })(this)
    });
    this.__moveDownButton = new CUI.Button({
      group: "tree_actions",
      icon: "fa-angle-down",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          return _this.__moveSelectedNode(true);
        };
      })(this)
    });
    this.__copyButton = new CUI.Button({
      group: "tree_more_actions",
      icon: "copy",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var node, ref, selectedNode;
          selectedNode = _this.__tree.getSelectedNode();
          node = selectedNode.copy();
          if (!node) {
            return;
          }
          if ((ref = selectedNode.getFather()) != null) {
            ref.addChild(node);
          }
          return _this.__updatePreview();
        };
      })(this)
    });
    this.__zoomLabel = new CUI.Label({
      text: "",
      appearance: "secondary"
    });
    this.__zoomButtonbar = new CUI.Buttonbar({
      buttons: [
        this.__zoomLabel, {
          icon: "zoom_out",
          group: "zoom",
          onClick: (function(_this) {
            return function() {
              return _this.__setZoom(-2);
            };
          })(this)
        }, {
          loca_key: "pdf-creator.zoom.fit-view",
          group: "zoom",
          onClick: (function(_this) {
            return function() {
              var heightZoom, widthZoom, zoom;
              heightZoom = _this.__iframeWrapper.clientHeight / _this.__zoomWrapper.clientHeight;
              widthZoom = _this.__iframeWrapper.clientWidth / _this.__zoomWrapper.clientWidth;
              zoom = heightZoom < widthZoom ? heightZoom : widthZoom;
              _this.__currentZoom = Math.floor(zoom * 100);
              _this.__setZoom();
              _this.__zoomWrapper.scrollIntoView();
              return _this.__iframeWrapper.scrollLeft = CUI.dom.getDimension(_this.__iframeWrapper, "paddingLeft");
            };
          })(this)
        }, {
          icon: "zoom_in",
          group: "zoom",
          onClick: (function(_this) {
            return function() {
              return _this.__setZoom(2);
            };
          })(this)
        }
      ]
    });
    this.__iframeWrapper = CUI.dom.div("pdf-creator-iframe-wrapper");
    this.__zoomWrapper = CUI.dom.div("pdf-creator-iframe-wrapper-zoom");
    this.__iframe = CUI.dom.$element("iframe", "pdf-creator-iframe-preview");
    CUI.dom.append(this.__zoomWrapper, this.__iframe);
    CUI.dom.append(this.__iframeWrapper, this.__zoomWrapper);
    this.__previewLabel = new CUI.Label({
      text: $$("pdf-creator.preview.title")
    });
    previewPane = new CUI.SimplePane({
      header_left: this.__previewLabel,
      header_right: this.__zoomButtonbar,
      content: this.__iframeWrapper,
      footer_center: this.__previewObjectNavigation
    });
    CUI.Events.listen({
      node: this.__iframeWrapper,
      type: "wheel",
      call: (function(_this) {
        return function(ev) {
          _this.__onWheel(ev.wheelDeltaY());
          ev.preventDefault();
        };
      })(this)
    });
    this.__settingsLabel = new CUI.Label({
      text: $$("pdf-creator.settings.title.node-not-selected")
    });
    this.__settingsPane = new CUI.SimplePane({
      header_left: this.__settingsLabel
    });
    this.__updateSettingsForm();
    this.__treePane = new CUI.SimplePane({
      header_left: new CUI.Label({
        text: $$("pdf-creator.elements.title")
      }),
      content: tree,
      footer_left: new CUI.Buttonbar({
        buttons: [this.__addButton, this.__removeButton, this.__copyButton, this.__moveToTopButton, this.__moveUpButton, this.__moveDownButton, this.__moveToBottomButton]
      })
    });
    content = new CUI.HorizontalLayout({
      left: {
        "class": "pdf-creator-tree",
        flexHandle: {
          state_name: "pdf-creator-left",
          hidden: false
        },
        content: this.__treePane
      },
      center: {
        "class": "pdf-creator-preview",
        content: previewPane
      },
      right: {
        "class": "pdf-creator-settings",
        flexHandle: {
          state_name: "pdf-creator-right",
          hidden: false
        },
        content: this.__settingsPane
      }
    });
    return content;
  };

  Modal.prototype.__onWheel = function(deltaY) {
    if (deltaY > 0) {
      this.__setZoom(-2);
    } else {
      this.__setZoom(2);
    }
  };

  Modal.prototype.__buildTree = function(opts) {
    var ref, updatePreview;
    if (opts == null) {
      opts = {};
    }
    if (this.__tree) {
      this.__tree.destroy();
      if ((ref = this.__pdfDocumentNode) != null) {
        ref.destroy();
      }
    }
    if (!opts.idObjecttype) {
      opts.idObjecttype = this._idObjecttype;
    }
    if (!opts.idMask) {
      opts.idMask = this._idMask;
    }
    updatePreview = (function(_this) {
      return function() {
        return _this.__updatePreview();
      };
    })(this);
    this.__pdfDocumentNode = new ez5.PdfCreator.Node.Document(opts);
    this.__tree = new CUI.ListViewTree({
      selectableRows: true,
      rowMove: true,
      root: new CUI.ListViewTreeNode({
        children: [this.__pdfDocumentNode]
      }),
      cols: ["maximize"],
      onSelect: (function(_this) {
        return function() {
          var selectedNode;
          _this.__updateSettingsForm();
          selectedNode = _this.__tree.getSelectedNode();
          if (!selectedNode) {
            return;
          }
          _this.__addButton.disable();
          _this.__addButton.getMenu().getItemList().getItems().done(function(items) {
            if (items.some(function(item) {
              return !item.disabled;
            })) {
              return _this.__addButton.enable();
            } else {
              return _this.__addButton.disable();
            }
          });
          if (selectedNode === _this.__pdfDocumentNode) {
            _this.__removeButton.disable();
            _this.__moveToTopButton.disable();
            _this.__moveToBottomButton.disable();
            _this.__moveUpButton.disable();
            _this.__moveDownButton.disable();
          } else {
            _this.__removeButton.enable();
            _this.__moveToTopButton.enable();
            _this.__moveToBottomButton.enable();
            _this.__moveUpButton.enable();
            _this.__moveDownButton.enable();
          }
          if (selectedNode.isCopyAllowed()) {
            _this.__copyButton.enable();
          } else {
            _this.__copyButton.disable();
          }
          CUI.scheduleCallback({
            ms: 200,
            call: updatePreview
          });
        };
      })(this),
      onRowMove: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 200,
            call: updatePreview
          });
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          _this.__updateSettingsForm();
          _this.__removeButton.disable();
          _this.__copyButton.disable();
          _this.__addButton.disable();
          _this.__moveUpButton.disable();
          _this.__moveDownButton.disable();
          _this.__moveToTopButton.disable();
          _this.__moveToBottomButton.disable();
          CUI.scheduleCallback({
            ms: 200,
            call: updatePreview
          });
        };
      })(this)
    });
    this.__tree.render();
    this.__tree.root.open();
    return this.__tree;
  };

  Modal.prototype.__setZoom = function(zoomOffset) {
    var iframeWrapperWidth, leftWidth, scale, zoomWrapperWidth;
    if (zoomOffset && (this.__currentZoom + zoomOffset) > 0) {
      this.__currentZoom += zoomOffset;
    }
    scale = this.__currentZoom / 100;
    CUI.dom.setStyle(this.__zoomWrapper, {
      transform: "scale(" + scale + ", " + scale + ")",
      left: 0
    });
    this.__zoomLabel.setText($$("pdf-creator.zoom|label", {
      zoom: this.__currentZoom
    }));
    iframeWrapperWidth = this.__iframeWrapper.clientWidth;
    zoomWrapperWidth = this.__zoomWrapper.clientWidth * scale;
    leftWidth = (iframeWrapperWidth - zoomWrapperWidth) / 2;
    if (leftWidth > 0) {
      CUI.dom.setStyle(this.__zoomWrapper, {
        left: leftWidth + "px"
      });
    }
  };

  Modal.prototype.__moveSelectedNode = function(after) {
    var nextRowIndex, selectedNode;
    selectedNode = this.__tree.getSelectedNode();
    if (selectedNode.isOpen()) {
      selectedNode.close();
    }
    nextRowIndex = this.__getNextRowIndexForMove(selectedNode, after);
    if (!nextRowIndex) {
      return;
    }
    this.__tree.moveRow(selectedNode.getRowIdx(), nextRowIndex, after);
  };

  Modal.prototype.__moveSelectedNodeToTop = function() {
    var fatherChildren, selectedNode, topIndex;
    selectedNode = this.__tree.getSelectedNode();
    fatherChildren = selectedNode.father.children;
    topIndex = fatherChildren[0].getRowIdx();
    if (fatherChildren === this.__pdfDocumentNode) {
      topIndex++;
    }
    return this.__tree.moveRow(selectedNode.getRowIdx(), topIndex, false);
  };

  Modal.prototype.__moveSelectedNodeToBottom = function() {
    var fatherChildren, lastIdx, lastNode, selectedNode;
    selectedNode = this.__tree.getSelectedNode();
    fatherChildren = selectedNode.father.children;
    lastNode = fatherChildren[fatherChildren.length - 1];
    if (lastNode.children) {
      lastNode.close();
    }
    lastIdx = lastNode.getRowIdx();
    return this.__tree.moveRow(selectedNode.getRowIdx(), lastIdx, true);
  };

  Modal.prototype.__getNextRowIndexForMove = function(node, after) {
    var fatherChildren, getNextRowIndex, quantity, rowIndexInArray;
    quantity = after ? 1 : -1;
    fatherChildren = node.father.children;
    rowIndexInArray = CUI.util.idxInArray(node, fatherChildren);
    getNextRowIndex = (function(_this) {
      return function(_quantity) {
        var nextListViewRow;
        nextListViewRow = fatherChildren[rowIndexInArray + _quantity];
        if (!nextListViewRow) {
          return;
        }
        if (!node.allowRowMove(nextListViewRow, null, after)) {
          return getNextRowIndex(_quantity + quantity);
        }
        return nextListViewRow.getRowIdx();
      };
    })(this);
    return getNextRowIndex(quantity);
  };

  return Modal;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var PdfFieldsFormNode,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

PdfFieldsFormNode = (function(superClass) {
  extend(PdfFieldsFormNode, superClass);

  function PdfFieldsFormNode() {
    return PdfFieldsFormNode.__super__.constructor.apply(this, arguments);
  }

  PdfFieldsFormNode.prototype.getModeForNested = function() {
    return "all";
  };

  PdfFieldsFormNode.prototype.renderContent = function() {
    var nameColumn, nameLocalizedInput, nameLocalizedOutput, nameOutput, row, setState;
    setState = (function(_this) {
      return function(event) {
        var i, len, ref, sibling;
        _this.setCheckbox(_this.data._enabled);
        if (!event.ctrlKey()) {
          _this.setChildren(_this.data._enabled);
        }
        if (event.altKey() || event.shiftKey()) {
          ref = _this.father.children;
          for (i = 0, len = ref.length; i < len; i++) {
            sibling = ref[i];
            sibling.setCheckbox(_this.data._enabled);
            if (!event.ctrlKey()) {
              sibling.setChildren(_this.data._enabled);
            }
          }
        }
      };
    })(this);
    this.checkbox = new CUI.Checkbox({
      name: "_enabled",
      undo_and_changed_support: false,
      data: this.data,
      onClick: (function(_this) {
        return function(event) {
          setState(event);
        };
      })(this)
    });
    this.checkbox.start();
    nameLocalizedOutput = new CUI.Output({
      name: "name_localized",
      data: this.data
    });
    nameLocalizedOutput.start();
    nameOutput = new CUI.Output({
      name: "name",
      data: this.data,
      "class": "cui-label-appearance-secondary"
    });
    nameOutput.start();
    nameColumn = new CUI.VerticalList({
      content: [nameLocalizedOutput, nameOutput]
    });
    CUI.Events.listen({
      node: nameColumn,
      type: "click",
      call: (function(_this) {
        return function(event) {
          _this.data._enabled = !_this.data._enabled;
          setState(event);
        };
      })(this)
    });
    CUI.dom.setAttribute(nameColumn, 'data-label-clickable', '1');
    nameLocalizedInput = new CUI.MultiInput({
      name: "label",
      data: this.data,
      maximize_horizontal: true,
      control: ez5.loca.getLanguageControl()
    });
    nameLocalizedInput.start();
    row = CUI.dom.table_one_row(this.checkbox, nameColumn, nameLocalizedInput);
    CUI.Events.listen({
      node: row,
      type: "click",
      call: (function(_this) {
        return function(ev) {
          ev.stopPropagation();
        };
      })(this)
    });
    this.setCheckbox(this.data._enabled);
    return row;
  };

  PdfFieldsFormNode.prototype.nodeAdded = function(level) {
    var fieldFullName, label;
    PdfFieldsFormNode.__super__.nodeAdded.call(this, level);
    fieldFullName = this.getFieldFullName();
    if (!this._data[fieldFullName]) {
      label = {};
      label[ez5.loca.getLanguage()] = this.field.nameLocalized();
      this._data[fieldFullName] = {
        _enabled: false,
        label: label,
        name_localized: this.field.nameLocalized(),
        name: this.field.name()
      };
    }
    this.data = this._data[fieldFullName];
  };

  PdfFieldsFormNode.prototype.setChildren = function(isEnabled) {
    var c, i, len, ref, results;
    if (!this.children) {
      return;
    }
    ref = this.children;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      c.setCheckbox(isEnabled);
      results.push(c.setChildren(isEnabled));
    }
    return results;
  };

  PdfFieldsFormNode.prototype.setCheckbox = function(isEnabled) {
    var ref;
    if (this.__hidden) {
      return this;
    }
    this.data._enabled = isEnabled;
    if ((ref = this.checkbox) != null) {
      ref.displayValue();
    }
    if (this.father && this.father.checkbox && this.father.isOpen()) {
      if (!this.father.children.some((function(_this) {
        return function(childNode) {
          var ref1;
          return (ref1 = childNode.checkbox) != null ? ref1.getValue() : void 0;
        };
      })(this))) {
        this.father.setCheckbox(false);
      } else {
        this.father.setCheckbox(true);
      }
    }
    return this;
  };

  PdfFieldsFormNode.prototype.open = function() {
    return PdfFieldsFormNode.__super__.open.call(this).done((function(_this) {
      return function() {
        var i, len, node, ref, results;
        if (!_this.children) {
          return;
        }
        ref = _this.children;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          node = ref[i];
          if (node.isHidden()) {
            results.push(node.hide());
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this));
  };

  PdfFieldsFormNode.prototype.isHidden = function() {
    return this.__hidden;
  };

  PdfFieldsFormNode.prototype.hide = function() {
    var element, ref;
    this.__hidden = true;
    element = (ref = this.columns[0]) != null ? ref.getElement() : void 0;
    if (!element) {
      return;
    }
    CUI.dom.hideElement(element);
  };

  PdfFieldsFormNode.prototype.show = function() {
    var element, ref;
    this.__hidden = false;
    element = (ref = this.columns[0]) != null ? ref.getElement() : void 0;
    if (!element) {
      return;
    }
    CUI.dom.showElement(element);
  };

  PdfFieldsFormNode.prototype.getFieldFullName = function() {
    if (this.father) {
      return this.father.getFieldFullName() + "." + this.field.name();
    }
    return this.field.fullName();
  };

  PdfFieldsFormNode.prototype.getLinkedObjectRenderDepth = function() {
    return 2;
  };

  return PdfFieldsFormNode;

})(FieldsFormNode);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node = (function(superClass) {
  extend(Node, superClass);

  function Node() {
    return Node.__super__.constructor.apply(this, arguments);
  }

  Node.getName = function() {
    return "pdf-node";
  };

  Node.getAvailableStyleSettings = function() {
    if (this.styleSettings) {
      return this.styleSettings;
    }
    this.styleSettings = {
      "class-name": {
        group: "basic",
        field: {
          type: CUI.Input,
          name: "class_name",
          form: {
            label: $$("pdf-creator.settings.node.class-name|label")
          }
        }
      },
      "height": {
        group: "basic",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.height|label")
          },
          name: "height"
        }
      },
      "width": {
        group: "basic",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.width|label")
          },
          name: "width"
        }
      },
      "position-absolute": {
        group: "extended",
        field: {
          type: CUI.Checkbox,
          form: {
            label: $$("pdf-creator.settings.node.position-absolute|label")
          },
          name: "position_absolute"
        }
      },
      "display": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.display|label")
          },
          name: "display"
        }
      },
      "background": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.background|label")
          },
          name: "background"
        }
      },
      "font-size": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.font-size|label")
          },
          name: "font_size"
        }
      },
      "color": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.color|label")
          },
          name: "color"
        }
      },
      "top": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.top|label")
          },
          name: "top"
        }
      },
      "bottom": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.bottom|label")
          },
          name: "bottom"
        }
      },
      "left": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.left|label")
          },
          name: "left"
        }
      },
      "right": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.right|label")
          },
          name: "right"
        }
      },
      "margin-top": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.margin-top|label")
          },
          name: "margin_top"
        }
      },
      "margin-bottom": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.margin-bottom|label")
          },
          name: "margin_bottom"
        }
      },
      "margin-left": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.margin-left|label")
          },
          name: "margin_left"
        }
      },
      "margin-right": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.margin-right|label")
          },
          name: "margin_right"
        }
      },
      "padding-top": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.padding-top|label")
          },
          name: "padding_top"
        }
      },
      "padding-bottom": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.padding-bottom|label")
          },
          name: "padding_bottom"
        }
      },
      "padding-left": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.padding-left|label")
          },
          name: "padding_left"
        }
      },
      "padding-right": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.padding-right|label")
          },
          name: "padding_right"
        }
      },
      "border-top": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.border-top|label")
          },
          name: "border_top"
        }
      },
      "border-bottom": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.border-bottom|label")
          },
          name: "border_bottom"
        }
      },
      "border-left": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.border-left|label")
          },
          name: "border_left"
        }
      },
      "border-right": {
        group: "extended",
        field: {
          type: CUI.Input,
          form: {
            label: $$("pdf-creator.settings.node.border-right|label")
          },
          name: "border_right"
        }
      }
    };
    return this.styleSettings;
  };

  Node.prototype.initOpts = function() {
    Node.__super__.initOpts.call(this);
    return this.addOpts({
      name: {
        check: String
      },
      data: {
        check: "PlainObject",
        "default": {}
      },
      children: {
        check: (function(_this) {
          return function(value) {
            return CUI.util.isArray(value) && value.every(function(_value) {
              return _value instanceof ez5.PdfCreator.Node;
            });
          };
        })(this)
      }
    });
  };

  Node.prototype.name = function() {
    return this._name;
  };

  Node.prototype.readOpts = function() {
    this._name = this.constructor.getName();
    Node.__super__.readOpts.call(this);
    this.setData(this._data);
    return this;
  };

  Node.prototype.initChildren = function() {
    this.children = this.children.filter((function(_this) {
      return function(node) {
        return node.isParentAllowed(_this);
      };
    })(this));
    return Node.__super__.initChildren.call(this);
  };

  Node.prototype.renderContent = function() {
    var horizontalLayout;
    this.__internalNameLabel = new CUI.Label({
      text: this.__getInternalName(),
      appearance: "secondary"
    });
    horizontalLayout = new CUI.HorizontalLayout({
      center: {
        content: new CUI.Label({
          text: this.getDisplayName()
        })
      },
      right: {
        content: this.__internalNameLabel
      }
    });
    return horizontalLayout.DOM;
  };

  Node.prototype.allowRowMove = function(to_node, newFather) {
    if (newFather === this.getRoot()) {
      return false;
    }
    return true;
  };

  Node.prototype.isParentAllowed = function(pdfNode) {
    var ref;
    return pdfNode && ((ref = pdfNode.name()) === "div" || ref === "document");
  };

  Node.prototype.setData = function(data) {
    if (!data.custom_css) {
      data.custom_css = $$("pdf-creator.settings.node.document.custom-css|placeholder");
    }
    return this.__data = data;
  };

  Node.prototype.getDisplayName = function() {
    return $$("pdf-creator.node." + this._name + ".display-name");
  };

  Node.prototype.__getInternalName = function() {
    return this.getData().internal_name;
  };

  Node.prototype.renderPdfContent = function(opts) {
    var customStylesTag, data, element;
    element = this.__renderPdfContent(opts);
    this.__addStyles(element);
    CUI.dom.addClass(element, "pdf-node");
    CUI.dom.addClass(element, "pdf-node-" + (this.name()));
    data = this.getData();
    if (element && data.custom_css) {
      customStylesTag = this.__createStyleElement(data.custom_css);
      CUI.dom.append(opts.head, customStylesTag);
    }
    if (opts.selectedNode === this) {
      CUI.dom.addClass(element, "pdf-node-selected");
    }
    return element;
  };

  Node.prototype.getSettingsForm = function(opts) {
    var customCSSPanel, extraPanels, fields, generalPanel, group, panelField, panels, ref, ref1, settingsFields, styleFields;
    if (opts == null) {
      opts = {};
    }
    panels = [];
    settingsFields = this.__getSettingsFields();
    if (this.__showInternalNameField()) {
      settingsFields.unshift({
        type: CUI.Input,
        name: "internal_name",
        form: {
          label: $$("pdf-creator.settings.node.document.internal-name|label")
        },
        onDataChanged: (function(_this) {
          return function() {
            _this.__internalNameLabel.setText(_this.__getInternalName());
          };
        })(this)
      });
    }
    if (settingsFields.length > 0) {
      generalPanel = this.__createPanelField(settingsFields, {
        group: "general"
      });
      panels.push(generalPanel);
    }
    ref = this.__getStyleFieldSettings();
    for (group in ref) {
      styleFields = ref[group];
      fields = styleFields.map(function(_field) {
        return _field.field;
      });
      panelField = this.__createPanelField(fields, {
        group: group,
        closed: group !== "basic",
        name_in_form: true
      });
      panels.push(panelField);
    }
    extraPanels = this.getExtraSettingsPanels(opts);
    if (extraPanels.length > 0) {
      panels = panels.concat(extraPanels);
    }
    if (this.__isCustomCSSEnabled()) {
      fields = [
        {
          type: CUI.CodeInput,
          mode: "css",
          name: "custom_css",
          maximize_horizontal: true
        }
      ];
      customCSSPanel = this.__createPanelField(fields, {
        group: "custom_css",
        closed: true
      });
      panels.push(customCSSPanel);
    }
    if (panels.length === 0) {
      return new CUI.Label({
        text: $$("pdf-creator.settings.node.no-settings|label"),
        centered: true,
        appearance: "secondary"
      });
    }
    if ((ref1 = this.__form) != null) {
      ref1.destroy();
    }
    this.__form = new CUI.Form({
      fields: panels,
      data: this.getData(),
      onDataChanged: (function(_this) {
        return function(data, field) {
          _this.__onDataChanged(data, field);
          return typeof opts.onDataChanged === "function" ? opts.onDataChanged(data, field) : void 0;
        };
      })(this)
    });
    this.__form.start();
    return this.__form;
  };

  Node.prototype.__createPanelField = function(fields, opts) {
    var field, group;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isUndef(opts.closed)) {
      opts.closed = false;
    }
    if (CUI.util.isUndef(opts.name_in_form)) {
      opts.name_in_form = false;
    }
    group = opts.group;
    field = new CUI.DataFieldProxy({
      maximize_horizontal: true,
      element: (function(_this) {
        return function() {
          var panel;
          panel = new CUI.Panel({
            text: $$("pdf-creator.settings.node.group-" + group + "|label"),
            closed: opts.closed,
            radio: group,
            content: function() {
              var form;
              form = new CUI.Form({
                padded: true,
                data: _this.getData(),
                name: opts.name_in_form ? group : void 0,
                fields: fields
              });
              return form;
            }
          });
          return panel;
        };
      })(this)
    });
    return field;
  };

  Node.prototype.getExtraSettingsPanels = function(opts) {
    return [];
  };

  Node.prototype.getData = function(isForSaving) {
    if (isForSaving == null) {
      isForSaving = false;
    }
    return this.__data;
  };

  Node.prototype.getSaveData = function() {
    var _data, child, data, i, len, ref;
    _data = CUI.util.copyObject(this.getData(true), true);
    data = {
      name: this.name(),
      open: this.isOpen(),
      data: _data
    };
    if (!this.children) {
      return data;
    }
    data.children = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      child = ref[i];
      data.children.push(child.getSaveData());
    }
    return data;
  };

  Node.prototype.__isCustomCSSEnabled = function() {
    return true;
  };

  Node.prototype.__showInternalNameField = function() {
    return true;
  };

  Node.prototype.isCopyAllowed = function() {
    return true;
  };

  Node.prototype.copy = function() {
    var child, i, len, opts, ref;
    if (!this.isCopyAllowed()) {
      return;
    }
    opts = {
      data: CUI.util.copyObject(this.getData(), true),
      open: this.isOpen()
    };
    if (this.children) {
      opts.children = [];
      ref = this.children;
      for (i = 0, len = ref.length; i < len; i++) {
        child = ref[i];
        opts.children.push(child.copy());
      }
    }
    return new this.constructor(opts);
  };

  Node.prototype.__addStyles = function(element) {
    var data, fieldStyles, group, i, len, ref, ref1, style, styles, value;
    if (!element) {
      return;
    }
    styles = {};
    data = this.getData();
    ref = this.__getStyleFieldSettings();
    for (group in ref) {
      fieldStyles = ref[group];
      for (i = 0, len = fieldStyles.length; i < len; i++) {
        style = fieldStyles[i];
        value = (ref1 = data[group]) != null ? ref1[style.field.name] : void 0;
        if (CUI.util.isUndef(value)) {
          continue;
        }
        if (style.name === "class-name") {
          CUI.dom.addClass(element, value);
          continue;
        }
        if (style.name === "position-absolute") {
          if (value) {
            styles["position"] = "absolute";
          }
          continue;
        }
        styles[style.name] = value;
      }
    }
    CUI.dom.setStyle(element, styles);
  };

  Node.prototype.__getStyleFieldSettings = function() {
    var availableStyleSettings, group, i, len, style, styleName, styleSettings, styles;
    availableStyleSettings = ez5.PdfCreator.Node.getAvailableStyleSettings();
    styleSettings = this.__getStyleSettings();
    styles = {};
    for (i = 0, len = styleSettings.length; i < len; i++) {
      styleName = styleSettings[i];
      style = availableStyleSettings[styleName];
      if (!style) {
        continue;
      }
      group = style.group;
      if (!styles[group]) {
        styles[group] = [];
      }
      styles[group].push({
        field: style.field,
        name: styleName
      });
    }
    return styles;
  };

  Node.prototype.__getIdObjecttype = function() {
    return this.__getDocumentNode().getIdObjecttype();
  };

  Node.prototype.__getObjecttypeName = function() {
    var idObjecttype;
    idObjecttype = this.__getIdObjecttype();
    return ez5.schema.CURRENT._table_by_id[idObjecttype].name;
  };

  Node.prototype.__getMask = function() {
    return this.__getDocumentNode().getMask();
  };

  Node.prototype.__getLayoutData = function() {
    var documentData, layoutData;
    documentData = this.__getDocumentNode().getData();
    layoutData = {
      mode: documentData.layout_mode,
      rows: documentData.layout_rows,
      columns: documentData.layout_columns,
      rowGap: documentData.row_gap,
      columnGap: documentData.column_gap,
      innerBorder: documentData.inner_border,
      outerBorder: documentData.outer_border
    };
    return layoutData;
  };

  Node.prototype.__getDocumentNode = function() {
    var root;
    root = this.getRoot();
    if (root instanceof ez5.PdfCreator.Node.Document) {
      return root;
    }
    if (root.children[0] instanceof ez5.PdfCreator.Node.Document) {
      return root.children[0];
    }
    throw new Error("PdfNode.__getDocumentNode :: PdfDocumentNode not initialized correctly.");
  };

  Node.prototype.__createStyleElement = function(styles) {
    var styleElement;
    styleElement = CUI.dom.element("style");
    styles = styles.replace(/\r?\n|\r/g, "");
    CUI.dom.append(styleElement, styles);
    return styleElement;
  };


  /* Methods to be implemented */

  Node.prototype.__onDataChanged = function(data, field) {};

  Node.prototype.__getSettingsFields = function() {
    return [];
  };

  Node.prototype.__getStyleSettings = function() {
    return [];
  };

  Node.prototype.__renderPdfContent = function() {
    return console.warn(CUI.util.getObjectClass(this) + ".__renderPdfContent needs to be implemented.");
  };

  return Node;

})(CUI.ListViewTreeNode);

ez5.PdfCreator.plugins = new CUI.PluginRegistry({
  "class": ez5.PdfCreator.Node
});
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.ObjecttypePlugin = (function(superClass) {
  extend(ObjecttypePlugin, superClass);

  function ObjecttypePlugin() {
    return ObjecttypePlugin.__super__.constructor.apply(this, arguments);
  }

  ObjecttypePlugin.prototype.getTab = function() {
    var tab;
    if (!ez5.session.hasSystemRight("root", "plugin.pdf-creator.show_pdf_creator")) {
      return;
    }
    tab = {
      padded: false,
      name: "pdf_creator",
      text: $$("admin.objecttype.tab.pdf_creator"),
      content: (function(_this) {
        return function() {
          return _this.__renderPdfCreatorTab();
        };
      })(this)
    };
    return tab;
  };

  ObjecttypePlugin.prototype.onLoad = function() {
    var data;
    data = this.__getData();
    if (!data.objecttype.custom_data.webfrontend.pdf_creator) {
      data.objecttype.custom_data.webfrontend.pdf_creator = {};
    }
  };

  ObjecttypePlugin.prototype.getSaveData = function(saveData) {
    saveData.objecttype.custom_data.webfrontend.pdf_creator = this.__getDataWithoutEmptyFields();
  };

  ObjecttypePlugin.prototype.__renderPdfCreatorTab = function() {
    var pdfCreator, preferredMaskId, ref;
    preferredMaskId = (ref = ez5.schema.CURRENT._objecttype_by_name[this.__getData().objecttype.name]._preferred_mask) != null ? ref.mask_id : void 0;
    pdfCreator = new ez5.PdfCreator({
      data: this.__getData().objecttype.custom_data.webfrontend.pdf_creator,
      idObjecttype: this.__getData().objecttype._id,
      idMask: preferredMaskId
    });
    return pdfCreator.renderList();
  };

  ObjecttypePlugin.prototype.__getDataWithoutEmptyFields = function() {
    var data, i, len, ref, removeDisabledFieldsOnFieldsNode, template;
    data = CUI.util.copyObject(this.__getData().objecttype.custom_data.webfrontend.pdf_creator, true);
    this.__removedFields = 0;
    removeDisabledFieldsOnFieldsNode = (function(_this) {
      return function(parent) {
        var child, i, k, len, ref, results, v;
        ref = parent.children || [];
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          child = ref[i];
          if (child.children) {
            removeDisabledFieldsOnFieldsNode(child);
          }
          if (child.name === "field") {
            results.push((function() {
              var ref1, ref2, results1;
              ref2 = (ref1 = child.data) != null ? ref1.dataFields : void 0;
              results1 = [];
              for (k in ref2) {
                v = ref2[k];
                if (!v._enabled) {
                  this.__removedFields++;
                  results1.push(delete child.data.dataFields[k]);
                } else {
                  results1.push(void 0);
                }
              }
              return results1;
            }).call(_this));
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this);
    ref = data.templates || [];
    for (i = 0, len = ref.length; i < len; i++) {
      template = ref[i];
      removeDisabledFieldsOnFieldsNode(template.documentData);
    }
    if (this.__removedFields > 0) {
      console.warn(this.__removedFields + " fields were removed from templated because they are empty");
    }
    return data;
  };

  return ObjecttypePlugin;

})(ez5.ObjecttypePlugin);

Objecttype.plugins.registerPlugin(ez5.PdfCreator.ObjecttypePlugin);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Header = (function(superClass) {
  extend(Header, superClass);

  function Header() {
    return Header.__super__.constructor.apply(this, arguments);
  }

  Header.prototype.initOpts = function() {
    Header.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        check: "PlainObject",
        "default": {}
      }
    });
  };

  Header.prototype.readOpts = function() {
    var i, len, position, ref;
    Header.__super__.readOpts.call(this);
    this.__data = this._data;
    ref = ["left", "center", "right"];
    for (i = 0, len = ref.length; i < len; i++) {
      position = ref[i];
      if (this.__data[position]) {
        continue;
      }
      this.__data[position] = {};
    }
    return this;
  };

  Header.prototype.getData = function() {
    return this.__data;
  };

  Header.prototype.renderPdfContent = function(opts) {
    var _data, asset, assetImg, centerDiv, children, data, dfr, div, easID, fn, header, i, img, imgDiv, imgEl, j, k, len, len1, len2, loadPromises, node, object, position, ref, ref1, ref2, ref3, ref4, text, textNodes, width;
    if (!opts.header_loaded && !opts.preview) {
      loadPromises = [];
      ref = ["left", "center", "right"];
      fn = (function(_this) {
        return function(position) {
          var easID, imagePromise, ref1, ref2;
          if (_this.__data[position].type === "image" && ((ref1 = _this.__data[position]["file:eas_file"]) != null ? ref1._id : void 0)) {
            if (_this.__imagesData == null) {
              _this.__imagesData = {};
            }
            easID = (ref2 = _this.__data[position]["file:eas_file"]) != null ? ref2._id : void 0;
            if (_this.__imagesData[easID]) {
              return;
            }
            imagePromise = new CUI.Deferred();
            ez5.api.eas({
              type: "GET",
              data: {
                ids: JSON.stringify([easID]),
                format: "long"
              }
            }).done(function(easData) {
              var imageRequest, ref3, ref4, ref5;
              imageRequest = new CUI.XHR({
                method: "GET",
                url: Session.addToken((ref3 = easData[easID]) != null ? (ref4 = ref3.versions) != null ? (ref5 = ref4.original) != null ? ref5.url : void 0 : void 0 : void 0),
                responseType: "blob"
              });
              return imageRequest.start().done(function(blob) {
                var fileReader;
                fileReader = new FileReader();
                fileReader.readAsDataURL(blob);
                return fileReader.onloadend = function() {
                  _this.__imagesData[easID] = fileReader.result;
                  return imagePromise.resolve();
                };
              });
            });
            return loadPromises.push(imagePromise.promise());
          }
        };
      })(this);
      for (i = 0, len = ref.length; i < len; i++) {
        position = ref[i];
        fn(position);
      }
      if (loadPromises.length > 0) {
        dfr = new CUI.Deferred();
        CUI.whenAll(loadPromises).done((function(_this) {
          return function() {
            opts.header_loaded = true;
            return dfr.resolve(_this.renderPdfContent(opts));
          };
        })(this));
        return dfr.promise();
      }
    }
    header = CUI.dom.div("pdf-node-" + (this.constructor.name.toLowerCase()));
    if (!opts.preview) {
      CUI.dom.setStyle(header, {
        "font-size": "8px",
        "padding-left": "0.28in",
        "padding-right": "0.28in",
        "width": "calc(100% - 0.56in)"
      });
    }
    data = this.getData();
    ref1 = ["left", "center", "right"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      position = ref1[j];
      div = CUI.dom.div();
      CUI.dom.append(header, div);
      CUI.dom.setStyle(div, {
        "display": "inline-block",
        "text-align": position,
        "min-height": opts.preview ? "12px" : "8px"
      });
      _data = data[position];
      switch (_data.type) {
        case "logo":
          if (!ez5.PdfCreator.logoImage) {
            continue;
          }
          CUI.dom.setStyle(div, {
            "min-height": 0
          });
          img = CUI.dom.element("img", {
            src: ez5.PdfCreator.logoImage
          });
          imgDiv = CUI.dom.div("pdf-node-header-image-" + position);
          CUI.dom.append(imgDiv, img);
          if (!opts.preview) {
            CUI.dom.setStyle(img, {
              "height": "0.3in"
            });
          }
          CUI.dom.append(div, imgDiv);
          break;
        case "image":
          if (!opts.preview) {
            CUI.dom.setStyle(div, {
              "min-height": 0
            });
            easID = (ref2 = _data["file:eas_file"]) != null ? ref2._id : void 0;
            img = CUI.dom.element("img", {
              src: this.__imagesData[easID]
            });
            imgDiv = CUI.dom.div("pdf-node-header-image-" + position);
            CUI.dom.append(imgDiv, img);
            CUI.dom.setStyle(img, {
              "height": "0.3in"
            });
          } else {
            if (!((ref3 = _data["file:eas_file"]) != null ? ref3._id : void 0)) {
              continue;
            }
            asset = new AssetPlain({
              value: _data["file:eas_file"]
            });
            imgDiv = CUI.dom.div("pdf-node-header-image-" + position);
            assetImg = asset.getImgElement(null, "original", {
              for_print: true
            });
            imgEl = assetImg.querySelector("img");
            if (imgEl) {
              CUI.dom.append(imgDiv, imgEl);
            } else {
              CUI.dom.append(imgDiv, assetImg);
            }
          }
          CUI.dom.append(div, imgDiv);
          break;
        default:
          text = ez5.loca.getBestFrontendValue(_data.text);
          if (!text) {
            continue;
          }
          CUI.dom.setStyle(div, {
            "white-space": "nowrap",
            "overflow": "hidden"
          });
          text = text.replace(/%pageNumber%/g, "<span class='pageNumber'>1</span>");
          text = text.replace(/%totalPages%/g, "<span class='totalPages'>" + (((ref4 = opts.objects) != null ? ref4.length : void 0) || 1) + "</span>");
          object = opts.objects[0];
          text = ez5.PdfCreatorUtils.replaceTextPlaceholders(text, object);
          textNodes = CUI.dom.htmlToNodes(text);
          CUI.dom.append(div, textNodes);
      }
    }
    centerDiv = header.children[1];
    if (!centerDiv.hasChildNodes()) {
      centerDiv.remove();
    }
    children = CUI.dom.children(header);
    width = 100 / children.length;
    for (k = 0, len2 = children.length; k < len2; k++) {
      node = children[k];
      CUI.dom.setStyle(node, {
        "width": width + "%"
      });
    }
    return header;
  };

  Header.prototype.getSettingsFields = function(opts) {
    var forms, getFields, i, len, position, ref;
    if (opts == null) {
      opts = {};
    }
    getFields = (function(_this) {
      return function(position) {
        var customImageField, eas_field, formFields, logoFieldDisabled, logoText, onDataChanged, textField, textHintButton;
        textHintButton = new CUI.Button({
          text: $$("pdf-creator.settings.node.header.text|hint"),
          appearance: "flat",
          onClick: function() {
            var pop;
            pop = new ez5.HintPopover({
              element: textHintButton,
              content: new CUI.Label({
                text: $$("pdf-creator.settings.node.header.text.popover"),
                markdown: true
              }),
              padded: true
            });
            return pop.show();
          }
        });
        textField = {
          type: CUI.MultiInput,
          form: {
            label: $$("pdf-creator.settings.node.header.text|label"),
            hint: textHintButton
          },
          control: ez5.loca.getLanguageControl(),
          name: "text"
        };
        eas_field = new EASField({
          name: "file:eas_file"
        });
        customImageField = {
          type: CUI.DataFieldProxy,
          form: {
            label: $$("pdf-creator.settings.node.eas.file")
          },
          name: "file:eas_file",
          element: function(df) {
            return eas_field.renderEditorInput(df.getData(), null);
          }
        };
        if (position === "center" || !_this.__supportsLogo()) {
          return [textField];
        }
        onDataChanged = function(data, field) {
          var form;
          form = field.getForm();
          textField = form.getFieldsByName("text")[0];
          customImageField = form.getFieldsByName("file:eas_file")[0];
          switch (data.type) {
            case "logo":
              textField.hide(true);
              customImageField.hide(true);
              break;
            case "text":
              textField.show(true);
              customImageField.hide(true);
              break;
            default:
              textField.hide(true);
              customImageField.show(true);
          }
        };
        logoFieldDisabled = !ez5.PdfCreator.logoImage;
        if (logoFieldDisabled) {
          logoText = $$("pdf-creator.settings.node.header.select.option-logo-disabled|label");
        } else {
          logoText = $$("pdf-creator.settings.node.header.select.option-logo|label");
        }
        formFields = [
          {
            type: CUI.Select,
            name: "type",
            form: {
              label: $$("pdf-creator.settings.node.header.select|label")
            },
            options: [
              {
                text: $$("pdf-creator.settings.node.header.select.option-text|label"),
                value: "text"
              }, {
                text: logoText,
                value: "logo",
                disabled: logoFieldDisabled
              }, {
                text: $$("pdf-creator.settings.node.header.select.option-image|label"),
                value: "image"
              }
            ],
            onDataInit: function(field, data) {
              return onDataChanged(data, field);
            },
            onDataChanged: onDataChanged
          }, textField, customImageField
        ];
        return formFields;
      };
    })(this);
    forms = [];
    ref = ["left", "center", "right"];
    for (i = 0, len = ref.length; i < len; i++) {
      position = ref[i];
      forms.push({
        type: CUI.Form,
        form: {
          label: $$("pdf-creator.settings.node.header.title." + position + "|label")
        },
        render_as_block: true,
        name: position,
        fields: getFields(position),
        data: this.getData()
      });
    }
    return forms;
  };

  Header.prototype.__supportsLogo = function() {
    return true;
  };

  Header.prototype.getSaveData = function() {
    var data, i, len, position, ref;
    data = this.getData();
    ref = ["left", "center", "right"];
    for (i = 0, len = ref.length; i < len; i++) {
      position = ref[i];
      if (CUI.util.isEmpty(data[position]["file:eas_file"])) {
        delete data[position]["file:eas_file"];
      }
    }
    return CUI.util.copyObject(this.getData(), true);
  };

  return Header;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Footer = (function(superClass) {
  extend(Footer, superClass);

  function Footer() {
    return Footer.__super__.constructor.apply(this, arguments);
  }

  Footer.prototype.__supportsLogo = function() {
    return false;
  };

  return Footer;

})(ez5.PdfCreator.Header);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node.Body = (function(superClass) {
  extend(Body, superClass);

  function Body() {
    return Body.__super__.constructor.apply(this, arguments);
  }

  Body.prototype.__renderPdfContent = function(opts) {
    var body, chunkSize, div, grid, i, layoutData, len, object, objects, offset, ref;
    body = CUI.dom.$element("body");
    layoutData = this.__getLayoutData();
    if (!opts.preview && layoutData.outerBorder) {
      CUI.dom.addClass(body, "outer-border");
    }
    if (!this.children || !opts.objects) {
      return body;
    }
    if (layoutData.mode === "one_object") {
      if (opts.preview) {
        this.__renderObject(opts.objects[0], body, opts);
      } else {
        ref = opts.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          object = ref[i];
          div = CUI.dom.div("pdf-break-page pdf-node-body-single");
          this.__renderObject(object, div, opts);
          CUI.dom.append(body, div);
        }
      }
      return body;
    }
    chunkSize = layoutData.rows * layoutData.columns;
    offset = 0;
    while (opts.objects.length > offset) {
      objects = opts.objects.slice(offset, offset + chunkSize);
      grid = this.__renderPage(objects, opts);
      CUI.dom.append(body, grid);
      offset = offset + chunkSize;
    }
    return body;
  };

  Body.prototype.__renderPage = function(objects, opts) {
    var column, columnGap, columnIndex, columnWidth, div, grid, i, j, layoutData, objectIndex, ref, ref1, row, rowGap, rowHeight, rowIndex;
    grid = CUI.dom.div("pdf-node-body-grid");
    CUI.dom.addClass(grid, "pdf-break-page");
    layoutData = this.__getLayoutData();
    rowHeight = 100 / layoutData.rows;
    columnWidth = 100 / layoutData.columns;
    rowGap = layoutData.rowGap / 2;
    columnGap = layoutData.columnGap / 2;
    objectIndex = 0;
    for (rowIndex = i = 0, ref = layoutData.rows; 0 <= ref ? i < ref : i > ref; rowIndex = 0 <= ref ? ++i : --i) {
      row = CUI.dom.div("pdf-node-body-row");
      CUI.dom.setStyle(row, {
        height: rowHeight + "%"
      });
      if (layoutData.innerBorder) {
        CUI.dom.addClass(row, "inner-border");
      }
      for (columnIndex = j = 0, ref1 = layoutData.columns; 0 <= ref1 ? j < ref1 : j > ref1; columnIndex = 0 <= ref1 ? ++j : --j) {
        column = CUI.dom.div("pdf-node-body-column");
        CUI.dom.append(row, column);
        CUI.dom.setStyle(column, {
          width: columnWidth + "%",
          "padding": rowGap + "mm " + columnGap + "mm " + rowGap + "mm " + columnGap + "mm"
        });
        if (layoutData.innerBorder) {
          CUI.dom.addClass(column, "inner-border");
        }
        div = CUI.dom.div("pdf-node-body-column-inner");
        this.__renderObject(objects[objectIndex], div, opts);
        objectIndex++;
        CUI.dom.append(column, div);
      }
      CUI.dom.append(grid, row);
    }
    return grid;
  };

  Body.prototype.__renderObject = function(object, container, opts) {
    var contentOpts, i, len, node, ref;
    if (!container) {
      return;
    }
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      contentOpts = {
        object: object,
        selectedNode: opts.selectedNode,
        preview: opts.preview,
        head: opts.head
      };
      CUI.dom.append(container, node.renderPdfContent(contentOpts));
    }
  };

  return Body;

})(ez5.PdfCreator.Node);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node.Document = (function(superClass) {
  extend(Document, superClass);

  function Document() {
    return Document.__super__.constructor.apply(this, arguments);
  }

  Document.FONT_AWESOME_CDN = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css";

  Document.getName = function() {
    return "document";
  };

  Document.pageSizes = {
    "A3": {
      width: 29.7,
      height: 42
    },
    "A4": {
      width: 21,
      height: 29.7
    },
    "A5": {
      width: 14.8,
      height: 21
    },
    "B4": {
      width: 25,
      height: 35.3
    },
    "B5": {
      width: 17.6,
      height: 25
    },
    "Tabloid": {
      width: 27.9,
      height: 43.2
    },
    "Legal": {
      width: 21.6,
      height: 35.6
    },
    "Statement": {
      width: 14,
      height: 21.6
    },
    "Executive": {
      width: 18.4,
      height: 26.7
    },
    "Folio": {
      width: 21.6,
      height: 33
    },
    "Letter": {
      width: 21.6,
      height: 27.9
    }
  };

  Document.FILE_EXTENSION = ".pdf";

  Document.prototype.initOpts = function() {
    Document.__super__.initOpts.call(this);
    return this.addOpts({
      header: {
        check: "PlainObject",
        "default": {}
      },
      footer: {
        check: "PlainObject",
        "default": {}
      },
      idObjecttype: {
        check: "Integer",
        mandatory: true
      },
      idMask: {
        check: "Integer"
      }
    });
  };

  Document.prototype.readOpts = function() {
    Document.__super__.readOpts.call(this);
    this.setMask();
    this.__header = new ez5.PdfCreator.Header({
      data: this._header
    });
    this.__footer = new ez5.PdfCreator.Footer({
      data: this._footer
    });
    return this;
  };

  Document.prototype.isCopyAllowed = function() {
    return false;
  };

  Document.prototype.setMask = function(maskId) {
    var mask, maskName;
    if (maskId == null) {
      maskId = this._idMask;
    }
    mask = ez5.mask.CURRENT._mask_by_id[maskId];
    maskName = (mask != null ? mask.name : void 0) || "_all_fields";
    this.__mask = Mask.getMaskByMaskName(maskName, this._idObjecttype);
  };

  Document.prototype.isParentAllowed = function() {
    return false;
  };

  Document.prototype.setData = function(data) {
    Document.__super__.setData.call(this, data);
    if (!this.__data.page_size) {
      this.__data.page_size = "A4";
    }
    if (!this.__data.margin_top) {
      this.__data.margin_top = 1.016;
    }
    if (!this.__data.margin_bottom) {
      this.__data.margin_bottom = 1.016;
    }
    if (!this.__data.margin_left) {
      this.__data.margin_left = 1.016;
    }
    if (!this.__data.margin_right) {
      this.__data.margin_right = 1.016;
    }
    if (!this.__data.layout_mode) {
      this.__data.layout_mode = "one_object";
    }
    if (!this.__data.layout_rows) {
      this.__data.layout_rows = 1;
    }
    if (!this.__data.layout_columns) {
      this.__data.layout_columns = 1;
    }
    if (!this.__data.row_gap) {
      this.__data.row_gap = 0;
    }
    if (!this.__data.column_gap) {
      this.__data.column_gap = 0;
    }
    if (!this.__data.header_custom_html) {
      this.__data.header_custom_html = $$("pdf-creator.settings.node.document.header_custom_html|placeholder");
    }
  };

  Document.prototype.renderContent = function() {
    return (new CUI.Label({
      text: this.getDisplayName()
    })).DOM;
  };

  Document.prototype.renderPdf = function(_opts) {
    var body, html, opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts.call(this, _opts, "PdfDocumentNode.renderPdf", {
      preview: {
        check: Boolean,
        "default": false
      },
      objects: {
        check: function(obj) {
          return CUI.util.isArray(obj) && obj.every(function(_o) {
            return CUI.util.isPlainObject(_o);
          });
        }
      },
      selectedNode: {
        check: ez5.PdfCreator.Node
      },
      styles: {
        check: String
      },
      custom_css_url: {
        check: String
      }
    });
    html = this.__getHtmlElement(opts);
    opts.head = html.children[0];
    body = this.renderPdfContent(opts);
    CUI.dom.append(html, body);
    return html;
  };

  Document.prototype.__getHtmlElement = function(opts) {
    var customLinkTag, data, fontAwesomeLinkElement, head, headerCustomHTMLNodes, html, stylesTag;
    html = CUI.dom.$element("html", "pdf-print");
    head = CUI.dom.$element("head");
    CUI.dom.append(html, head);
    if (opts.preview) {
      CUI.dom.addClass(html, "pdf-print-preview");
    }
    data = this.getData();
    if (data.custom_css_url) {
      customLinkTag = this.__createLinkElement(data.custom_css_url);
      CUI.dom.append(head, customLinkTag);
    }
    if (opts.styles) {
      stylesTag = this.__createStyleElement(opts.styles);
      CUI.dom.append(head, stylesTag);
    }
    if (opts.custom_css_url) {
      customLinkTag = this.__createLinkElement(opts.custom_css_url);
      CUI.dom.append(head, customLinkTag);
    }
    headerCustomHTMLNodes = CUI.dom.htmlToNodes(data.header_custom_html);
    CUI.dom.append(head, headerCustomHTMLNodes);
    fontAwesomeLinkElement = this.__createLinkElement(ez5.PdfCreator.Node.Document.FONT_AWESOME_CDN);
    CUI.dom.append(head, fontAwesomeLinkElement);
    return html;
  };

  Document.prototype.__renderPdfContent = function(opts) {
    var body, div, footer, header;
    body = Document.__super__.__renderPdfContent.call(this, opts);
    if (opts.preview) {
      div = CUI.dom.div("pdf-print-preview-body");
      div.innerHTML = body.innerHTML;
      if (this.__getLayoutData().outerBorder) {
        CUI.dom.addClass(div, "outer-border");
      }
      CUI.dom.replace(body, div);
      CUI.dom.setStyle(body, {
        "padding-top": this.__data["margin_top"] + "cm",
        "padding-bottom": this.__data["margin_bottom"] + "cm",
        "padding-right": this.__data["margin_right"] + "cm",
        "padding-left": this.__data["margin_left"] + "cm"
      });
      footer = this.renderFooter(opts);
      header = this.renderHeader(opts);
      CUI.dom.prepend(body, header);
      CUI.dom.append(body, footer);
    }
    return body;
  };

  Document.prototype.getMaxCountPerPage = function() {
    var layoutData;
    layoutData = this.__getLayoutData();
    if (layoutData.mode === "one_object") {
      return 1;
    }
    return layoutData.rows * layoutData.columns;
  };

  Document.prototype.getFilename = function(object) {
    var filename;
    filename = this.getData().filename || $$("pdf-creator.settings.node.document.filename-dafault-value");
    filename = ez5.PdfCreatorUtils.replaceTextPlaceholders(filename, object);
    if (!filename.endsWith(ez5.PdfCreator.Node.Document.FILE_EXTENSION)) {
      filename += ez5.PdfCreator.Node.Document.FILE_EXTENSION;
    }
    return filename;
  };

  Document.prototype.getExtraSettingsPanels = function(opts) {
    var customHeadHTMLField, footerFields, headerFields, panels;
    if (opts == null) {
      opts = {};
    }
    headerFields = this.__header.getSettingsFields(opts);
    footerFields = this.__footer.getSettingsFields(opts);
    customHeadHTMLField = {
      type: CUI.CodeInput,
      mode: "html",
      name: "header_custom_html",
      maximize_horizontal: true
    };
    panels = [
      this.__createPanelField([customHeadHTMLField], {
        group: "header_custom_html",
        closed: true
      }), this.__createPanelField(headerFields, {
        group: "header",
        closed: true
      }), this.__createPanelField(footerFields, {
        group: "footer",
        closed: true
      })
    ];
    return panels;
  };

  Document.prototype.getTemplateName = function() {
    return this.getData().template_name;
  };

  Document.prototype.__getSettingsFields = function() {
    var colRowsOptions, data, fields, filenameHintButton, onLayoutChanged;
    data = this.getData();
    onLayoutChanged = (function(_this) {
      return function(field) {
        var _field, fieldName, fieldNames, form, i, len;
        form = field.getForm();
        fieldNames = ["inner_border", "layout_columns", "layout_rows", "row_gap", "column_gap"];
        for (i = 0, len = fieldNames.length; i < len; i++) {
          fieldName = fieldNames[i];
          _field = form.getFieldsByName(fieldName)[0];
          if (data.layout_mode === "one_object") {
            _field.disable();
          } else {
            _field.enable();
          }
        }
      };
    })(this);
    colRowsOptions = [
      {
        value: 1
      }, {
        value: 2
      }, {
        value: 3
      }, {
        value: 4
      }, {
        value: 5
      }, {
        value: 6
      }, {
        value: 7
      }, {
        value: 8
      }, {
        value: 9
      }, {
        value: 10
      }
    ];
    filenameHintButton = new CUI.Button({
      text: $$("pdf-creator.settings.node.document.filename|hint"),
      appearance: "flat",
      onClick: (function(_this) {
        return function() {
          var pop;
          pop = new ez5.HintPopover({
            element: filenameHintButton,
            content: new CUI.Label({
              text: $$("pdf-creator.settings.node.document.filename-popover"),
              markdown: true
            }),
            padded: true
          });
          return pop.show();
        };
      })(this)
    });
    fields = [
      {
        type: CUI.MultiInput,
        form: {
          label: $$("pdf-creator.settings.node.document.template-name|label")
        },
        control: ez5.loca.getLanguageControl(),
        name: "template_name"
      }, {
        type: CUI.Input,
        form: {
          label: $$("pdf-creator.settings.node.document.filename|label"),
          hint: filenameHintButton
        },
        name: "filename"
      }, {
        type: CUI.Select,
        form: {
          label: $$("pdf-creator.settings.node.document.orientation|label")
        },
        name: "orientation",
        options: [
          {
            text: $$("pdf-creator.settings.node.document.orientation.option.portrait"),
            value: false
          }, {
            text: $$("pdf-creator.settings.node.document.orientation.option.landscape"),
            value: true
          }
        ]
      }, {
        type: CUI.Select,
        form: {
          label: $$("pdf-creator.settings.node.document.paper-size|label")
        },
        name: "page_size",
        options: [
          {
            text: "A3 (29.7 cm x 42.0 cm)",
            value: "A3"
          }, {
            text: "A4 (21.0 cm x 29.7 cm)",
            value: "A4"
          }, {
            text: "A5 (14.8 cm x 21.0 cm)",
            value: "A5"
          }, {
            text: "B4 (25.0 cm x 35.3 cm)",
            value: "B4"
          }, {
            text: "B5 (17.6 cm x 25.0 cm)",
            value: "B5"
          }, {
            text: "Tabloid (27.9 cm x 43.2 cm)",
            value: "Tabloid"
          }, {
            text: "Legal (21.6 cm x 35.6 cm)",
            value: "Legal"
          }, {
            text: "Statement (14.0 cm x 21.6 cm)",
            value: "Statement"
          }, {
            text: "Executive (18.4 cm x 26.7 cm)",
            value: "Executive"
          }, {
            text: "Folio (21.6 cm x 33.0 cm)",
            value: "Folio"
          }, {
            text: "Letter (21.6 cm x 27.9 cm)",
            value: "Letter"
          }
        ]
      }, {
        type: CUI.NumberInput,
        form: {
          label: $$("pdf-creator.settings.node.document.margin-top|label")
        },
        name: "margin_top",
        decimals: 3,
        min: 0,
        max: 30
      }, {
        type: CUI.NumberInput,
        form: {
          label: $$("pdf-creator.settings.node.document.margin-bottom|label")
        },
        name: "margin_bottom",
        decimals: 3,
        min: 0,
        max: 30
      }, {
        type: CUI.NumberInput,
        form: {
          label: $$("pdf-creator.settings.node.document.margin-left|label")
        },
        name: "margin_left",
        decimals: 3,
        min: 0,
        max: 30
      }, {
        type: CUI.NumberInput,
        form: {
          label: $$("pdf-creator.settings.node.document.margin-right|label")
        },
        name: "margin_right",
        decimals: 3,
        min: 0,
        max: 30
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.document.outer-border|label")
        },
        name: "outer_border"
      }, {
        type: CUI.Options,
        name: "layout_mode",
        form: {
          label: $$("pdf-creator.settings.node.document.layout-mode|label")
        },
        radio: true,
        horizontal: false,
        options: [
          {
            text: $$("pdf-creator.settings.node.document.layout-mode.option.one-object"),
            value: "one_object"
          }, {
            text: $$("pdf-creator.settings.node.document.layout-mode.option.multiple-objects"),
            value: "multiple_objects"
          }
        ],
        onDataChanged: (function(_this) {
          return function(_data, field) {
            return onLayoutChanged(field);
          };
        })(this),
        onDataInit: onLayoutChanged
      }, {
        type: CUI.Select,
        name: "layout_rows",
        form: {
          label: $$("pdf-creator.settings.node.document.layout-rows|label")
        },
        options: colRowsOptions
      }, {
        type: CUI.Select,
        form: {
          label: $$("pdf-creator.settings.node.document.layout-columns|label")
        },
        name: "layout_columns",
        options: colRowsOptions
      }, {
        type: CUI.NumberInput,
        decimals: 2,
        min: 0,
        max: 100,
        form: {
          label: $$("pdf-creator.settings.node.document.row-gap|label")
        },
        name: "row_gap"
      }, {
        type: CUI.NumberInput,
        decimals: 2,
        min: 0,
        max: 100,
        form: {
          label: $$("pdf-creator.settings.node.document.column-gap|label")
        },
        name: "column_gap"
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.document.inner-border|label")
        },
        name: "inner_border"
      }, {
        type: CUI.Input,
        form: {
          label: $$("pdf-creator.settings.node.document.custom-css-url|label")
        },
        regexp: "^https?://[^/]+?([a-z0-9]|/.*)$",
        name: "custom_css_url"
      }
    ];
    return fields;
  };

  Document.prototype.__createLinkElement = function(url) {
    var linkElement;
    linkElement = CUI.dom.element("link", {
      rel: "stylesheet",
      href: url
    });
    return linkElement;
  };

  Document.prototype.__getPageSizes = function() {
    var pageSize;
    pageSize = this.getData().page_size;
    return ez5.PdfCreator.Node.Document.pageSizes[pageSize];
  };

  Document.prototype.getSaveData = function() {
    var data;
    data = Document.__super__.getSaveData.call(this);
    data.header = this.__header.getSaveData();
    data.footer = this.__footer.getSaveData();
    data.idObjecttype = this._idObjecttype;
    return data;
  };

  Document.prototype.getWidth = function() {
    var sizes;
    sizes = this.__getPageSizes();
    if (this.isLandscape()) {
      return sizes.height;
    } else {
      return sizes.width;
    }
  };

  Document.prototype.getHeight = function() {
    var sizes;
    sizes = this.__getPageSizes();
    if (this.isLandscape()) {
      return sizes.width;
    } else {
      return sizes.height;
    }
  };

  Document.prototype.isLandscape = function() {
    return this.getData().orientation;
  };

  Document.prototype.renderHeader = function(opts) {
    opts.documentNode = this;
    return this.__header.renderPdfContent(opts);
  };

  Document.prototype.renderFooter = function(opts) {
    opts.documentNode = this;
    return this.__footer.renderPdfContent(opts);
  };

  Document.prototype.getPaperWidth = function() {
    var sizes;
    sizes = this.__getPageSizes();
    return this.__cmToInch(sizes.width);
  };

  Document.prototype.getPaperHeight = function() {
    var sizes;
    sizes = this.__getPageSizes();
    return this.__cmToInch(sizes.height);
  };

  Document.prototype.getMargins = function(inchUnit) {
    var i, len, margin, margins, ref, side;
    if (inchUnit == null) {
      inchUnit = true;
    }
    margins = {};
    ref = ["top", "bottom", "left", "right"];
    for (i = 0, len = ref.length; i < len; i++) {
      side = ref[i];
      margin = this.__data["margin_" + side];
      margins[side] = inchUnit ? this.__cmToInch(margin) : margin;
    }
    return margins;
  };

  Document.prototype.__cmToInch = function(cm) {
    var inches;
    inches = cm / 2.54;
    return Math.round(inches * 10) / 10;
  };

  Document.prototype.__showInternalNameField = function() {
    return false;
  };

  Document.prototype.getMask = function() {
    return this.__mask;
  };

  Document.prototype.getIdObjecttype = function() {
    return this._idObjecttype;
  };

  Document.prototype.getHeader = function() {
    return this.__header;
  };

  Document.prototype.getFooter = function() {
    return this.__footer;
  };

  return Document;

})(ez5.PdfCreator.Node.Body);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node.Div = (function(superClass) {
  extend(Div, superClass);

  function Div() {
    return Div.__super__.constructor.apply(this, arguments);
  }

  Div.getName = function() {
    return "div";
  };

  Div.prototype.__renderPdfContent = function(opts) {
    var div, i, len, node, ref;
    div = CUI.dom.div();
    if (!this.children) {
      return div;
    }
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      CUI.dom.append(div, node.renderPdfContent(opts));
    }
    return div;
  };

  Div.prototype.__getStyleSettings = function() {
    return ["class-name", "height", "width", "display", "background", "font-size", "color", "position-absolute", "top", "bottom", "left", "right", "margin-top", "margin-bottom", "margin-left", "margin-right", "padding-top", "padding-bottom", "padding-left", "padding-right", "border-top", "border-bottom", "border-left", "border-right"];
  };

  return Div;

})(ez5.PdfCreator.Node);

ez5.PdfCreator.plugins.registerPlugin(ez5.PdfCreator.Node.Div);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node.FixedText = (function(superClass) {
  extend(FixedText, superClass);

  function FixedText() {
    return FixedText.__super__.constructor.apply(this, arguments);
  }

  FixedText.getName = function() {
    return "fixed_text";
  };

  FixedText.prototype.__renderPdfContent = function() {
    var data, span, text;
    data = this.getData();
    span = CUI.dom.span();
    text = ez5.loca.getBestFrontendValue(data.loca_fixed_text) || ("< " + ($$("pdf-creator.settings.node.fixed-text.empty-text")) + " >");
    CUI.dom.append(span, text);
    return span;
  };

  FixedText.prototype.__getSettingsFields = function() {
    var fields;
    fields = [
      {
        type: CUI.MultiInput,
        form: {
          label: $$("pdf-creator.settings.node.fixed-text.text|label")
        },
        control: ez5.loca.getLanguageControl(),
        name: "loca_fixed_text"
      }
    ];
    return fields;
  };

  FixedText.prototype.__getStyleSettings = function() {
    return ["class-name", "color", "font-size"];
  };

  return FixedText;

})(ez5.PdfCreator.Node.Div);

ez5.PdfCreator.plugins.registerPlugin(ez5.PdfCreator.Node.FixedText);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node.EAS = (function(superClass) {
  extend(EAS, superClass);

  function EAS() {
    return EAS.__super__.constructor.apply(this, arguments);
  }

  EAS.getName = function() {
    return "eas";
  };

  EAS.prototype.__renderPdfContent = function() {
    var asset, data, div, fileData, span;
    data = this.getData();
    div = CUI.dom.div();
    fileData = data["file:eas_file"];
    if (fileData != null ? fileData._id : void 0) {
      asset = new AssetPlain({
        value: fileData
      });
      CUI.dom.append(div, asset.getImgElement(null, "original", {
        for_print: true
      }));
    } else {
      span = CUI.dom.span();
      span.textContent = "< " + ($$("pdf-creator.settings.node.eas.no-file-selected")) + " >";
      CUI.dom.append(div, span);
    }
    return div;
  };

  EAS.prototype.__getSettingsFields = function() {
    var eas_field, fields;
    eas_field = new EASField({
      name: "file:eas_file"
    });
    fields = [
      {
        type: CUI.DataFieldProxy,
        form: {
          label: $$("pdf-creator.settings.node.eas.file")
        },
        name: "file:eas_file",
        element: (function(_this) {
          return function(df) {
            return eas_field.renderEditorInput(df.getData(), null);
          };
        })(this)
      }
    ];
    return fields;
  };

  EAS.prototype.getSaveData = function() {
    var _data, ref, saveData;
    saveData = EAS.__super__.getSaveData.call(this);
    _data = saveData.data;
    if (_data != null ? (ref = _data["file:eas_file"]) != null ? ref._id : void 0 : void 0) {
      _data["file:eas_file"] = {
        _id: _data["file:eas_file"]._id
      };
    } else {
      delete _data["file:eas_file"];
    }
    return saveData;
  };

  EAS.prototype.__getStyleSettings = function() {
    return ["class-name", "width"];
  };

  return EAS;

})(ez5.PdfCreator.Node.Div);

ez5.PdfCreator.plugins.registerPlugin(ez5.PdfCreator.Node.EAS);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node.Asset = (function(superClass) {
  extend(Asset, superClass);

  function Asset() {
    return Asset.__super__.constructor.apply(this, arguments);
  }

  Asset.getName = function() {
    return "asset";
  };

  Asset.prototype.__renderPdfContent = function(opts) {
    var _assets, asset, assetBrowser, assets, assetsOffset, columnsOffset, data, div, easFieldsData, f, fieldsToReset, i, icon, j, k, len, len1, mask, placeholder, ref, ref1, rowIndex, rows, span, width;
    if (!opts.object) {
      return;
    }
    mask = this.__getMask();
    data = this.getData();
    easFieldsData = data.easFields;
    fieldsToReset = [];
    if (mask.name() === "_all_fields") {
      mask.invokeOnFields("all", true, ((function(_this) {
        return function(f, _, depth) {
          var ref;
          if (!(f instanceof LinkedObject) || depth > 1 || !((ref = f.FieldSchema) != null ? ref.output : void 0)) {
            return;
          }
          f.FieldSchema.output.__standard_eas = f.FieldSchema.output.standard_eas;
          f.FieldSchema.output.standard_eas = {
            order: 1
          };
          return fieldsToReset.push(f);
        };
      })(this)));
    }
    assets = mask.getAssetsForBrowser(opts.object, "all") || [];
    assets = assets.filter((function(_this) {
      return function(asset) {
        var name;
        if (asset.value._linked_object) {
          name = asset.value._linked_object.fullName();
        } else {
          name = asset.field.fullName();
        }
        return easFieldsData[name];
      };
    })(this));
    for (i = 0, len = fieldsToReset.length; i < len; i++) {
      f = fieldsToReset[i];
      f.FieldSchema.output.standard_eas = f.FieldSchema.output.__standard_eas;
      delete f.FieldSchema.output.__standard_eas;
    }
    if (data.range) {
      assets.splice(data.range);
    }
    if (assets.length === 0) {
      if (!data.show_placeholder) {
        return;
      }
      placeholder = CUI.dom.div("pdf-node-asset-placeholder");
      icon = new CUI.Icon({
        icon: "fa-file-o"
      });
      CUI.dom.append(placeholder, icon);
      if (data.placeholder_text) {
        span = CUI.dom.span();
        span.textContent = data.placeholder_text;
        CUI.dom.append(placeholder, span);
      }
      return placeholder;
    }
    div = CUI.dom.div();
    rows = Math.ceil(assets.length / data.columns);
    width = 100 / data.columns;
    assetsOffset = 0;
    columnsOffset = data.columns;
    for (rowIndex = j = 0, ref = rows; 0 <= ref ? j < ref : j > ref; rowIndex = 0 <= ref ? ++j : --j) {
      _assets = assets.slice(assetsOffset, columnsOffset);
      if (_assets.length === 0) {
        break;
      }
      assetsOffset += data.columns;
      columnsOffset += data.columns;
      assetBrowser = new AssetBrowser({
        assets: _assets,
        for_print: true,
        printLowRes: data.low_resolution
      });
      ref1 = assetBrowser.getAssets();
      for (k = 0, len1 = ref1.length; k < len1; k++) {
        asset = ref1[k];
        CUI.dom.setStyle(asset.getElement(), {
          width: width + "%"
        });
      }
      CUI.dom.append(div, assetBrowser);
    }
    if (data.show_info) {
      CUI.dom.addClass(div, "pdf-node-asset-show-info");
    }
    return div;
  };

  Asset.prototype.__getSettingsFields = function() {
    var easFields, fields, form, mask;
    mask = this.__getMask();
    easFields = [];
    mask.invokeOnFields("all", true, ((function(_this) {
      return function(f, _, depth) {
        var easField;
        if (depth > 1) {
          return;
        }
        if (f instanceof EASColumn || (f instanceof LinkedObject && depth <= 1)) {
          if (f instanceof LinkedObject) {
            easField = f.linkMask().getEASFields("all")[0];
            if (!easField) {
              return;
            }
          }
          return easFields.push({
            type: CUI.Checkbox,
            text: f.fullNameLocalized(),
            form: {
              hint: f.fullName()
            },
            name: f.fullName()
          });
        }
      };
    })(this)));
    if (easFields.length === 0) {
      easFields.push({
        type: CUI.DataFieldProxy,
        element: function() {
          return new CUI.Label({
            text: $$("pdf-creator.settings.node.assets.no-eas-fields-available|label")
          });
        }
      });
    }
    form = new CUI.Form({
      form: {
        label: $$("pdf-creator.settings.node.assets.eas-fields|label")
      },
      name: "easFields",
      fields: easFields
    });
    fields = [
      form, {
        type: CUI.Select,
        form: {
          label: $$("pdf-creator.settings.node.assets.columns|label")
        },
        name: "columns",
        options: [
          {
            value: 1
          }, {
            value: 2
          }, {
            value: 3
          }, {
            value: 4
          }, {
            value: 5
          }
        ]
      }, {
        type: CUI.Select,
        form: {
          label: $$("pdf-creator.settings.node.assets.range|label")
        },
        name: "range",
        options: [
          {
            text: $$("pdf-creator.settings.node.assets.range.option-all|label"),
            value: null
          }, {
            text: $$("pdf-creator.settings.node.assets.range.option-first|label"),
            value: 1
          }
        ]
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.assets.low-resolution|label")
        },
        name: "low_resolution"
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.assets.show-info|label")
        },
        name: "show_info"
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.assets.show-placeholder|label")
        },
        name: "show_placeholder"
      }, {
        type: CUI.Input,
        form: {
          label: $$("pdf-creator.settings.node.assets.placeholder-text|label")
        },
        name: "placeholder_text"
      }
    ];
    return fields;
  };

  Asset.prototype.setData = function(data) {
    Asset.__super__.setData.call(this, data);
    if (!this.__data.easFields) {
      this.__data.easFields = {};
    }
    return this;
  };

  Asset.prototype.__getStyleSettings = function() {
    return ["class-name"];
  };

  return Asset;

})(ez5.PdfCreator.Node);

ez5.PdfCreator.plugins.registerPlugin(ez5.PdfCreator.Node.Asset);
// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreator.Node.Field = (function(superClass) {
  extend(Field, superClass);

  function Field() {
    return Field.__super__.constructor.apply(this, arguments);
  }

  Field.getName = function() {
    return "field";
  };

  Field.prototype.__renderPdfContent = function(_opts) {
    var data, element, fieldsRendererPlain, getFieldData, mask, objecttypeName, opts, selectedFields, span;
    data = this.getData();
    mask = this.__getMask();
    if (CUI.util.isEmpty(_opts.object)) {
      return;
    }
    selectedFields = ez5.PdfCreator.Node.Field.getSelectedFields(data);
    if (CUI.util.isEmpty(selectedFields)) {
      span = CUI.dom.span();
      span.textContent = $$("pdf-creator.settings.node.field.empty-fields");
      return span;
    }
    getFieldData = function(field, opts) {
      var fieldName;
      if (opts == null) {
        opts = {};
      }
      fieldName = ez5.PdfCreator.Node.Field.getFieldName(field, opts);
      if (!fieldName) {
        return;
      }
      return selectedFields[fieldName];
    };
    fieldsRendererPlain = new FieldsRendererPlain();
    mask.invokeOnFields("all", true, (function(_this) {
      return function(field) {
        if (!getFieldData(field)) {
          return;
        }
        return fieldsRendererPlain.addField(field);
      };
    })(this));
    objecttypeName = this.__getObjecttypeName();
    opts = {
      mode: _opts.mode || "detail",
      data: _opts.object[objecttypeName],
      top_level_data: _opts.object,
      inline_mode: data.linked_object_mode,
      nested_condensed_output: data.nested_condensed_output,
      for_print: true,
      removeBlockWidth: true,
      nested_only_first_row: data.nested_only_first_row,
      nested_display_as_table: data.nested_display_as_table,
      getLabel: (function(_this) {
        return function(field, _, opts) {
          var displayName, fieldData, label;
          fieldData = getFieldData(field, opts);
          displayName = ez5.loca.getBestFrontendValue(fieldData != null ? fieldData.label : void 0);
          label = new CUI.Label({
            "class": "ez5-field-label",
            text: displayName,
            multiline: true
          });
          return label;
        };
      })(this),
      isVisible: (function(_this) {
        return function(field, _, opts) {
          return !CUI.util.isEmpty(getFieldData(field, opts));
        };
      })(this)
    };
    element = fieldsRendererPlain.render(opts);
    if (data.row_format) {
      CUI.dom.addClass(element, "row-format");
    }
    if (data.hide_labels) {
      CUI.dom.addClass(element, "hide-labels");
    }
    return element;
  };

  Field.prototype.__getSettingsFields = function() {
    var fields, onHideLabelsChanged;
    this.__fieldSelectorButton = new CUI.FormButton({
      form: {
        label: $$("pdf-creator.settings.node.field.fields|label")
      },
      text: $$("pdf-creator.settings.node.field.select-fields.button"),
      disabled: !this.__getMask(),
      onClick: (function(_this) {
        return function() {
          return _this.__showFieldSelector();
        };
      })(this)
    });
    this.__fieldsSelectedLabel = new CUI.Label({
      text: ""
    });
    onHideLabelsChanged = function(data, field) {
      var rowFormatField;
      rowFormatField = field.getForm().getFieldsByName("row_format")[0];
      if (data.hide_labels) {
        rowFormatField.disable();
      } else {
        rowFormatField.enable();
      }
    };
    fields = [
      this.__fieldSelectorButton, new CUI.DataFieldProxy({
        element: (function(_this) {
          return function() {
            _this.__showSelectedFields();
            return _this.__fieldsSelectedLabel;
          };
        })(this)
      }), {
        type: CUI.Select,
        name: "linked_object_mode",
        form: {
          label: $$("pdf-creator.settings.node.field.linked-object-mode|label"),
          hint: $$("pdf-creator.settings.node.field.linked-object-mode|hint")
        },
        options: (function(_this) {
          return function() {
            return ["text", "short", "standard"].map(function(value) {
              return {
                text: $$("pdf-creator.settings.node.field.linked-object-mode.option." + value),
                value: value
              };
            });
          };
        })(this)
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.field.nested-condensed-output|label")
        },
        name: "nested_condensed_output"
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.field.nested_display_as_table|label")
        },
        name: "nested_display_as_table"
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.field.hide_labels|label")
        },
        name: "hide_labels",
        onDataChanged: onHideLabelsChanged
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.field.row_format|label")
        },
        name: "row_format",
        onDataInit: function(field, data) {
          return onHideLabelsChanged(data, field);
        }
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("pdf-creator.settings.node.field.nested_only_first_row|label")
        },
        name: "nested_only_first_row"
      }
    ];
    return fields;
  };

  Field.prototype.__getStyleSettings = function() {
    return ["class-name"];
  };

  Field.prototype.__showSelectedFields = function() {
    var data, selectedFields, selectedFieldsCount;
    data = this.getData();
    selectedFields = ez5.PdfCreator.Node.Field.getSelectedFields(data);
    selectedFieldsCount = Object.keys(selectedFields).length;
    if (selectedFieldsCount === 0) {
      this.__fieldsSelectedLabel.setText($$("pdf-creator.settings.node.field.select-fields.no-fields-selected|label"));
    } else {
      this.__fieldsSelectedLabel.setText($$("pdf-creator.settings.node.field.select-fields.count|label", {
        count: selectedFieldsCount
      }));
    }
  };

  Field.prototype.__showFieldSelector = function() {
    var data, fieldsForm, fieldsFormDiv, hideSystemFieldsCheckbox, mask, objecttypeManager, ref;
    mask = this.__getMask();
    this.__currentMask = mask;
    data = this.getData();
    data.dataFields = data.dataFields || {};
    objecttypeManager = new ObjecttypeManager();
    objecttypeManager.addMask(this.__getMask());
    objecttypeManager.initCommonFields("all");
    fieldsForm = new FieldsForm({
      otm: objecttypeManager,
      data: data.dataFields,
      treeNodeClass: PdfFieldsFormNode,
      acceptField: function(field, fieldsFormNodeFather) {
        if (!field.mask) {
          return false;
        }
        if (field instanceof CustomDataType && !field.isVisible("detail", {
          for_print: true
        })) {
          return false;
        }
        if (field instanceof CustomDataTypeMappingField) {
          return false;
        }
        return true;
      },
      treeOpts: {
        "class": 'cui-lv--has-datafields',
        maximize: false,
        rowMove: false,
        cols: ["auto"],
        fixedRows: 0
      }
    });
    fieldsFormDiv = fieldsForm.renderForm();
    fieldsForm.open();
    hideSystemFieldsCheckbox = new CUI.Checkbox({
      text: $$("pdf-creator.settings.node.field.select-fields.modal.checkbox.hide-system-fields"),
      onClick: function() {
        var hideShowColumns;
        hideShowColumns = function(nodes) {
          var i, len, node;
          for (i = 0, len = nodes.length; i < len; i++) {
            node = nodes[i];
            if (hideSystemFieldsCheckbox.isActive() && node.field.isTopLevelField()) {
              node.hide();
            } else {
              node.show();
            }
            if (node.children) {
              hideShowColumns(node.children);
            }
          }
        };
        hideShowColumns(fieldsForm.getNodes());
      }
    });
    hideSystemFieldsCheckbox.start();
    if ((ref = this.__fieldSelectorModal) != null) {
      ref.destroy();
    }
    this.__fieldSelectorModal = new CUI.Modal({
      "class": "pdf-creator-field-selector",
      pane: {
        header_left: new CUI.Label({
          text: $$("pdf-creator.settings.node.field.select-fields.modal.header")
        }),
        content: fieldsFormDiv,
        footer_left: hideSystemFieldsCheckbox,
        footer_right: new CUI.Button({
          text: $$("pdf-creator.settings.node.field.select-fields.modal.button"),
          primary: true,
          onClick: (function(_this) {
            return function() {
              _this.__showSelectedFields();
              CUI.Events.trigger({
                node: _this.__fieldSelectorButton,
                type: "data-changed",
                info: {
                  element: _this.__fieldSelectorButton
                }
              });
              _this.__fieldSelectorModal.hide();
            };
          })(this)
        })
      }
    });
    this.__fieldSelectorModal.show();
  };

  Field.prototype.getData = function(isForSaving) {
    var data, key, ref, value;
    if (isForSaving == null) {
      isForSaving = false;
    }
    data = Field.__super__.getData.call(this);
    if (!isForSaving) {
      return data;
    }
    if (data.dataFields) {
      ref = data.dataFields;
      for (key in ref) {
        value = ref[key];
        if (value._enabled) {
          continue;
        }
        delete data.dataFields[key];
      }
    }
    return data;
  };

  Field.getFieldName = function(field, opts) {
    var fieldName;
    if (opts == null) {
      opts = {};
    }
    if (!field.mask) {
      return;
    }
    if (opts._path) {
      fieldName = opts._path + "." + field.fullName(false);
    } else {
      fieldName = field.fullName();
    }
    return fieldName;
  };

  Field.getSelectedFields = function(data) {
    var fields, key, ref, value;
    if (!data.dataFields) {
      return {};
    }
    fields = {};
    ref = data.dataFields;
    for (key in ref) {
      value = ref[key];
      if (!value._enabled) {
        continue;
      }
      fields[key] = value;
    }
    return fields;
  };

  return Field;

})(ez5.PdfCreator.Node);

ez5.PdfCreator.plugins.registerPlugin(ez5.PdfCreator.Node.Field);
